Saturday 27 April 2019

Conditions


Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
For Example:
x = 2
print x == 2 # prints out True
print x == 3 # prints out False
print x < 3  # prints out True

Boolean Operators

The "and" and "or" boolean operators allow building complex boolean expressions, 
For Example:
name = "John"
age = 23
if name == "John" and age == 23:
    print "Your name is John, and you are also 23 years old."

if name == "John" or name == "Rick":
    print "Your name is either John or Rick."

True or False

Unfortunately it is not as easy in real life as it is in Python to differentiate between true and false: The following objects are evaluated by Python as False:
  1. numerical zero values (0, 0L, 0.0, 0.0+0.0j),
  2. the Boolean value False,
  3. empty strings,
  4. empty lists and empty tuples,
  5. empty dictionaries.
  6. plus the special value None.

All other values are considered to be True.

"In" Operator

The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:
name = "Rick"

        if name in ["John", "Rick"]:

            print "Your name is either John or Rick."
        

Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks do not need any termination. 

Here is an example for using Python's "if" statement using code blocks:

if (statement is true):
 (do something)
  ....
  ....
elif (another statement is true): # else if
 (do something else)
  ....
  ....
 else:
 (do another thing)
  ....
  ....
   

No comments:

Post a Comment

Online Compiler - Techie Delight TECHIE DELIGHT </> Bash (4.4) Bash (4.0) Basic (fbc 1.05.0) ...