Chapter3: Control Flow in Python
#SeekhoPython #HMWBAcademy
In this chapter, we’ll be learning the
- Conditionals.
- Comparison Operators.
- Loops (for & while)
- Break, Continue and Pass
Conditionals
Conditional expressions, involving keywords such as if, elif, and else, provide Python programs with the ability to perform different actions depending on a boolean condition: True or False. This section covers the use of Python conditionals, boolean logic, and ternary statements.
- Ternary Operator:
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 “surprising” behaviour use it (they may reverse the order).
- Some find it “unwieldy”, since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
n = 5
"Greater than 2" if n > 2 else "Smaller than or equal to 2"
# Out: 'Greater than 2'2. if, elif and else:
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 clause (you can have multiple elifs)
print("Number is smaller than 2.")
else: # Optional clause (you can only have one else)
print("Number is 2.")
# out: 'Number is bigger than 2Note: Using else if instead of elif will trigger a syntax error and is not allowed.
Truth Values:
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__ or __len__ methods return 0 or False
All other values in Python evaluate to True.
Boolean Logic Expressions:
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 expression if all expressions evaluate to True. Otherwise it returns the first value that evaluates to False:
>>> 1 and 2
2
>>> 1 and 0
0
>>> 1 and "Hello World"
"Hello World"
>>> "" and "Pancakes"
""Or operator:
The or operator evaluates the expressions left to right and returns the first value that evaluates to True or the last value (if none are True).
>>> 1 or 2
1
>>> None or 1
1
>>> 0 or []
[]Testing for multiple conditions:
A common mistake when checking for multiple conditions is to apply the logic incorrectly.
This example is trying to check if two variables are each greater than 2. The statement is evaluated as — if (a) and (b > 2). This produces an unexpected result because bool(a) evaluates as True when a is not zero.
>>> a = 1
>>> b = 6
>>> if a and b > 2:
... print('yes')
... else:
... print('no')
yesEach variable needs to be compared separately.
>>> if a > 2 and b > 2:
... print('yes')
... else:
... print('no')
noAnother, similar, mistake is made when checking if a variable is one of multiple values. The statement in this example is evaluated as — if (a == 3) or (4) or (6). This produces an unexpected result because bool(4) and bool(6) each evaluate to True
>>> a = 1
>>> if a == 3 or 4 or 6:
... print('yes')
... else:
... print('no')
yesAgain each comparison must be made separately
>>> if a == 3 or a == 4 or a == 6:
... print('yes')
... else:
... print('no')
noUsing the in operator is the canonical way to write this.
>>> if a in (3, 4, 6):
... print('yes')
... else:
... print('no')
noComparisons
Parameters:
x → First item to be compared
y → Second item to be compared
- Chain Comparison:
You can compare multiple items with multiple comparison operators with chain comparison. For Example:
x > y > zis just a short form of:
x > y and y > z2. Comparison by `is` vs `==`:
A common pitfall is confusing the equality comparison operators is and ==.
- a == b compares the value of a and b.
- a is b will compare the identities of a and b.
To Illustrate:
a = 'Python is fun!'
b = 'Python is fun!'
a == b # returns True
a is b # returns False
a = [1, 2, 3, 4, 5]
b = a # b references a
a == b # True
a is b # True
b = a[:] # b now references a copy of a
a == b # True
a is b # False [!!]Basically, is can be thought of as shorthand for id(a) == id(b).
Beyond this, there are quirks of the run-time environment that further complicate things. Short strings and small integers will return True when compared with is, due to the Python machine attempting to use less memory for identical objects.
a = 'short'
b = 'short'
c = 5
d = 5
a is b # True
c is d # TrueBut longer strings and larger integers will be stored separately.
a = 'not so short'
b = 'not so short'
c = 1000
d = 1000
a is b # False
c is d # FalseNote: You should use is to test for None. A use of is is to test for a “sentinel” (i.e. a unique object).
3. Greater than or less than (<, >):
x > y
x < yThese operators compare two types of values, they’re the less than and greater than operators. For numbers this simply compares the numerical values to see which is larger:
12 > 4
# True
12 < 4
# False
1 < 4
# TrueFor strings they will compare lexicographically, which is similar to alphabetical order but not quite the same.
"alpha" < "beta"
# True
"gamma" > "beta"
# True
"gamma" < "OMEGA"
# FalseIn these comparisons, lowercase letters are considered ‘greater than’ uppercase, which is why “gamma” < “OMEGA” is false. If they were all uppercase it would return the expected alphabetical ordering result:
"GAMMA" < "OMEGA"
# TrueEach type defines it’s calculation with the operators differently, so you should investigate what the operators mean with a given type before using it.
Get Hindi Medium Waala Banda’s stories in your inbox
Join Medium for free to get updates from this writer.
4. Not equal to ( !=):
x != y This returns True if x and y are not equal and otherwise returns False.
12 != 1
# True
12 != '12'
# True
'12' != '12'
# False5. Equal to (==):
x == yThis expression evaluates if x and y are the same value and returns the result as a boolean value. Generally both type and value need to match, so the int 12 is not the same as the string ‘12’.
12 == 12
# True
12 == 1
# False
'12' == '12'
# True
'spam' == 'spam'
# True
'spam' == 'spam '
# False
'12' == 12
# FalseNote that each type has to define a function that will be used to evaluate if two values are the same. For builtin types these functions behave as you’d expect, and just evaluate things based on being the same value. However custom types could define equality testing as whatever they’d like, including always returning True or always returning False.
Loops
As one of the most basic functions in programming, loops are an important piece to nearly every programming language. Loops enable developers to set certain portions of their code to repeat through a number of loops which are referred to as iterations. This topic covers using multiple types of loops and applications of loops in Python.
- for loop:
for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from the collection.
for i in [0, 1, 2, 3, 4]:
print(i)The above for loop iterates over a list of numbers.
Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output will be as follow:
0
1
2
3
4range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:
for i in range(5):
print(i)gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0.
Iterating Over List:
for x in ['one', 'two', 'three', 'four']:
print(x)This will print out the elements of the list:
one
two
three
fourIf you want to loop though both the elements of a list and have an index for the elements as well, you can use Python’s enumerate function:
for index, item in enumerate(['one', 'two', 'three', 'four']):
print(index, '::', item)enumerate will generate tuples, which are unpacked into index (an integer) and item (the actual value from the list). The above loop will print
(0, '::', 'one')
(1, '::', 'two')
(2, '::', 'three')
(3, '::', 'four')Loops with an “else” clause:
The for and while compound statements (loops) can optionally have an else clause (in practice, this usage is fairly rare). The else clause only executes after a for loop terminates by iterating to completion, or after a while loop terminates by its conditional expression becoming false
for i in range(3):
print(i)
else:
print('done')
i = 0Output:
0
1
2
doneThe else clause does not execute if the loop terminates some other way (through a break statement or by raising an exception):
for i in range(2):
print(i)
if i == 1:
break
else:
print('done')Output:
0
12. While Loop:
A while loop will cause the loop statements to be executed until the loop condition is falsey. The following code will execute the loop statements a total of 4 times.
i = 0
while i < 4:
#loop statements
i = i + 1While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if some condition has been met. The following loop will continue to execute until myObject is ready.
myObject = anObject()
while myObject.isNotReady():
myObject.tryToGetReady()If the condition is always true the while loop will run forever (infinite loop) if it is not terminated by a break or return statement or an exception.
while True:
print "Infinite loop"Output:
Infinite loop
Infinite loop
Infinite loop
Infinite loop
Infinite loop
Infinite loop
...3. break, continue and pass:
break Statement: When a break statement executes inside a loop, control flow “breaks” out of the loop immediately:
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1The loop conditional will not be evaluated after the break statement is executed. Note that break statements are only allowed inside loops, syntactically. A break statement inside a function cannot be used to terminate loops that called that function.
Executing the following prints every digit until number 4 when the break statement is met and the loop stops:
0
1
2
3
4
Breaking from loopbreak statements can also be used inside for loops, the other looping construct provided by Python:
for i in (0, 1, 2, 3, 4):
print(i)
if i == 2:
breakExecuting this loop now prints:
0
1
2continue Statement:
A continue statement will skip to the next iteration of the loop bypassing the rest of the current block but continuing the loop.
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
""" Output:
0
1
3
5
"""
Note that 2 and 4 aren’t printed, this is because continue goes to the next iteration instead of continuing on to print(i) when i == 2 or i == 4
pass statement:
pass is a null statement for when a statement is required by Python syntax (such as within the body of a for or while loop), but no action is required or desired by the programmer. This can be useful as a placeholder for code that is yet to be written.
for x in range(10):
pass #we don't want to do anything, or are not ready to do anything here, so we'll passIn this example, nothing will happen. The for loop will complete without error, but no commands or code will be actioned. pass allows us to run our code successfully without having all commands and action fully implemented.
Similarly, pass can be used in while loops, as well as in selections and function definitions etc.
while x == y:
pass






