= 10
a
if a < 10:
print("lt")
elif a == 10:
print("eq")
else:
print("gt")
L04: Conditionals, loops
Lecture Overview
Conditional Statements (if / elif / else)
Conditional statements allow us to tell Python to run certain lines of code (statements) only if some condition is satisfied. The syntax for conditional statements in python is as follows:
if <condition>:
<statement(s)>
elif <condition>:
<statement(s)>
else:
<statement(s)>
Note that the “<>” symbols should not appear in your code. They just signify places where you are expected to input something.
Each conditional statement must have exactly one “if” condition, any number of “elif” conditions (as long as they are all between “if” and “else”) and zero or one “else” statements. Each if/elif/else block is called a branch of that conditional statement.
Let’s work through some examples to show exactly how these conditional statements function:
Indentation matters: all lines of code under a particular if/else branch must have the same indent (which must be deeper than the indent of the if statement itself):
if 1 > 0:
print("this won't work")
if 1 > 0:
print("this")
print("won't work either")
The order of the conditions matters: only the statements under the first true condition (from the top) will be executed:
if 1==1:
print(1)
elif 2==2:
print(2)
elif 3==3:
print('asd')
Anything that has a truth value (i.e. evaluates to True or False) can be supplied as the condition after an “if” or “elif” (but not after “else”):
= 1 in [1,2]
a print(a)
if a:
print("it's in")
From the Python official documentation (https://docs.python.org/3/library/stdtypes.html):
Here are most of the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: ’’, (), [], {}, set(), range(0)
if False:
print(1)
if 0:
print(2)
if []:
print(3)
if True:
print(1)
if 1:
print(2)
if ['asd']:
print(3)
Compound conditions (joined by logical operators like “and”, “or”) can be supplied on any “if” and “elif”. Just make sure each condition is in its own set of parentheses:
if (1 > 2) or (2 > 0):
print("this")
Iteration (‘for’ loops)
The concept of iteration is fundamental to all programming languages. Iteration is one of the key reasons why programming is so powerful: it allows us to do something repeatedly, with only a slight modification each time around. We’ll explain what that means using lots of examples below, but first, here is the general syntax of a “for” loop - the most widely used method of iteration in Python:
for <var> in <iterable>:
<statement(s)>
For example, in the loop below, <var> is i, <iterable> is the list [1, ‘a’, [2,3]], and <statement(s)> is the single line of code “print(i)”
for i in [1, 'a', [2,3]]:
print(i)
The for loop “iterates over” (i.e. cycles through the elements of) the list [1, ‘a’, [2,3]]. Each time around, it assigns that element the name i, and then it executes the line(s) of code in the “body” of the for loop (i.e. “print(i)”) in our example.
So the for loop above is equivalent to the following code:
= 1
i print(i)
= 'a'
i print(i)
= [2,3]
i print(i)
Just like with “if” statements, the body of the loop can contain multiple lines of code (statements), as long as they have the same indent:
for i in [1,2,3]:
= i**2
x print(x)
Can you tell why the following code does not produce the same output?
for i in [1,2,3]:
= i**2
x print(x)
The “iterable” that we iterate over with the for loop, does not have to be a list. It can be any data structure with elements over which Python knows how to cycle (e.g. a tuple, a dictionary, a string, and many others):
# Iterating over a string:
for x in 'abc':
print(x)
# Iterating over a tuple:
for x in (1,2,3):
print(x)
# Iterating over a dict
= {1: 'a', 2: 'b'}
myDict
for x in myDict:
print(x)
Note that the loop only iterates over the “keys” of the dictionary. If we want access to the “values” of the dictionary we have to use the “values()” attribute for dictionaries:
print(myDict.values())
for x in myDict.values():
print(x)
This dictionary example shows you that the behavior of the loop depends crucially on the nature of the iterable you supply it (i.e. Python may iterate over objects of different types in different ways). The easiest way to see how Python iterates over objects of a particular type is to just create an example of such a type and then print its elements in a loop.
For example, if you were curious how Python iterates over a nested list (a list of lists), you can use something like this:
= [[1,2],[3,4],[5,6]]
m for i in m:
print(i)
The “break” statement
The “break” command tells Python to exit the loop regardless of weather it has finished looping through the elements of its iterable:
for i in [1,2,3]:
break
print(i) #this line never gets executed
for i in [1,2,3]:
if i < 3:
print(i)
else:
break #this line is only exectured if (i < 3) is False
The range() function
A range is another type of iterable that is commonly used in for loops. Ranges are sequences of integers created using the range() function.
The syntax of the range function is as follows:
range(<start>, <end>, <step>)
This gives us all the integers from “start” to “end” (excluding “end”) in increments of “step”. Both the “start” and “step” arguments can be omitted, but “end” must be supplied.
Let’s work through some examples:
for i in range(1,10,3): #"start" is 1, "end" is 10, "step" is 3
print(i)
for i in range(3): #here we only supply the "end" of the range. note how 3 is excluded
print(i)
List comprehensions
If we want to apply some simple transformation to all the elements in an iterable and store these transformations in a new list, we can use a Python construct called list comprehensions.
The syntax for list comprehensions is as follows:
<newList> = [<statement> for i in <existingList> if <condition> ]
In the above notation, Python goes through all the elements in “existingList” that satisfy “condition”, inputs each of these elements into “statement” (i.e. some Python code) one by one, and collects the results of these statements into a new list called “newList”.
That sounds pretty complicated but it really isn’t once you look at some examples:
= [1,2,3]
myiter = [i**2 for i in myiter if i<3]
sq print(sq)
The if statement is not required:
= [i**2 for i in myiter]
sq print(sq)