Tutorial by Examples

In Python you can define a series of conditionals using if for the first one, elif for the rest, up until the final (optional) else for anything not caught by the other conditionals. number = 5 if number > 2: print("Number is bigger than 2.") elif number < 2: # Optional cl...
The ternary operator is used for inline conditional expressions. It is best used in simple, concise operations that are easily read. The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "s...
if condition: body The if statements checks the condition. If it evaluates to True, it executes the body of the if statement. If it evaluates to False, it skips the body. if True: print "It is true!" >> It is true! if False: print "This won't get printed.....
if condition: body else: body The else statement will execute it's body only if preceding conditional statements all evaluate to False. if True: print "It is true!" else: print "This won't get printed.." # Output: It is true! if False: print &...
Boolean logic expressions, in addition to evaluating to True or False, return the value that was interpreted as True or False. It is Pythonic way to represent logic that might otherwise require an if-else test. And operator The and operator evaluates all expressions and returns the last expressi...
The following values are considered falsey, in that they evaluate to False when applied to a boolean operator. None False 0, or any numerical value equivalent to zero, for example 0L, 0.0, 0j Empty sequences: '', "", (), [] Empty mappings: {} User-defined types where the __bool__ o...
Python 2 includes a cmp function which allows you to determine if one object is less than, equal to, or greater than another object. This function can be used to pick a choice out of a list based on one of those three options. Suppose you need to print 'greater than' if x > y, 'less than' if x &...
Python allows you to hack list comprehensions to evaluate conditional expressions. For instance, [value_false, value_true][<conditional-test>] Example: >> n = 16 >> print [10, 20][n <= 15] 10 Here n<=15 returns False (which equates to 0 in Python). So what Python i...
You'll often want to assign something to an object if it is None, indicating it has not been assigned. We'll use aDate. The simplest way to do this is to use the is None test. if aDate is None: aDate=datetime.date.today() (Note that it is more Pythonic to say is None instead of == None.) ...

Page 1 of 1