Control statements in Python
1 Conditions
1.1 Blocks
What is a block?
It is a group of statements.
Python uses spaces and/or tabs to create a block.
The standard width of a tab is 8 spaces, but many editors support different widths.
I would not mix tabs and spaces for Python blocks.
How many spaces do you need? You can use any number of spaces, but just be careful to be consistent in the same block. We’ll see how blocks work in the next section.
1.2 if
The if
statement executes its block only if the condition is truthy
Try
x = int(input("x? "))
if x == 0:
print('x is 0') # use 2 spaces for this block
What about this?
x = int(input("x? "))
if x > 0:
print(x) # 2 spaces
print('x is 0') # 4 spaces in the same block, inconsistent!
Try
x = int(input("x? "))
if x == 0:
print('x is 0') # 2 spaces
if x < 0:
print(x) # 4 spaces
print('x is negative') # 4 spaces, consistent
if x > 0:
print(x) # 8 spaces
print('x is positive') # 8 spaces, consistent
1.3 else
The else
statement executes its block if the previous if
or elif
condition is falsy. Compare these two:
x = int(input("x? "))
if x <= 0:
print('x is not positive')
if x > 0: # this condition is NOT of the above
print('x is positive')
x = int(input("x? "))
if x <= 0:
print('x is not positive')
else: # NOT x <= 0
print('x is positive')
1.4 elif
The elif
statement is a shorthand for an if
statement inside an else
block. You just need one less block. Compare these two.
x = int(input("x? "))
if x <= 0:
print('x is not positive')
else:
if x > 5:
print('x > 5')
x = int(input("x? "))
if x <= 0:
print('x is not positive')
elif x > 5:
print('x > 5')
A series of if
, elif
, and else
is possible, but there should be only one else
at the end logically.
x = int(input("x? "))
if x <= 0:
print('x is not positive')
elif x > 5:
print('x > 5')
else:
print('0 < x <= 5')
1.5 Exercise: Branch
Try this code. Can you control the branching (if
-elif
-else
) algorithm by changing your input to print a certain string (one
, two
, or other
)?
x = input("Enter data: ")
if x == 1:
print("one")
elif x == 2:
print("two")
else:
print("other")
1.6 Exercise: Debug branching
Did the branching exercise work for you? Why or why not? Can you debug it?
1.7 Exercise: Print the range of an integer using if
input()
, print()
, if
You need to test if x
is between $(0,2]$, $(2,4]$, $(4,6]$, $(6,8]$, or $(8,10]$. What is your algorithm using if
statements? Here, $(a, b]$ means that a number is greater than $a$, but less than or equal to $b$. That is $a<\text{number}\leq b$.
Does this code work? Why or why not? How would you fix it?
x = int(input("x? "))
if x <= 0:
print('x <= 0')
if x > 0:
print('x in (0,2]')
if x > 2:
print('x in (2,4]')
if x > 4:
print('x in (4,6]')
if x > 6:
print('x in (6,8]')
if x > 8:
print('x in (8,10]')
if x > 10:
print('x > 10')
x = int(input("x? "))
if x <= 0:
print('x <= 0')
if x > 0 and x <= 2:
print('x in (0,2]')
if x > 2 and x <= 4:
print('x in (2,4]')
if x > 4 and x <= 6:
print('x in (4,6]')
if x > 6 and x <= 8:
print('x in (6,8]')
if x > 8 and x <= 10:
print('x in (8,10]')
if x > 10:
print('x > 10')
x = int(input("x? "))
if x <= 0:
print('x <= 0')
if 0 < x <= 2: # chain and's
print('x in (0,2]')
if 2 < x <= 4:
print('x in (2,4]')
if 4 < x <= 6:
print('x in (4,6]')
if 6 < x <= 8:
print('x in (6,8]')
if 8 < x <= 10:
print('x in (8,10]')
if x > 10:
print('x > 10')
1.8 Exercise: Print the range of an integer using if
, elif
, and else
elif
, else
Let’s try the same algorithm again, but you’re a little smarter now. You need to test if x
is between $(0,2]$, $(2,4]$, $(4,6]$, $(6,8]$, or $(8,10]$.
x = int(input("x? "))
if x <= 0:
print('x <= 0')
elif x <= 2:
print('x in (0,2]')
elif x <= 4:
print('x in (2,4]')
elif x <= 6:
print('x in (4,6]')
elif x <= 8:
print('x in (6,8]')
elif x <= 10:
print('x in (8,10]')
else:
print('x > 10')
2 Loops
2.1 for
A for
loop iterates each item in an array-like object and runs the block.
# tuple
for i in (1, 2, 3):
print(i)
# list
for i in [1, 2, 3]:
print(i)
# range
for i in range(1, 4):
print(i)
2.2 while
A while
loop tests a given condition and loops the block as long as the condition is truthy.
What does this code print?
x = 1
while x <= 10:
print(x)
x = x + 1
2.3 continue
While inside a for
or while
loop, you may want to skip the rest of the block and move to the next iteration. In this case, use the continue
statement.
What is this code supposed to print? Does it even work as intended? Why not?
x = 1
while x <= 10:
if x % 2:
continue
print(x)
x = x + 1
x = 1
while x <= 10:
if x % 2:
x = x + 1
continue
print(x)
x = x + 1
2.4 break
Use the break
statement to get out a for
or while
loop without looping it further. You only exist one level of a loop.
What does this code do?
for x in range(1, 10):
for y in range(1, 10):
if y < 3:
continue
if y > 6:
break # exit the y loop only
print(x+y)
2.5 Exercise: for
and list
Iterate over each element in a list and print it.
A = [12, 34, 45, 67]
for a in A:
print(a)
2.6 Exercise: for
and forward indexing
Let’s iterate over a list and print its elements using indexing.
A = [12, 34, 45, 67]
n = len(A)
for i in range(n):
a = A[i]
print(a)
2.7 Exercise: for
and reverse indexing
Let’s iterate over a list and print its elements using reverse indexing.
A = [12, 34, 45, 67]
n = len(A)
for i in range(n):
a = A[n-1-i]
print(a)
2.8 Exercise: Summation using a for
loop
Summation from $1$ to $n$ i expressed as $x=\sum_{i=1}^n i$. What this equation means is that we add all $i$'s from $1$ up to $n$ and assign that result to $x$. Let’s try $n=2$ first. That’s $x=\sum_{i=1}^2 i=1+2=3$. If $n=3$, $x=\sum_{i=1}^3 i=1+2+3=6$. If $n=4$, $x=\sum_{i=1}^4 i=1+2+3+4=10$. Let’s write the $n=2$ case in Python.
x = 0 # we need this variable x called an accumulator because
# we're going to accumulate the values of i in this variable
for i in range(1, 3): # we start from 1 and stop at 2;
# guess why you need 3, not 2
x = x + i
print(x)
2.9 Exercise: Summation using a while
loop
What about the while
loop version of summation for $n=2$? Let’s try.
i = 1
x = 0
while i <= 2:
x = x + i
i = i + 1 # you have to advance i by i yourself because while doesn't do this for you
print(x)
3 Homework: Summation
Take an integer $n$ from the keyboard, calculate and print $x=\sum_{i=1}^n i$. Assume that the user always enters a positive integer, so you don’t have to handle non-positive integer inputs. Implement two versions of this program using for
and while
loops. Create two separate files following this naming convention: sum_for.py
and sum_while.py
. Zip these two files into FirstLastname_sum.zip
and upload it to the D2L assignment folder.
4 Homework: Random integers
- Read n, a, b from the keyboard.
- Generate two random integers between a and b inclusively.
- If the first random integer is greater than the second one, print the first plus second.
- If the first random integer is less than the second one, print the first minus second.
- If the first random integer is equal to the second one, print the multiplication of both.
- Repeat steps 2-5 n times.
Submit your code in FirstLastname_randint.py
.