Safari - Jun 9, 2022 at 2:56 PM
Safari - Jun 9, 2022 at 2:56 PM
Safari - Jun 9, 2022 at 2:56 PM
(Alpha version)
Home
Python control
structures
Overview
Teaching: 20 min
Exercises: 25 min
Questions
What constructs are available for changing the flow
of a program?
How can I repeat an action many times?
How can I perform the same task(s) on a set of
items?
Objectives
Change program flow using available language
constructs
Demonstrate how to execute a section of code a
fixed number of times
Demonstrate how to conditionally execute a
section of code
Demonstrate how to execute a section of code on a
list of items
if..else..
while…
for …
Python
if expression :
statement 1
statement 2
...
statement n
Python
print("\nExample 1\n")
value = 5
threshold= 4
print("value is", value, "threshold is ",thre
shold)
if value > threshold :
print(value, "is bigger than ", threshold
)
print("\nExample 2\n")
high_threshold = 6
print("value is", value, "new threshold is ",
high_threshold)
if value > high_threshold :
print(value , "is above ", high_threshold
, "threshold")
print("\nExample 3\n")
mid_threshold = 5
print("value is", value, "final threshold is
",mid_threshold)
if value == mid_threshold :
print("value, ", value, " and threshold,"
, mid_threshold, ", are equal")
Output
Example 1
value is 5 threshold is 4
5 is bigger than 4
Example 2
Example 3
✏ Exercise
Solution
Python
value = 4
threshold = 5
print("value = ", value, "and threshold = ",
threshold)
Output
✏ Exercise
Python
a = 5
b = 4
print("a = ", a, "and b = ", b)
if a > b :
print(a, " is greater than ", b)
elif a == b :
print(a, " equals ", b)
else :
print(a, " is less than ", b)
Output
a = 5 and b = 4
5 is greater than 4
Python
# while loop
n = 10
cur_sum = 0
# sum of n numbers
i = 1
while i <= n :
cur_sum = cur_sum + i
i = i + 1
print("The sum of the numbers from 1 to", n,
"is ", cur_sum)
Output
Points to note:
Python
Python
Python
Python
Solution
Python
Python
print("\nExample 1\n")
for i in [1,2,3] :
print(i)
print("\nExample 2\n")
for name in ["Tom", "Dick", "Harry"] :
print(name)
print("\nExample 3\n")
for name in ["Tom", 42, 3.142] :
print(name)
print("\nExample 4\n")
for i in range(3) :
print(i)
print("\nExample 5\n")
for i in range(1,4) :
print(i)
print("\nExample 6\n")
for i in range(2, 11, 2) :
print(i)
print("\nExample 7\n")
for i in "ABCDE" :
print(i)
print("\nExample 8\n")
longString = "The quick brown fox jumped over
the lazy sleeping dog"
for word in longString.split() :
print(word)
Output
Example 1
1
2
3
Example 2
Tom
Dick
Harry
Example 3
Tom
42
3.142
Example 4
0
1
2
Example 5
1
2
3
Example 6
2
4
6
8
10
Example 7
A
B
C
D
E
Example 8
The
quick
brown
fox
jumped
over
the
lazy
sleeping
dog
✏ Exercise
Python
variablelist = "01/01/2010,34.5,Yellow,True
"
Solution
Key Points
Licensed under CC-BY 4.0 2018–2022 by The Carpentries
Licensed under CC-BY 4.0 2016–2018 by Data Carpentry
Edit on GitHub / Contributing / Source / Cite / Contact