Introductory Python: If, While, and For
We often wish to tell the computer instructions involving the words "if," "while," and "for."
This post is part of the series Introduction to Python Programming.
Want to get notified about new posts? Join the mailing list and follow on X/Twitter.
When programming, we often wish to tell the computer instructions such as:
- If thing X happens, then do thing Y.
- While thing X is true, do thing Y.
- For each item in collection X, do thing Y.
And we can, using these words (if, while, and for) exactly!
If
An if
statement involves first checking whether some value is true, and if it is, then running some code indented below the if
statement.
Otherwise, if the value is false, the indented code is not executed.
X = True
if X:
print('This will only print if X is True.')
OUTPUT
------
This will only print if X is True.
X = False
if X:
print('This will only print if X is True.')
OUTPUT
------
(empty)
The value checked by the if statement can also be an expression, as long as it ultimately evaluates to a boolean True/False value.
X = 5
if X > 3: # true because 5 > 3
print('This will only print if X is greater than 3')
OUTPUT
------
This will only print if X is greater than 3
X = 1
if X > 3: # true because 5 > 3
print('This will only print if X is greater than 3')
OUTPUT
------
(empty)
If
statements can also be nested within each other.
A = 3
B = 2
if A > 0: # true because 3 > 0
print('This will only print if A is greater than 0.')
if A + B > 0: # true because 3+2=5 > 0
print('This will only print if both A is greater than 0, and A+B is also greater than 0.')
OUTPUT
------
This will only print if A is greater than 0.
This will only print if both A is greater than 0, and A+B is also greater than 0.
A = 3
B = -5
if A > 0: # true because 3 > 0
print('This will only print if A is greater than 0.')
if A + B > 0: # true because 3+2=5 > 0
print('This will only print if both A is greater than 0, and A+B is also greater than 0.')
OUTPUT
------
This will only print if A is greater than 0.
A = -2
B = 4
if A > 0: # true because 3 > 0
print('This will only print if A is greater than 0.')
if A + B > 0: # true because 3+2=5 > 0
print('This will only print if both A is greater than 0, and A+B is also greater than 0.')
OUTPUT
------
(empty)
Exercise 1
Change the values of the variables A
, B
, C
, and D
so that 'Success'
prints to the screen.
A = 1
B = 2
C = 3
D = 0
if A < 0:
if A + B == 5:
if C * D != 0:
print('Success')
Else
If
statements can include an else
afterward, containing code that is executed if the value checked by the if
turns out to be False
.
X = False
if X:
print("'if' code was executed because X was True.")
else:
print("'else' code was executed because X was NOT True.")
OUTPUT
------
'else' code was executed because X was NOT True.'
Exercise 2
Change the values of the variables A
, B
, C
, and D
so that 'Success'
prints to the screen.
A = 1
B = 2
C = 3
D = 4
if A + B >= 0:
pass # "pass" just means to do nothing if it is executed
else:
if C + D <= 10:
pass
else:
print('Success')
While
Like an if
statement, a while
loop involves first checking whether some value is true, and if it is, then running some code indented below the while
.
However, whereas an if
statement just runs the code a single time, the while
loop continues to run the code until the checked value becomes False
.
For example, the while
loop below increases the variable counter
each time it runs.
Initially, counter
is set to 0
, so the condition counter < 3
is initially true.
However, after a few iterations, the counter’s value reaches 3
, at which point the condition counter < 3
is no longer true and the while
loop stops running.
counter = 0
while counter < 3:
print('while loop executes with counter =',counter)
counter = counter + 1
OUTPUT
------
while loop executes with counter = 0
while loop executes with counter = 1
while loop executes with counter = 2
Exercise 3
Change the condition in the while loop below so that the output list has 5 entries.
counter = 0
my_list = []
while counter < 5: # change this condition so that the output list has 5 entries
if counter > 3:
my_list = my_list + [3*counter/8]
counter = counter + 1
print(my_list)
OUTPUT
------
[1.5]
For
A for
loop runs some indented code for each item in a list.
for item in [1,2,3]:
print(item)
OUTPUT
------
1
2
3
For
loops can also be used to build other lists.
my_list = []
for item in [1,2,3]:
my_list += [2*item]
print(my_list)
OUTPUT
------
[2, 4, 6]
We can even include a for
loop within a list to build it in a single line of code.
my_list = [2*item for item in [1,2,3]]
print(my_list)
OUTPUT
------
[2, 4, 6]
Note that in the context of creating lists, the real utility of for
loops comes from not having to write down the entries of any list to begin with.
In the previous cell, we constructed a list [2,4,6]
using [1,2,3]
as a starting list. However, a smarter way to do this is to use range(1,4)
which returns the list of numbers starting at 1
and stopping before 4
. This way, we can create even longer lists without having to do the work of writing down the initial list in full.
my_list = []
for item in range(1,20):
my_list += [2*item]
print(my_list)
OUTPUT
------
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
my_list = [2*item for item in range(1,20)]
print(my_list)
OUTPUT
------
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
Caution: range(1,20)
, for example, does NOT include the number 20. It stops right before 20, at 19. So if you want the list [1,2,3,...,20]
, you should use range(1,21)
instead.
Exercise 4
Using a for
loop, construct a list of the first 30 multiples of 7. (The last entry of the list should be 210.)
Solutions
Exercise 1
A = -1
B = 6
C = 3
D = 1
if A<0:
if A+B == 5:
if C*D != 0:
print('Success')
OUTPUT
------
Success
Exercise 2
A = 1
B = -2
C = 7
D = 4
if A + B >= 0:
pass
else:
if C + D <= 10:
pass
else:
print('Success')
OUTPUT
------
Success
Exercise 3
counter = 0
my_list = []
while counter < 9:
if counter > 3:
my_list = my_list + [3*counter/8]
counter = counter + 1
print(my_list)
OUTPUT
------
[1.5, 1.875, 2.25, 2.625, 3.0]
Exercise 4
multiples = []
for n in range(1,31):
multiples += [7*n]
print(multiples)
OUTPUT
------
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105, 112, 119, 126, 133, 140, 147, 154, 161, 168, 175, 182, 189, 196, 203, 210]
This post is part of the series Introduction to Python Programming.
Want to get notified about new posts? Join the mailing list and follow on X/Twitter.