0% found this document useful (0 votes)
27 views43 pages

55284A - Introduction To Python - Chapter7

This lesson covers flow control in Python, focusing on conditional statements (if-elif-else), loops, generator functions, and list comprehensions. It explains how to use comparison and logical operators, as well as the 'is' and 'is not' operators for object identity. Additionally, it introduces the built-in functions all() and any() for evaluating iterables and the ternary operator for conditional assignments.

Uploaded by

ssuresh19747745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views43 pages

55284A - Introduction To Python - Chapter7

This lesson covers flow control in Python, focusing on conditional statements (if-elif-else), loops, generator functions, and list comprehensions. It explains how to use comparison and logical operators, as well as the 'is' and 'is not' operators for object identity. Additionally, it introduces the built-in functions all() and any() for evaluating iterables and the ternary operator for conditional assignments.

Uploaded by

ssuresh19747745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LESSON 7: Flow Control

Topics Covered

if conditions in Python.

Loops inTh Python.


is
do
cu
me
Generator functions.
nt
be
lon
List comprehensions.
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
But the path began nowhere and s a ended nowhere,
JA and it remained mystery, as the man who made it and
llo GT
the reason he made it remained mystery. we A
d! P.
– The Call of the Wild, Jack London

Introduction
Th
is
do
By default, a program cu flows line by line in sequential order. We have seen already that we can change this flow by
me
calling functions. The flownt can also be changed using conditional statements and loops.
be
lon
No agta gs to
j
un p NI
Conditional Statements au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
Conditional statements (if-elif-else s a conditions)JAallow programs to output different code based on specific
llo GT
we AP
conditions. The syntax is: d! .

if some_conditions:
do_this_1()
Th
do_this_2()
is
oc d
do_this_after() u me
nt
be
lon
No jagta gs to
un
Notice that the do_this_1() p Ndo_this_2()
au nilkand an LKA
I function calls are both indented indicating that they are part of
t h
the if block. They will only orun if t N
some_conditions evaluates to True. The do_this_after() function is not
riz @
ed red TES
indented. That indicates that the if co blockif H
has ended and it will run regardless of the value of some_conditions.
pie [Link] WAR
sa JA
llo GT
we AP
elif and else d! .

elif (for else if) conditions are only evaluated when the if condition is False. They are evaluated in order
up until one evaluates to True, at which point, that elif block is executed and the rest of the elif
conditions are skipped. An if statement can have zero or more elif conditions.
Th
The elseis block
do is only executed if the if condition and all the elif conditions evaluate to False. An if
cu
m
statement can have en zer or one else conditions.
tb
elo
ja ng
N g s
The following syntax blocks show an if-else and an if-elif-else statement:

if some_conditions:
do_this_1()
do_this_2()
else:
T
his
do_this_3()
d oc
do_this_after()ume
nt
be
lon
No ja gta gs to
if some_conditions:
un p NI
au nilka L
do_this_1() tho nt@ KAN
riz re TE
ed SH
do_this_2() co diff.c
pie om WAR
elif other_conditions: sa JA
llo GT
we AP
do_this_3() d! .
else:
do_this_4()
do_this_5()
do_this_after()
Th
is
do
cu
en m
t
Values that Evaluate tobeFalse lon
No agta gs to
j
un p NI
au nFalse:
The following values are considered il LK
tho kant
1. None riz @ ANT
ed re ES
co diff.c H
pie om WAR
2. 0 (or 0.0) s all JA
ow GT
ed AP
! .
3. Empty containers such as strings, lists, tuples, etc.

You can use the bool() function to demonstrate this:

>>> bool(None)
False
>>> bool(0)Th
is
do
False cu
>>> bool(0.0)
men
tb
False elo
n
>>> bool('') No agta gs to
j
un pn NI
au il LK
tho kant
False
>>> bool([]) riz @ ANT
ed re ES
False co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
The following table shows Python’s comparison operators:

Comparison Operators

Th
is
Operator do Description
cu
men
tb
elo
jag ng
N s
Operator Description

Equals
==

Doesn’t equal
!=
Th
is
do
cu
men
tb Is greater than
elo
> ng
No jagta st
oN
un p
au nilka ILK
tho n A
riz t@re NTE
ed Is lessd than SH
co if
< pie [Link] WAR
sa JA
llo GT
we AP
d! .
Is greater than or equal to
>=

Is less than or equal to


<= Th
is
do
cu
men
tb
elo
n Is the same object
is No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c WA
Ispnot om object
iesthe same R
all JA
is not
ow GT
ed AP
! .

Python also includes these membership operators:

in
Th
is
do
cu
True if value is found mein sequence.
nt
be
lon
No jagta gs to
un p N
au n#ilkaTrueILK
'a' in ['a', 'b', 'c'] tho nt@ AN
riz re TE
ed SH
'a' in 'abc' # True co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
not in

True if value is not found in sequence.

T
'a' not in hi['a',
sd 'b', 'c'] # False
oc
um# True
'd' not in 'abc' en
tb
elo
jag ng
N s
The following example demonstrates an if-elif-else statement.

Demo 35: flow-control/Demos/[Link]

1. def main():
2. age = int(input('How old are you? '))
3. Th
i
sd
4. oc >= 21:
if age
um
5. en
print('You can vote and drink.')
t be
n lo
6.
No jagta18:gs to
elif age >=
un pn canNvote,
IL
7. print('You
a ilk uth but can\'t drink.')
KA an
ori NT t@
8. else: r e ze
dif ESH
dc f.c
9. op
print('You cannot om or WA drink.')
ies vote R
all JA
10. ow GT
ed AP
11. main()
! .

Code Explanation

You can seeTthe


his different results by running this file and entering different ages at the prompt:
do
cu
me
nt
be
lon
No agta gs tpython
PS …\flow-control\Demos> j [Link]
un pn o NI
a i l L
How old are you? 17 u
tho kant K
riz @ ANT
You cannot vote or drink. ed re ES
co diff.c H
PS …\flow-control\Demos> python pie om WAR
s a [Link] JA
llo GT
How old are you? 19 we AP
d! .
You can vote, but can't drink.
PS …\flow-control\Demos> python [Link]
How old are you? 21
You can vote and drink.

Th
is
do
cu
men
tb
Compound Conditions
j
elo
ng
No agta s
un pn to NI
au i l LK
th kant
More complex if statementsooften
riz @ ANT
ed require
red that E several conditions be checked. The following table shows and and
iff. SHand
or operators for checking multiplecoconditions WA the not operator for negating a boolean value (i.e., turning True
pie c o
sa m R
JA
to False or vice versa). llo GT
we AP
d! .
Logical Operators

Operator Name Example

Th AND
is
and do if a and b:
cu
men
tb
elo
jag ng
N s
Operator Name Example

OR
or if a or b:

NOT
not if not a:
Th
is
do
cu
en m
tb
The following example showselo these logical operators in practice:
n
No jagta gs to
un p NI
au nilka L
tho
Demo 36: flow-control/Demos/[Link] nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
1. def main(): llo GT
we AP
d!
2. age = int(input('How old are you? ')) .
3.
4. is_citizen = (input('Are you a citizen? Y or N ').lower() == 'y')
5.
6. if age >= 21 and is_citizen:
Th
7. is print('You can vote and drink.')
do
cu
8. elif age me>= 21:
nt
be
9. print('You lon can drink, but can\'t vote.')
No agta gs to
j
10. elif age >=
un 18p and Nis_citizen:
au nilka ILK
tho can n AN but can\'t drink.')
11. print('You
riz t@vote,
red TES
ed H
co if
pie [Link] WAR
12. else:
13. print('You cannot vote s all JA
or drink.')
ow GT
ed AP
14. ! .
15. main()

Code Explanation
Th
is
do
Notice that is_citizen is assigned to a comparison expression:
cu
me
nt
be
lon
No jagta gs to
un p NI a citizen? Y or N ').lower() == 'y')
au nilka
is_citizen = (input('Are you
L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
If the user enters “Y” or “y”, is_citizen s a will be True.
JA Otherwise, it will be False.
llo GT
we AP
d! .
The is and is not Operators

The is and is not operators differ from the == and != operators. The former check whether two objects are the
same object. The latter check whether two objects have the same value. The following code illustrates this:
Th
is
do
cu
me
nt
b
>>> a = [1, 2, 3, 4] elon
N ja g gs
>>> b = [1, 2, 3, 4]
>>> c = a
>>> a == b
True
>>> a is b
False
>>> a == c
True
h T
>>> a is c is do
cu
True me
n tb
e
lon
>>> id(a), id(b), id(c)
No jagta gs to
un p
(1847278372096, 1847279744512, NI 1847278372096)
au nilka LK
t
>>> [Link](5) h o riz
n t @ ANT
ed re ES
>>> c co diff.c HW
pie o AR
sa m JA
[1, 2, 3, 4, 5] llo GT
we AP
d! .

Two identical lists are assigned to the a and b variables, but, because they are assigned separately, they are two
separate objects. So, while a == b is True, a is b is False.

But c is assigned
Th a, meaning c points to the same location in memory as a does, which is why the two variables
is
have the same id do and why, when we append 5 to a and then print c, we get the list containing 5.
cu
me
nt
be
lon
The following diagram, which was generated at [Link] shows the status after all the
No agta gs to
j
un
variables have been assigned: pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Th
is
do
cu
en m
As you can see, a and ct point
be to the same object:
lon
No jagta gs to
un p NI
au nilka L
all() and any() tho
riz
nt@ KAN
r TE
ed e SH
co diff.c
pie om WAR
s J
The built-in all() and any() functionsallare ow used to Aloop
GT through an iterable to check the boolean value of its
ed AP
elements. ! .

The all() function returns True if all the elements of the iterable evaluate to True.

The any() function returns True if any of the elements of the iterable evaluate to True.
Th
is
do
cu
me
nt
Ternary Operator be
lon
N ja g gs
Many programming languages, including Python, have a ternary conditional operator, which is most often used for
conditional variable assignment. To illustrate, consider this code:

if season == 'summer':
pant_color = 'white'
else:
T
his
pant_color = 'black'
do
cu
men
tb
elo
That’s very clear, but jag nfour
No it takes gs lines of code to assign a value to pant_color.
t t
un apni o NI
au l LK
tho kant AN
r ize @ T is:
The syntax for the ternary operator d c inrePython
dif ESH
f
op . WA
ies com R
all JA
ow GT
ed AP
[on_true] if [expression] else [on_false]
! .

Here is how we could use this syntax to assign our pants’ color:

Th
is
do
cu
pant_color = 'white' if season == 'summer' else 'black'
me
nt
b elo
n
No jagta gs to
u p NI Note that the expression could be any type of expression, including a function
au nshorter.
It’s still pretty clear, butnmuch il LK
tho kant AN
call, that returns a value that revaluates
ize @ to TTrue or False. For example, if you had an is_summer() function, you
d c rediff ESH
could do this: op . WA
ies com R
all JA
ow GT
ed AP
! .
pant_color = 'white' if is_summer() else 'black'

In Between
Th
is
do
cu
en m
tb
To check if a value is betweenelo two values, use the following syntax:
n
No agta gs to
j
un pn NI
au il LK
tho kant
r i z @ ANT
if low_value < your_value re ES
ed < high_value:
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
For example: d ! .

age = 15
if 12 < age < 20:
Th
print("You are a teenager.")
is
do
cu
men
if 13 <= age <= 19: belo
t
ja ng
s
print("You Nare ag teenager.")
This same syntax works with other types of objects (e.g., strings and dates) as well.

Loops in Python

As the name implies, loops are used to loop (or iterate) over code blocks. The following section shows examples of
Th
is types of loops in Python: while loops and for loops.
the two different do
cu
me
nt
be
You can find the loop examples lon used in this section in flow-control/Demos/[Link]
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
while Loops riz
ed re TE
SH
co diff.c
pie om WAR
while loops are used to execute a block s a of code repeatedly
JA while one or more conditions evaluate to True.
llo GT
we A
d! P.

num=0
while num < 6:
print(num)
num +=
T 1
his
do
cu
en m
tb
elo
The preceding code will return: n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
0 co diff.c HW
pie o AR
1 sa m JA
llo GT
we AP
2 d! .
3
4
5

Th
is
You can combine dowhile loops with user input to continually prompt the user until he or she enters an acceptable
cu
value. The following m en
example
tb
illustrates this:
elo
n
No jagta gs to
na p
Demo 37: flow-control/Demos/while_input.py
u n N
uth ilkan ILKA
ori t N
ze @red TES
dc iff. HW
op
1. def is_valid_age(s): ies com AR
all JA
2. return [Link]() and 1ow<= GT 113
ed int(s) <=AP
! .
3.
4. def main():
5. age = input('How old are you? ')
6. while not is_valid_age(age):
7. Th age = input('Please enter a real age as a number: ')
is
8. do
cu
en m
9. age = int(age)
t be
10. if age >= ja21:long
N g s
11. print('You can vote and drink.')
12. elif age >= 18:
13. print('You can vote, but can\'t drink.')
14. else:
15. print('You cannot vote or drink.')
16.
17. main()
Th
is
do
cu
men
Code Explanation tb
elo
n
No jagta gs to
un pn NI
au and il a entering
L
Run the file at the terminaltho ktry nt@ KAN some non-integer values:
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
ll GT
PS …\flow-control\Demos> python o we AP
while_input.py
d! .
How old are you? twenty Please enter a real age as a number: I'm 20 Please enter a real age
as a number: 20!

Please enter a real age as a number: 20 You can vote, but can't drink.
Th
is
do
c
The following demoushows
me how to combine if conditions and a while loop to create a simple game in which the
nt
user has to guess a number be between 1 and 100. Review the code and the comments, which provide explanations.
lon
No jagta gs to
un p NI
au nilka L
nt@ KAN
Demo 38: flow-control/Demos/guess_the_number.py
tho
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
1. import random llo GT
we AP
d! .
2.
3. def is_valid_num(s):
4. # Make sure the number is a digit between 1 and 100.
5. return [Link]() and 1 <= int(s) <= 100
6.
T
his
7. def main():
d
c o
8. # Get uamrandom
en number between 1 and 100
tb
9. e lon
number = [Link](1, 100)
No jagta gs to
10. un p NI
au nilka L
11. tho
# Set guessed_number nt@ Kto AN False to start.
riz r ed TES
ed H the user guesses the number
12. # We'll set it [Link]
pie com WAR
13. guessed_number = False all s JA
ow GT
ed AP
14. ! .
15. # Get the user's guess
16. guess = input("Guess a number between 1 and 100: ")
17.
18. # Set num_guesses to 0.
19. ThWe'll increment it by 1 after each guess
# is
do
20. cu
num_guesses = 0
m en
tb
21. elo
ja ng
22. N keep
# We'll s
g looping until the user guesses the number
23. while not guessed_number:
24. # Make sure the number is valid
25. if not is_valid_num(guess):
26. print("I won't count that one.")
27. guess = input("A number between 1 and 100 please: ")
28. else: # Number is valid
29. num_guesses += 1 # Increment num_guesses
Th
is
30. do guess = int(guess) # Convert user's guess to an int
cu
31. men
tb
32.
e
# If loguess is wrong, provide info and ask for another guess
n
No jagta gs to
33. uif pn < Nnumber:
na guess
uth ilkan ILKA
34. o
guess N
riz t=@rinput("Too low. Guess again: ")
ed ed TES
35. iff.
elif guesscop> number: HW
ies com AR
36. all
guess = input("Too JA
high.
ow GT Guess again: ")
ed AP
37. else: ! .
38. print("You got it in", num_guesses, "guesses!")
39. guessed_number = True # This will break us out of loop
40.
41. print("Thanks for playing.")
Th
42. is
do
cu
43. main() men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant AN
r @
for Loops ize
d c rediff ESH
T
op . WA
ie com R
A for loop is used to loop through ansiterator all (e.g., JaArange,
GT list, tuple, dictionary, etc.). The syntax is as follows:
ow
ed AP
! .

for item in sequence_name:


do_something(item)

Th
is
Looping through dao range
cu
me
nt
be
lon
No jagta gs to
for num in range(6): un p NI
au nilka LK
t h ori n t AN
ze @red TES
print(num)
dc
op [Link] HWA
ies m R
for num in range(0, 6): all JA
ow GT
ed AP
print(num) ! .

Both loops above will return:

Th
is
0 do
cu
men
1 tb
elo
2 jag ng
N s
3
4
5

Remember that a range goes up to but does not include the stop value.

Th
Skipping Steps is
do
cu
men
tb
elo
g2): n
No jag11,
for num in range(1, t s t # 3rd argument is the step
un apni o NI
print(num) a ut lk a LK
A ho nt@ N
riz red TES
ed H
co if
pie [Link] WAR
sa JA
This loop will return: llo GT
we AP
d! .

1
3
5
Th
7 is
do
cu
9 men
tb
elo
n
No agta gs to
j
un pn NI
Stepping Backwards au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
for num in range(10, 0, -1): llo GT
we AP
d! .
print(num)

This loop will return:

Th
is
do
10 cu
men
9 tb
elo
n
8 No agta gs to
j
un pn NI
au il LK
7 tho kant
riz @ ANT
6 ed re ES
co diff.c HW
pie o AR
5 sa m JA
llo GT
4 we AP
d! .
3
2
1

Th
Looping throughis a list and a tuple
do
cu
me
nt
be
lon
N ja g gs
nums = [0, 1, 2, 3, 4, 5]
for num in nums:
print(num)

nums = (0, 1, 2, 3, 4, 5)
for num in nums:
print(num)
T his
do
cu
men
tb
elo
Both loops above will return: n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
0 co diff.c
pie om WAR
1 sa JA
llo GT
we AP
2 d! .
3
4
5

Th
is
Looping throughdaocdict
um
en
tb
elo
n
No agta gs to
j
un
grades = {'English':97, pn 'Math':93,
NI 'Art':74, 'Music':86}
au il LK
tho kant A N
riz @
ed red TES
c op iff . HW
ies com
for course in grades: AR
all JA
print(course) ow GT
ed AP
! .
for course in [Link]():
print(course)

Th above will return the courses (the keys):


Both of the loops
is
do
cu
me
nt
be
lon
English No jagta gs to
un p NI
Math au nilka L
tho nt@ KAN
Art riz r e TE
ed SH
co diff.c
Music pie om WAR
sa JA
llo GT
we AP
d! .
Looping through the values of dict

for grade in [Link]():


Th
print(grade)
is
do
cu
men
tb
elo
ag ngs(the values)
This loop will returnN the jgrades
97
93
74
86

Looping through the items of dict


Th
is
do
cu
me
nt
for course, grade [Link]():
lo
N jag ngs
print(f'{course}: ou to
ta {grade}')
na pnilk NIL
uth an KA
ori t N
ze @red TES
dc iff. HW
o co
This loop will return the courses (thepiekeys) s a and
AR
m grades
JA
(the values):
llo G
we TA
d! P.

English: 97
Math: 93
Art: 74
Music: 86
Th
is
do
cu
en m
tb
Notice the unpacking of the elovariables:
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c
for course, grade in [Link](): HW
pie o AR
sa m JA
llo GT
we AP
d! . object, which is a pseudo-list of tuples:
Remember that the items() method returns a dict_items

dict_items([('English', 97), ('Math', 93), ('Art', 74), ('Music', 86)])

Th
is
do
The first item in eachcu of the tuples above is the course and the second item is the grade.
me
nt
be
lon
Another way of writing jag loop
No the g
tap sshown to above would be:
un n i NI
au l LK
tho kant
riz @ ANT
ed r e ES
co diff.c HW
for item in [Link](): pie o AR
sa m JA
course = item[0] l low GT
ed AP
! .
grade = item[1]
print(f'{course}: {grade}')

But, the original way, which unpacks the tuples into the course and grade variables with each iteration, is more
pythonic. This
do
cu
me
nt
be
lon
ExerciseN 22:g All ja gsTrue and Any True
10 to 15 minutes

In this exercise, you will use loops to write all_true() and any_true() functions that behave the same way as
the built-in all() and any() functions.

1. Th
Open flow-control/Exercises/all_and_any.py in your editor.
is
do
cu
2. me
In the main() function, there are calls to all_true() and any_true(), but those functions have yet to be
nt
be
written. Complete jthose l onfunctions:
No agta gs to
un pn NI
all_true()au–thshould ilka return
LK True if (and only if) all elements in the passed-in iterable evaluate to
ori nt@ ANT
ze
True. d c rediff ESH
op . WA
ies com R
any_true() – should returnallTrue JA one element in the passed-in iterable evaluates to True.
ow if at leastGT
ed AP
! .
3. Keep in mind that you want your function to return a value as soon as it can. For example, if you pass a list of
1,000,000 values to all_true() and the first value is False, the function does not need to continue looping
through the list to determine that not all values are True.

Th
is
Exercise Code:dflow-control/Exercises/all_and_any.py
oc
um
en
tb
elo
n
1. No agta gs to
j
def all_true(iterable):
un pn NI
au il LK
2. # write functiontho kant
riz @ ANT
3. pass ed re ES
co diff.c HW
pie o AR
4. sa m JA
llo GT
5. def any_true(iterable): we AP
d! .
6. # write function
7. pass
8.
9. def main():
10. a
T = all_true([1, 0, 1, 1, 1])
hi
s
11. b = dall_true([1,
oc 1, 1, 1, 1])
um
12. en
c = any_true([0, 0, 0, 1, 1])
bet
long 0, 0, 0, 0])
13. ja
d = any_true([0,
gta
No s to
14. na pnilk NIL
u
uth a KA
ori d)nt#@ Should NT be: False True True False
15. print(a, b, c, ze r
d c ediff ESH
op . WA
16. ies com R
all JA
17. main() ow GT
ed AP
! .

Solution: flow-control/Solutions/all_and_any.py

1.
T
his
def all_true(iterable):
do
cu False if any item is False
2. m
# Return
en
t
3. for item inbeiterable:
lon
ja g
4. ifN not gitem:s
5. return False
6. # If we made it through the loop without returning False,
7. # then all items are True
8. return True
9.
10. def any_true(iterable):
11. # Return True if any item is True
Th
is item in iterable:
12. for do
u c
13. if m en
item:
tb
14. return
elo True
jag n gs
N t t
15. # If weo umade a
na pit
oN
n through the loop without returning True,
uth ilkan ILKA
16. # o
then all itemsri t N
@are False
T
ze
d c rediff ESH
17. return False op . WA
ies com R
18. all JA
ow GT
ed AP
19. def main(): ! .
20. a = all_true([1, 0, 1, 1, 1])
21. b = all_true([1, 1, 1, 1, 1])
22. c = any_true([0, 0, 0, 1, 1])
23. d = any_true([0, 0, 0, 0, 0])
Th
24. is
do
c
um b, c, d) # Should be: False True True False
25. print(a, e nt
26. be
lon
27. main() No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
break and continue llo GT
we AP
d! .
To break out of a loop, insert a break statement:

for num in range(11, 20):


Th
print(num)
s i
if num % d5oc==
um 0:
en
break tb
elo
n
No jagta gs to
un pn
au ilka NILK
t h
Because 15 % 5 is equal toor0 nt@15AN /T 5 has a remainder of 0), the loop will stop after printing 15:
ize(i.e.,
d c rediff ESH
op . WA
ies com R
all JA
ow GT
e d! AP
11 .
12
13
14
15
Th
is
do
cu
me
nt
be of a loop without executing the remaining statements in the block, insert a continue
To jump to the next iteration
lo
statement:
N jag ngs
for num in range(1, 12):
if num % 5 == 0:
continue
print(num)

This will skip to the next iteration when num is divisible by 5, resulting in:
Th
is
do
cu
me
nt
1 be
lon
ja g
2 N ou g tap s to
na n N
3 uth ilkan ILKA
ori t@ N
ze
d red TES
4 co if H
pie [Link] WAR
6 sa JA
llo GT
we AP
7 d! .
8
9
11

Th
is
Notice 5 and 10 dare
oc not printed.
um
en
tb
elo
Here’s our Guess-the-Number n game modified to use continue instead of an else block:
No agta gs to
j
un pn NI
au il LK
tho kant
@ ANT
Demo 39: flow-control/Demos/guess_the_number_continue.py
riz
ed re ES
co diff.c HW
pie o AR
sa m JA
l lo GT
1. import random we AP
d! .
2.
3. def is_valid_num(s):
4. return [Link]() and 1 <= int(s) <= 100
5.
6. def main():
Th
i
s d = [Link](1, 100)
7. number
o cu
enm
8. guessed_number
t = False
be
9. lon
guess = input("Guess a number between 1 and 100: ")
Noja gtag st
oN
10. na =pn0i
u
num_guesses
lka ILK
uth
11. ori nt@ ANT
ze
d c rediff ESH
op . WA
12. while not guessed_number:
ies com R
a llo JA
13. if not is_valid_num(guess): we GT
d! AP
14. print("I won't count that one.") .
15. guess = input("A number between 1 and 100 please: ")
16. continue # Skip to next iteration through loop
17.
18. num_guesses += 1
Th
19. is guess = int(guess)
do
cu
20. me
nt
b
21. if guesselo<n number:
N ja g gs
22. guess = input("Too low. Guess again: ")
23. elif guess > number:
24. guess = input("Too high. Guess again: ")
25. else:
26. print("You got it in", num_guesses, "guesses!")
27. guessed_number = True
28.
Th
is
29. do
print("Thanks for playing.")
cu
30. men
tb
31. main()
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
Looping through Lines inpieas aFile om WAR
llo JA
we GT
AP
d! how to use
In an earlier lesson (see page 132), we showed . the splitlines() method of a string to split the lines
of text read from a file into a list. Let’s look again at the [Link] file we saw in that lesson:

Demo 40: flow-control/data/[Link]

T
his AL
1. Alabama d
c o
2. Alaska AK ume
nt
be
3. Arizona AZ lon
N jag gs
4. Arkansas ARo u ta to
na pnilk NIL
5. California CA
uth
o
a nt@ KAN
riz re TE
e
d c 50 diOmitted------- S
-------Lines 6 through op [Link] HWA
ies m R
all JA
ow GT
ed AP
! .
Code Explanation

Again, this file is a listing of states in the United States. Each line lists the name of the state and its abbreviation,
separated by a tab.

Th
is
Let’s see how we docan use the data in this file to write a program that allows the user to enter a state abbreviation
cu
and get the state name me in return:
nt
be
lon
No jagta gs to
Demo 41: flow-control/Demos/get_state.py
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed H
c if
1. def get_state(abbreviation): o pie [Link] WAR
sa JA
2. # Read the data from the llo file into
GTa list
we AP
d!
3. with open('../data/[Link]') as f: .
4. states = [Link]().splitlines()
5.
6. # Loop through the list
7. for state_row in states:
Th
8. is # Split each row on the tab character into a
do
cu
9. # mtwo-element
en list
tb
10. state = estate_row.split('\t')
lon
N jag gs
11.
12. # If the 2nd element matches the passed-in abbreviation
13. # return the first element
14. if state[1] == [Link]():
15. return state[0]
16.
17. # If no state matched the abbreviation, return None
Th
is
18. do None
return
cu
19. men
tb
20. def main():
elo
n
No jagta gs to
21. un
# Loop until pbreakNstatement
au nilka IL
22. t
while True: ri h o nt@ KAN
ze T
d c rediff ESH
23. abbr = input('State op . WA
abbreviation (q to quit): ').upper()
ies com R
24. all J AG
ow TA
ed P.
25. # Allow user to break loop ! by entering "Q"
26. if abbr == 'Q':
27. print('Goodbye!')
28. break
29.
Th
30. is # Get state name from abbreviation
do
cu
31. stateme = get_state(abbr)
nt
32. be
lon
ja g
33. o u gtapthes touser
# NInform
NI what state, if any, maps to the abbreviation
na nil LK
u tho k a A
34. if state: n
riz t@re NTE
e d d SHthe abbreviation for {state}.')
35. print(f'"{abbr}" co if is
pie [Link] WAR
36. else: sa JA
llo GT
we APas an abbreviation.')
37. print(f'No state has d! "{abbr}" .
38.
39. main()

Code Explanation
Th
is
do
cu
me
Read through this file carefully,
nt paying particular attention to the comments. Then run the file. Here is a sample
be
result: l o n
No jagta gs to
un pn NI
au il LK
tho kant
riz @ ANT
e r e ES
PS …\flow-control\Demos> dpython co diff.cget_state.py
H
pie om WAR
State abbreviation (q to quit): any s JA
llo GT
we AP
"NY" is the abbreviation for New York. d! .
State abbreviation (q to quit): ca
"CA" is the abbreviation for California.
State abbreviation (q to quit): as
No state has "AS" as an abbreviation.
Th
State abbreviation (q to quit): tx
is
do
cu
m
"TX" is the abbreviation for Texas.
en
State abbreviation (q
t
be to quit): q
lon
N ja g gs
Goodbye!
Exercise 23: Word Guessing Game

T45
his
to 120 minutes
do
cu
me
nt
be
In this exercise, you will create lon a word guessing game similar to hangman, but without a limit on the number of
No ja gta gs to
guesses. un p NI
au nilka L
tho nt@ KAN
riz re TE
e SH do your best and work your way through it one step at a time.
co diff.c Just
You may find this exercise quitedchallenging.
pie om WAR
Start by carefully reviewing the code. You s a may also Jfind
AG it helpful to play the game a couple of times by running
llo
python guess_word.py at the terminal from w TA
ed the flow-control/Solutions folder. A completed game would
! P.
look like this:

PS …\flow-control\Solutions> python guess_word.py


The word contains 9 letters.
Th
i
s d or a 9-letter word: A
Guess a lettero cu
en no "A"s. m
Sorry. The word hast be
********* lon
No agta gs to
j
pn
Guess a letter orunaa 9-letter N word: O
uth ilkan ILKA
The word has 3 "O"s. oriz t@ N
ed red TES
c op iff . HW
*OO***O**
ies com AR
all S JA
Guess a letter or a 9-letter word: ow GT
ed AP
The word has one "S". ! .
*OO*S*O**
Guess a letter or a 9-letter word: A
You already guessed "A".
Guess a letter or a 9-letter word: CK
T
his
Invalid entry.d
cu o
Guess a letter ormea 9-letter word: Woodstock
nt
be
WOODSTOCK is it! It took lon 4 tries.
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
The starting code is shown below: ed SH
co diff.c
pie om WAR
sa JA
llo GT
Exercise Code: flow-control/Exercises/guess_word.py we AP
d! .

1. import random
2.
3. def get_word():
4. Th
"""Returns random word."""
is
d
5. wordsoc=
um['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus',
en
6. tb
'Schroeder', 'Patty', 'Sally', 'Marcie']
e
lon
7. jag gs
returnN [Link](words).upper()
8.
9. def check(word, guesses):
10. """Creates and returns string representation of word
11. displaying asterisks for letters not yet guessed."""
12. status = '' # Current status of guess
13. last_guess = guesses[-1]
14. matches = 0 # Number of occurrences of last_guess in word
Th
is
15. do
u c
16. # Loop m en
through word checking if each letter is in guesses
tb
17.
e l
# If it is, oappend the letter to status
nja gs
No gt toappend an asterisk (*) to status
18. # If itunis anot,
p NI
au nilka LK
t h o n t AN
19. # Also, each time ri @
a letter
ze T in word matches the last guess,
d red ES
co by if HW
20. # pie f.co1.
increment matches
m AR
sa
JA
21. GT llo
A we
22. !
# Write a condition that outputs d
one [Link] the following when
23. # the user's last guess was "A":
24. # 'The word has 2 "A"s.' (where 2 is the number of matches)
25. # 'The word has one "A".'
26. # 'Sorry. The word has no "A"s.'
Th
27. is
do
c
28. returnum
status
e nt
29. be
lon
30. No agta gs to
def main():
j
un p NI
au nilka LK
31. tho
word = get_word() nt#@ The ANrandom word
riz red TES
e d H letters in the random word
32. n = len(word) # The co numberif of
pie [Link] WAR
33. s
guesses = [] # The lista of guesses JA made so far
llo GT
we AP
34. guessed = False d! .
35. print('The word contains {} letters.'.format(n))
36.
37. while not guessed:
38. guess = input('Guess a letter or a {}-letter word: '.format(n))
39. Th
is guess = [Link]()
do
40. # cWrite
um an if condition to complete this loop.
en
41. # You tmustbe set guessed to True if the word is guessed.
lon
ja g
42. o u gtapto sbe
# NThings to looking for:
NI
na nil LK already guess this guess?
43. # - Did uth the ka user
ori n t@ ANT
z
# - Is theeduseredguessing r E
44.
co iff. SHW the whole word?
pie c o AR
sa m JA
llo GT
45. # - If so, is it wcorrect? ed AP
! .
46. # - Is the user guessing a single letter?

47. Th # - If so, you'll need your check() function.


is
48. d#o - Is the user's guess invalid (the wrong length)?
cu
me
49. # nt
be
lon
50. # NAlso,jag don't gs forget to keep track of the valid guesses.
51.
52. print('{} is it! It took {} tries.'.format(word, len(guesses)))
53.
54. main()

Th
1. Open flow-control/Exercises/guess_word.py
is in your editor. The program consists of three
do
functions: cu me
nt
be
lon
A. get_word() No ja gtareturns
– gs a random secret word to guess. This function is complete.
un pn to NI
au il LK
B. check() – described tho kanbelow. A You must complete this function.
riz t@re NTE
ed d SH
co if
C. main() – our main program. pie [Link] co must
m
WA
Rcomplete this function.
sa JA
llo GT
we AP
2. The program selects a secret word anddprints: ! .
“The word contains n letters.” For example:

The word contains 6 letters.

Th
3. is then continuously prompts the user to choose a letter or guess the word until the word is
The programdo
cu
guessed: “Guess mea letter or a n-letter word: ”. For example:
nt
be
lon
No agta gs to
j
Guess a letter un or pani 6-letter
NI
au l LK word:
tho kant
riz @ ANT
ed re ES
co diff.c H
pie om WAR
s JA
ow in a guesses
4. The program keeps all previous guesses all GT list.
ed AP
! .
5. For each guess:

A. If the user has already guessed that letter or word, the program prints “You already guessed
"guess".” For example:

Th
i
Yous dalready
o guessed "A".
cu
men
tb
elo
N jag ngs
It then prompts
ou tfor to
a another guess.
na pnilk NIL
uth a K
o i nt@ ANT
B. Otherwise, if the ruser ze enters
d c rediff ESH
a word of the same length as the secret word, the program records
the guess in guesses and o . c
pie thenom WA to see if it is correct.
checks
sa R
llo JA
we GT
i. If the user’s guess is correct,d!the program APprints “GUESS is it! It took n tries.” For example:
.

SNOOPY is it! It took 8 tries.

Th The game then ends.


is
do
cu
me
ii. nt
If the user’sbe guess is incorrect, the program prints “Sorry, that is incorrect.” It then prompts for
lon
anotherjaguess. gs
N g
C. Otherwise, if the user enters a single character, the program records the guess in guesses and then
checks to see if the letter is in the word. It should do this by calling the check() function and passing it the
secret word and guesses:

result = check(word, guesses)

Th
is
do
cu
me
i. The check() nt function must do the following:
be
lon
ja g
No onegof
a. Print t thes following
t based on the number of times the last guess in guesses shows up in
un apni o NI
a
the secret lk
uthword:an L KA
ori t N
ze @red TES
dc iff. wordHW
a. Multiple times: op “The Ahas n "guess"s.” For example:
ies com R
all JA
ow GT
ed AP
! .
The word has 2 "O"s.

b. Exactly one time: “The word has one "guess".” For example:

Th
is
do
cu The word has one "S".
me
nt
be
lon
No agta gs to
j
c. uZero pn
na times: “Sorry.
N The word has no "guess"s.” For example:
uth ilkan ILKA
ori t N
ze @red TES
dc iff HW
o .
Sorry. The pword ies cohas m no AR"E"s.
all JA
ow GT
ed AP
! .

b. It should then return a string representation of the word displaying asterisks for letters not yet
guessed. For example, if the word is SNOOPY and O and Y have been guessed, it would return
**OO*Y.

ii. Th in the main() function, the value returned from the check() function should be compared to the
Back
is
d
secret oword:
cu
me
nt
b
a. If the two evalueslon are the same, the program prints “GUESS is it! It took n tries.” For example:
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
SNOOPY isrizit! ed Itre took TE 8 tries.
SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
The game then ends. d! .

b. If the two values are different, the program prints the value returned from check() (e.g.,
**OO*Y).

D. Otherwise, the program prints “Invalid Entry” and prompts the user for another guess. We only reach this
Th
is user enters a multi-character string that is not the same length as the secret word.
block if the do
cu
me
nt
be
lon
N ja g gs
Challenge
Create your own list of words in a separate file in the flow-control/data folder (or use the Harry Potter spells
in the [Link] file that’s already there) and use the words from that file in the get_word() function.

Solution: flow-control/Solutions/guess_word.py

-------Lines 1 through 8 Omitted-------


9. def check(word,
T guesses):
his
10. do
"""Creates and returns string representation of word
cu
m
en asterisks for letters not yet guessed."""
11. displayingt be
12. status = '' #lonCurrent status of guess
No jagta gs to
13. un = pguesses[-1]
last_guess nil NI
a L u ka K
th nt AN
14. matches = 0 #oriNumber
ze @reof occurrences
TE of last_guess in word
dif SH dc
f. WA op
15. ies com R
all JA
16. for letter in word: ow GT
ed AP
17. !
status += letter if letter in guesses . else '*'
18.
19. if letter == last_guess:
20. matches += 1
21.
Th
22. ifismatches
d > 1:
oc
u
me
23. print('The
n word has {} "{}"s.'.format(matches, last_guess))
tb
24. elif matcheselo==
n 1:
No jagta gs to
25. print('The
u pn word
N has one "{}".'.format(last_guess))
naIL ilka
26. else: nt@ KANuth
ori
ze red TES
d c The
27. print('Sorry. op ifword
f. Hhas
WA no "{}"s.'.format(last_guess))
ies com R
28. all JA
ow GT
ed AP
29. return status ! .
30.
31. def main():
32. word = get_word() # The random word
33. n = len(word) # The number of letters in the random word
34. Th
guesses = [] # The list of guesses made so far
is
do
cu = False
35. guessedm en
t
print('The bword
36. elo contains {} letters.'.format(n))
ja ng
37. No st gta
u oN pn
i lna
k ILK
38. u tho ant
while not guessed: AN
riz @ TE
e r e
dc d aSletter or a {}-letter word: '.format(n))
op [Link] HWA
39. guess = input('Guess
40. guess = [Link]() i es m R
all JA
ow GT
41. if guess in guesses: ed! AP
.
42. print('You already guessed "{}".'.format(guess))
43. elif len(guess) == n: # Guessing whole word
44. [Link](guess)
45. if guess == word:
46. Th guessed = True
is
do
47. cu else:
me
nt print('Sorry, that is incorrect.')
48. be
lon
49. elif jag gs
N len(guess) == 1: # Guessing letter
50. [Link](guess)
51. result = check(word, guesses)
52. if result == word:
53. guessed = True
54. else:
55. print(result)
56. else: # guess had wrong number of characters
Th
is
57. do print('Invalid entry.')
cu
58. men
tb
59.
e
print('{} is loit!
n It took {} tries.'.format(word, len(guesses)))
No jagta gs to
60. un p NI
au nilka LK
t
61. main() h o riz
n t @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Challenge Solution: flow-control/Solutions/guess_word_challenge.py

1. import random
2.
3. Th
def get_word():
is
oc d
4. """Returns
um random word."""
en
5. tb
with open('../data/[Link]') as f:
e
lon
6. N
words gs
ja=g [Link]().splitlines()
ap ou t oN t
na n
7. uth ilkan ILKA
return [Link](words).upper()
ori t NT
ze @61
-------Lines 8 through d c rediOmitted-------
ES
op ff .co HWA
ies m R
all JA
ow GT
ed AP
! .
The else Clause of Loops
In Python, for and while loops have an optional else clause, which is executed after the loop has successfully
completed iterating (i.e., without a break). The following demo shows how it works:
Th
is
do
Demo 42: flow-control/Demos/loop_else.py
cu
me
nt
be
lon
1. def main(): No jagta gs to
un p NI
au nil1: L loop')
2. print('Example
tho kantforKA N
r @
3. num = int(input('Enter i z ed r ed aTnumber:
ES '))
co iff . HW
p i c o A
4. for i in range(5): es m R
all JA
5. if i == num: ow GT
ed AP
! .
6. break
7. print(i)
8. else:
9. print(f'Completed iterating without reaching {num}.')
10. Th
is
11. do
print('\nExample 2: while loop')
c um
12. i = 0 en
tb
on el
13. ja gs
num = int(input('Enter
N g
a number: '))
14. while i <= 5:
15. if i == num:
16. break
17. print(i)
18. i += 1
19. else:
20. print(f'Completed iterating without reaching {num}.')
Th
is
21. do
cu
22. main() m en
tb
elo
n
No jagta gs to
un p NI
au nilka L
Code Explanation tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
The preceding code will render something s a like the following:
JA
llo GT
we AP
d! .

First Run
PS …\flow-control\Demos> python loop_else.py
Example 1: for loop
Enter a number:
T 4
his
0 do
cu
m en
1 tb
elo
n
2
No agta gs to
j
u na p n N
3
uth ilkan ILKA
ori t N
ze @red TES
dc iff HW
op .
Example 2: while loop ies com AR
all JA
Enter a number: 3 ow GT
ed AP
0
! .

1
2

Second Run
Th
is
do
PS …\flow-control\Demos> python loop_else.py
cu
me
Example 1: for loopn tb
Enter a number: 7
elo
n
No agta gs to
j
0 un pn NI
au il LK
tho kant
1 riz @ ANT
ed re ES
2 co diff.c HW
pie o AR
sa m JA
3 llo GT
we AP
4 d! .
Completed iterating without reaching 7.

Example 2: while loop


Enter a number: 6
Th
0 is
do
cu
1 m en
tb
2 elo
jag ng
3 N s
4
5
Completed iterating without reaching 6.

The first run through, we entered numbers lower than 5, so the loops were broken out of before completing. The
second run through, we entered numbers higher than 5, so the loops completed all iterations, which led to the else
Th
clause also being
is executed.
do
cu
me
So, when would you use nt this? You might use it to check user-entered text for black-listed words. The following code
be
lon
shows a common way No j
toa gdo gs in other programming languages:
this
t t
un apni o NI
au l LK
tho kant
riz @ ANT
ed re ES
co diff.c ') HW
sentence = input('Input a sentence: pie o AR
sa m JA
found_bad_word = False llo GT
we AP
d! .
for word in [Link]():
if word in BLACK_LIST:
found_bad_word = True
break

Th
is
if found_bad_word:
d oc
u
me a naughty word.')
print('You used
n tb
else: elo
n
No agta gs to
j
print('Sentence un passespn NI
cleanliness test.')
au il LK
tho kant A NT
riz @
ed re ES
co diff.c H
pie om WAR
The code in the following file shows how s a you can accomplish
JA the same thing in a cleaner way using the else
llo GT
clause: wed AP
! .

Demo 43: flow-control/Demos/loop_else_use_case.py

1. BLACK_LIST = [
2. Th
'shitake',
is
oc d
3. 'sugar',
u
e m
4. 'fudge', nt be
lo
5. 'gosh',
N jag ngs
tap
ou to
nil NI
6. 'darn', nau k LK
tho ant
r i z @ ANT
7. 'dang', ed r e ES
co diff.c HW
pie o AR
8. 'heck' sa m JA
llo GT
9. ] we AP
d! .
10.
11. def main():
12. sentence = input('Input a sentence: ')
13.
14. for
T word in [Link]():
his
15. dif
oc word in BLACK_LIST:
um
16. en
print('You used a naughty word.')
tb
elo
17.
N jag ngs
break
18. else:
19. print('Sentence passes cleanliness test.')
20.
21. main()

Code Explanation
Th
is
do
Here are the results cuof running this file, first with a “clean” sentence and then with a “dirty” one:
me
nt
be
lon
No ja gta gs to
un p NI
au nilkapython L
PS …\flow-control\Demos> tho nt@ KANloop_else_use_case.py
riz re inTmy ES coffee.
Input a sentence: I like edcream
co diff.c HW
Sentence passes cleanliness test. p ies om AR
all JA
o we GT
PS …\flow-control\Demos> python loop_else_use_case.py
d! AP
.
Input a sentence: I like sugar in my coffee.
You used a naughty word.

Th
is
do
Exercise cu 24: for…else
me
nt
be
lon
No agta gs to
j
un p NI
au nilka L
10 to 20 minutestho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
l
In this exercise, you will rewrite a functionloto GT clause of a loop.
we use the else
AP
d! .

1. Open flow-control/Exercises/[Link] in your editor and review the code. Then run the script to
see how it works.

A. First, try entering only valid states:


Th
is
do
cu
me
PS …\flow-control\Exercises> python [Link]
nt
be
Name as many lstate on abbreviations do you know?
No jagta gs to
Separateunthempnwith Nspaces:
au il ILK
tho kant AN
AZ CA NY riz @
ed red TES
co if H
You named 3 states. pie [Link] WAR
sa JA
llo GT
we AP
d! .
B. Now, try including an invalid state:

PS …\flow-control\Exercises> python [Link]


Name as many state abbreviations do you know?
This
Separate
d them with spaces:
cu o
AZ CA CCmeNY
nt
CC is not abestate.
lo
jag ng
N s
2. Modify the main() function so that it uses the for loop’s else clause.

3. Run the script again. It should work in exactly the same way.

Exercise Code: flow-control/Exercises/[Link]


Th
is
oc d
1. def is_state(state):
um
en
2. tb
with open('../data/[Link]') as f:
e lon
3. N
states gs
jag= [Link]().splitlines()
ou a t t
o
na pnilk NIL
4. uth an KA
ori t N
5. state_abbreviations ze @r=ed[]TES
dc
op [Link] HWA
6. for state_row in states: ies m R
all JA
o GT
7. state_abbreviation = wstate_row.split('\t')[1]
ed AP
! .
8. state_abbreviations.append(state_abbreviation)
9.
10. return state in state_abbreviations
11.
12. def main():
T his
13. do
print('Name as many state abbreviations do you know?')
c um
14. en
print('Separate them with spaces:')
t be
lo
ng
15. ja
states = input('').split()
gta
No s
upn to N
bad_statena= False
16.
uth ilkan ILKA
17. riz t@re NTE
for state in ostates:
ed SH
co diff.c
18. state = [Link]()pie om WAR
sa JA
19. if not is_state(state): llo GT
we AP
d! .
20. print(f'{state} is not a state.')
21. bad_state = True
22. break
23.
24. if not bad_state:
Th
is print(f'You named {len(states)} states.')
25. do
cu
26. me
nt
be
27. main() lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c WA
Solution: flow-control/Solutions/[Link] i es o m R
all JA
ow GT
ed AP
! .
-------Lines 1 through 11 Omitted-------
12. def main():
13. print('Name as many state abbreviations do you know?')
14. print('Separate them with spaces:')
15. Th
states = input('').split()
is
do
16. cu
for state me in states:
17.
n
state t=[Link]()
lon
18. gs
ifN notjagis_state(state):
19. print(f'{state} is not a state.')
20. break
21. else:
22. print(f'You named {len(states)} states.')
23.
24. main()

Th
is
do
cu
me
nt
The enumerate() beFunction
lo n
No jagta gs to
un p
It is common in other programming Nlanguages to write code like this:
au nilka IL
tho nt@ KAN
riz re TE
ed SH
co diff.c
Demo 44: flow-control/Demos/without_enum.py
pie om WAR
sa JA
llo GT
we AP
d! .
1. i = 1
2. for item in ['a', 'b', 'c']:
3. print(i, item, sep='. ')
4. i += 1

Th
is
do
Code Explanation cum
en
tb
elo
n
j gta gs to list:
Noan aenumerated
This code will output
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
1. a sa m JA
llo GT
2. b we AP
d! .
3. c

The more Pythonic way of accomplishing the same thing is to use the enumerate() function, like this:

Th
Demo 45: flow-control/Demos/with_enum.py
is
do
cu
me
nt
be
1. lon
for i, item in enumerate(['a', 'b', 'c'], 1):
No jagta gs to
2. print(i,unitem, p sep='. NI ')
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
This saves us from creating a new variable s a to hold theJA count.
llo GT
we AP
d! .
Note that enumerate() takes two arguments:

1. The iterable to enumerate.

2. The number at which to start counting (defaults to 0).


Th
is
do
cu
me
nt
be
lon
It returns an iterable of two-element tuples of the format (count, value).
N ja g gs
Here is a more practical example, in which we output a list of all the state names in [Link]:

Demo 46: flow-control/Demos/state_list.py

1. def main():
2. with open('../data/[Link]') as f:
3. Th states = [Link]().splitlines()
is
4. do
cu
en m
5. for i, state
t in enumerate(states, 1):
be
lo
ng= [Link]('\t')[0]
6. ja
state_name
Nogta s to
7. na pnilk {state_name}')
u
print(f'{i}. NI
uth an LKA
ori t@ NT
8. ze
d c rediff ESH
op . WA
9. main() ies com R
all JA
ow GT
ed AP
! .

Generators
Generators are special iterators that can only be iterated through one time. Generators are created with special
generator functions. Before looking at one, let’s first consider how a standard iterator (e.g., a list) works:
Th
is
do
cu
me
Demo 47: flow-control/Demos/list_loop.py
nt
be
lon
No agta gs to
j
un p NI
au nilka
1. import random
LK
tho n A
2. riz t@re NTE
ed d SH
co high,if
3. def get_rand_nums(low, pie [Link]): WA
R
sa JA
4. numbers = [] llo GT
we AP
5. for number in range(num): d ! .
6. [Link]([Link](low, high))
7. return numbers
8.
9. numbers = get_rand_nums(1, 100, 5)
Th
10. is
do
c
um time through:')
11. print('First e nt
be
12. lo
for num in numbers:
n
13. No jagta gs to
print(num)
un p NI
au nilka LK
14. th n A ori t@ NT
ze
15. d c rediff ESH
print('Second time through:')
op . WA
ies com R
16. for num in numbers: al JA
low GT
17. print(num) ed AP
! .

Code Explanation

This code will


Thoutput something like:
is
do
cu
me
nt
be
lon
N ja g gs
First time through:
13
63
50
10
16
Second time
T through:
his
13 do
cu
m en
63 tb
elo
n
50 No jagta gs to
un p NI
10 au nilka L
tho nt@ KAN
r ize T
d c rediff ESH
16
op . WA
ies com R
all JA
ow GT
ed AP
There is nothing new in this code. The get_rand_nums()! . function returns a list of num random numbers between
low and high. We assign that list to numbers and then loop through it twice. We can loop through it any number
of times.

Now, consider this code, which uses a generator:


Th
is
do
Demo 48: flow-control/Demos/generator_loop.py
cu
me
nt
be
lon
1. import random No agta gs to
j
un p NI
au nilka L
2. tho nt@ KAN
riz red TES
3. def get_rand_nums(low, ed H
co high,if num):
pie [Link] WAR
4. for number in range(num): sa JA
llo G
we high)TAP.
5. yield [Link](low, d!
6.
7. numbers = get_rand_nums(1, 100, 5)
8.
9. print('First time through:')
10. Th in numbers:
for num
is
oc d
11. print(num)
u me
nt
12. be
ng lo
13. No jatime
print('Second gt st
through:')
un apni o NI
14. au
for num in numbers:lka LK
tho nt@ AN
riz red TES
15. print(num) ed H
co if
pie [Link] WAR
sa JA
llo GT
we AP
d! .
Code Explanation

This code will output something like:

Ththrough:
First time is
do
cu
69 m en
tb
32 elo
jag ng
65 N s
76
87
Second time through:

Here are the two functions again:

Th
is
do
List Loop cu
men
t b high, num):
def get_rand_nums(low,e lo
No
numbers = [] jag ngs
t t
un apni o NI
au l LK
tho kant
for number in range(num):
riz @ ANT
ed re ES
co diff.c
[Link]([Link](low, HW high))
return numbers
p ies om AR
all JA
ow GT
ed AP
! .
Generator
def get_rand_nums(low, high, num):
for number in range(num):
yield [Link](low, high)
Th
is
do
cu
The two functions work me in essentially the same way, but the second function is much cleaner as there is no need for
nt
be
the local numbers variable. loRather than creating a full list and then returning it, the generator function yields each
jag ngs
Noit works
result one by one as tap its wayto through the for loop. The only functional difference, as the example
un nil NI
a k L through the generator one time. However, if you want to iterate through
u
illustrates, is that you can tonly a
ho iterate nt@ K AN
riz redgeneratorTE
multiple times, you can simply ecall d c the if SH function again as shown in the next example:
op f . WA
ies com R
all JA
ow GT
Demo 49: flow-control/Demos/generator_loop2.py ed AP
! .

1. import random
2.
3. def get_rand_nums(low, high, num):
4. Th number in range(num):
for
is
do
5. cu
yield
m [Link](low, high)
en
6. tb
elo
7. jag nthrough:')
No time
print('First gs
t t
un apni o NI
8. au lka
for num in get_rand_nums(1, LK 100, 5):
tho n A
riz t@re NTE
9. print(num) ed d SH
co if
10. pie [Link] WAR
sa JA
llo GT
11. print('Second time through:') we AP
d! .
12. for num in get_rand_nums(1, 100, 5):
13. print(num)

Code Explanation
Th
is
do
cu
This will return somethingme like:
nt
be
lon
N ja g gs
First time through:
56
19
99
33
8
Second time
T through:
his
36 do
cu
men
88 tb
elo
n
76 No jagta gs to
un p NI
54 au nilka L
tho nt@ KAN
r ize T
d c rediff ESH
80
op . WA
ies com R
all JA
ow GT
ed AP
As the function is returning a sequence of random ! . you will get different numbers each time you call the
numbers,
generator function.

If you want a sequence of random numbers that you can count on being the same each time you iterate through it,
then you should create a function that returns a list.
Th
is
do
When to Use cu Generators
me
nt
be
Use generators whenever lon want to be able to get the next item in a sequence without creating the whole
you
No agta gs to
j
sequence ahead of time. un Some p examples:
NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
Infinite Sequences co diff.c
pie om WAR
sa JA
llo GT
Demo 50: flow-control/Demos/odd_numbers.py we AP
d! .

1. def odd_numbers():
2. i = -1
3. while True:
4. Thi += 2
is
do
5. yield cu i
me
nt
6. be
lo
N jag ngs
7. def main():o tap to
un nil NI
a u k LK
8. tho ant
for i in odd_numbers():
riz @ ANT
ed r e ES
9. print(i) co diff.c H
pe om WAR
10. if input('Enter ifor s a next or qJ to quit: ') == 'q':
llo AG
11. print('Goodbye!') ed w TA
! P.
12. break
13.
14. main()

Th
is
Code Explanationdo
cu
men
tb
It’s impossible to store the einfinite
lon
N ja g gs number of odd numbers in a list. This generator function just yields the next one
every time it is called:
PS …\flow-control\Demos> python odd_numbers.py
1
Enter for next or q to quit:
3
Enter for next or q to quit:
5
Enter for Tnext or q to quit: q
his
Goodbye! do
c um
en
tb
elo
n
No jagta gs to
un p NI
au nilka L
The Fibonacci Sequence tho nt@ KAN
riz red TES
ed HW
c op ifin
f.
The Fibonacci sequence is a sequence ies comathematics
m AR in which each number is the sum of the two preceding
numbers. all JA
ow GT
ed AP
! .
Demo 51: flow-control/Demos/[Link]

1. def fibonacci():
2. a, b = 0, 1
Th
3. is
whiled True:
oc
u
me a
4. yieldn
be t
5. a, b = b, lona + b
ja
No stg gta
6. u oN pn
na
uth kan ILKA
i l
ori t N
ze @red TES
7. def main():
dc iff HW
8. for i in fibonacci(): op .
ies com AR
9. print(i) all JA
ow GT
ed AP
10. if input('Enter for next! or q to quit: . ') == 'q':
11. print('Goodbye!')
12. break
13.
14. main()
Th
is
do
cu
men
Code Explanation tb
elo
n
No agta gs to
j
un pn NI
au il
See [Link]
LK for information on the Fibonacci Sequence.
tho kant
riz @ ANT
ed r ed E SH
c iff
A Sequence of Unknown Lengthopie .com WAR
sa JA
llo GT
In Bingo, the caller keeps picking out numbers we until someone
AP wins. It’s impossible to know ahead of time how many
d! .
numbers must be drawn.

Demo 52: flow-control/Demos/[Link]

1. Th random
importi sd
oc
2. um
n e
3. def bingo(): t be
lon
4. balls N= { jag gs
5. 'B': list(range(1, 16)),
6. 'I': list(range(16, 31)),
7. 'N': list(range(31, 46)),
8. 'G': list(range(46, 61)),
9. 'O': list(range(61, 76))
10. }
11.
Th
is
12. whiledo balls:
cu
13. me = [Link](list([Link]()))
letter
n tb
14.
e
number = [Link](balls[letter])
n
No jagta gs to
15. un p NI
balls[letter].remove(number) # Remove number from letter list
au nilka LK
t h o n t A N
16. if not balls[letter]:
riz @ TE # Letter has no more numbers
ed re SH
co diff.c letter)
17. print('Removing', pie om WAR
sa JA letter from dictionary
18. del balls[letter] llo # DeleteGT
we AP
19. yield (letter, number)d! .
20.
21. def main():
22. for ball in bingo():
23. print(ball)
Th
24. is if input('Enter for next ball or q to quit') == 'q':
do
cu
25. mprint('Goodbye!')
en
tb
26. break elo
N jag ngs
27. else: o u ta to
na pnilk NIL
28. print('All u tho out a n ofKA balls.')
riz t@re NTE
ed d SH
29. co if
pie [Link] WAR
30. main() sa JA
llo GT
we AP
d! .

Code Explanation

This generator function keeps spitting out Bingo balls until it runs out of balls.

Th
i
Here's a Bingo scard,
do in case you want to try your luck:
cu
me
nt
be
lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

Th
is
do
cu
m en
tb
elo
jag ng
N s
Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

The next() Function


To be an iterator, an object must have a special __next__() method (that’s two underscores before and two
his “next”), which returns the next item of the iterator. Python’s built-in next(iter) function calls
underscoresTafter
the __next__()domethod
cu of iter. The following example shows how to use the next() function with a generator
me
to play Rock, Paper, Scissors
nt (RoShamBo) against your computer.
be
lon
No jagta gs to
un p
Demo 53: flow-control/Demos/[Link] NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
1. import random pie om WAR
sa JA
llo GT
2. we AP
d! .
3. def roshambo(weapons):
4. while True:
5. yield [Link](weapons)
6.
7. def play(weapons, choice, python_weapons):
Th
is
8. do
your_weapon = weapons[int(choice)-1]
cu
9. en
python_weapon
m
= next(python_weapons)
tb
elo
10. n
No agta gs to
j
11. un
if your_weapon pn == python_weapon:
NI
au il LK
tho kant AN
12. print('Tie: riz You@rboth
ed TES
chose', your_weapon)
ed HW
if
elif ((your_weaponcop== 'Scissors'
f.
ies com
13. AR and python_weapon == 'Paper')
14. or (your_weapon == a llo 'Paper' JAGT python_weapon == 'Rock')
and
we AP
15. d !
or (your_weapon == 'Rock' and python_weapon . == 'Scissors')):
16. print('You win:', your_weapon, 'beats', python_weapon)
17. else:
18. print('You lose:', python_weapon, 'beats', your_weapon)
19. print('--------')
Th
20. is
do
cu
21. men
be t
22. def make_choice():lo ng
g ja s
23. choiceN = input("""Choose your weapon:
24. 1: Rock
25. 2: Paper
26. 3: Scissors
27. q: Quit
28. """)
29. return choice
30.
Th
is
31. do
def main():
cu
32. weaponsm=en ['Rock', 'Paper', 'Scissors']
tb
33. python_weapons
e
lon = roshambo(weapons)
No jagta gs to
34. p
choice =unmake_choice() NI
au nilka LK
t
35. while choice inh o n t
riz ['1', @ A N
'2', '3']:
ed red TES
36. play(weapons, cchoice, op iff . HW
python_weapons)
ies com AR
37. choice = make_choice() all JA
ow GT
ed AP
38. print('Goodbye!') ! .
39.
40. main()

Code Explanation
Th
is
do
cu
me
One benefit of assigning nt a generator to python_weapons instead of a list is that you don’t need to know how
be
lon
many iterations thereNo agbe.
will
j g generator just spits out a new result each time its __next__() method is called.
The
tap s to
un NI
au nilka L
tho nt@ KAN
Here is a possible output of the r ize game: T
d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
PS …\flow-control\Demos> python [Link] ! .
Choose your weapon:
1: Rock
2: Paper
3: Scissors
Th
q: Quit is
do
cu
1 m en
tb
elo
You win: Rock beats Scissors
n
No agta gs to
j
-------- un p NI
au nilka LK
Choose your weapon: t h ori n t AN
ze @red TES
dc
1: Rock op [Link] HWA
ies m R
2: Paper all JA
ow GT
e d! AP
3: Scissors .
q: Quit
2
You lose: Scissors beats Paper
--------
Th weapon:
Choose youris
do
1: Rock cu
m en
tb
2: Paper elo
jag ng
3: Scissors N s
q: Quit
q
Goodbye!

Note that the roshambo() generator is overly simplistic. On line 9, we could have just used
[Link](weapons) to get the value of python_weapon. But imagine that the generator did something
Th For example, you could give it weapon preferences like this:
more than [Link]
do
cu
me
nt
be
lon
def roshambo(weapons):
No ja gta gs to
un p NI
while True: au nilka L
tho nt@ KAN
r ize T
d c rediff ESH
num = [Link]()
op . WA
if num < .5: ies com R
all JA
yield weapons[0] o we GT
d! AP
.
elif num < .8:
yield weapons[1]
else:
yield weapons[2]

Th
is
do
cu
m e
nt
List Comprehensions
be
lo
N jag ngs
tap t
List comprehensionso are
un used to ocreate
NI new lists from existing sequences by taking a subset of that sequence
au nilka LK
t
and/or modifying its members.h n A
ori To tunderstand N the purpose, let’s first look at creating a new list from a list using a
ze @red TES
for loop: dc iff H
op . WA
ies com R
all JA
ow GT
ed AP
! .
squares = []
for i in range(10):
[Link](i*i)

Th
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
is
do
cu
m en
tb
elo
This same thing can be jadone nmuch more tersely with a list comprehension. The syntax is:
No gta gs to
un pn NI
au il LK
tho kant
riz @ ANT
ed red ES
new_list = [modify(item) for co itemiff. in HWitems]
pie c o AR
sa m JA
llo GT
we AP
d! .
Where modify(item) represents any change made to item.

Using a list comprehension, the code above could be rewritten like this:

Th
is
do for i in range(10)]
squares = [i*i cu
me
nt
be
lo
N jag ngs
Here’s another example, in which we use a list comprehension to create a list of people’s initials from a list of their
names:

Demo 54: flow-control/Demos/list_from_list.py

1. def initials(name):
2. fullname
T = [Link](' ')
his
3. do = (fullname[0][0], fullname[1][0])
inits
cu
en m
4. return inits
t be
5. lon
No ja gta gs to
6. def main(): una pnil N
uth kan ILKA
o t @
riz Chapman', N
7. names = ['Graham
ed red TES'John Cleese', 'Eric Idle',
co if HW
8. 'Terry Gilliam', pie [Link]'Terry AR Jones', 'Michael Palin']
sa J
9. inits = [initials(name)llow for name Ain
GT names]
ed AP
10. for i in inits: ! .
11. print(f'{i[0]}.{i[1]}.')
12.
13. main()

Th
is
d
Code Explanationocum
en
tb
elo
j ng
No agcreates
The list comprehensions t s t a new list from names by passing each of its elements to the initials()
un apni o NI
a
function. This will return: ut lk L
ho ant@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
G.C. llo GT
we AP
d! .
J.C.
E.I.
T.G.
T.J.
M.P.
Th
is
do
cu
en m
Remember our add_nums() tb
elo function from the Iterables lesson:
n
No agta gs to
j
un pn NI
au il LK
tho kant
Demo 55: iterables/Demos/add_nums.py
riz @ ANT
ed re ES
co diff.c H
pie om WAR
1. def add_nums(num, *nums): all s JA
ow GT
e d! AP
2. total = sum(nums, num) .
3. print(f"The sum of {nums} and {num} is {total}.")
4.
5. def main():
6. add_nums(1, 2)
7. Th
add_nums(1, 2, 3, 4, 5)
is
do
8. cu
add_nums(11, 12, 13, 14)
m en
t b 201, 301)
9. add_nums(101,el on
N jag gs
10.
11. main()

When you call that function like this:

Th 2, 3, 4, 5)
add_nums(1,i sd
oc
um
en
tb
elo
The result is: n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed
The sum of (2, 3, 4, 5) andcop1 is iff. 15. HW
ies com AR
all JA
ow GT
ed AP
! .
That’s not too pretty. We can improve it using a list comprehension, like this:

Demo 56: flow-control/Demos/add_nums.py

1. Th
def add_nums(num, *nums):
is
do
2. total = cumsum(nums, num)
en
tb
3. elo
j ng
No agta= ', s '.join([str(n) for n in nums])
pn to NI
4. nums_joined
un i
5. a
print(f"Theuthsum ka l LK
of {nums_joined} and {num} is {total}.")
ori nt@ ANT
ze r E
6. d c ediff S
op .co HWA
7. def main(): i es m R
all JA
ow GT
8. add_nums(1, 2) ed AP
! .
9. add_nums(1, 2, 3, 4, 5)
10. add_nums(11, 12, 13, 14)
11. add_nums(101, 201, 301)
12.
13. Th
main()
is
do
cu
men
tb
elo
Code Explanation n
No agta gs to
j
un pn
au ilka NILK
t
This uses a list comprehension h ori tontconvertAN the list of numbers into a list of strings and then joins that list on ', ' in one
ze @red TES
dc
step. The output will be: op [Link] HWA
ies m R
all JA
ow GT
ed AP
! .
The sum of 2 and 1 is 3.
The sum of 2, 3, 4, 5 and 1 is 15.
The sum of 12, 13, 14 and 11 is 50.
The sum of 201, 301 and 101 is 603.
Th
is
do
cu
m
Much prettier, right? ent
be
lo
N jag ngs
Creating Sublists with List Comprehensions
List comprehensions have an optional if clause that can be used to create a sublist from a list:

new_list = [item for item in items if some_condition]

Th
is
Assume that youdowant
cu to get all the three-letter words from a list of words. First, let’s do it without a list
me
comprehension: nt
be
lon
No ja gta gs to
un p NI
au nilka LK
tho
three_letter_words = []riz n t @ ANT
ed re ES
for word in words: co diff.c HW
pie o AR
sa m JA
if len(word) == 3: llo GT
we AP
three_letter_words.append(word) d! .

In the following file, we do the same thing with a list comprehension:

Demo 57: flow-control/Demos/sublist_from_list.py


Th
is
do
cu
me
nt
1. def main(): be
lo
jag ngs
words N=o ['Woodstock',
2. tap to 'Gary', 'Tucker', 'Gopher', 'Spike', 'Ed',
un nil NI
a u k a L K
3. tho
'Faline', A
n 'Willy', 'Rex', 'Rhino', 'Roo', 'Littlefoot',
riz t@re NTE
4. 'Bagheera', ed d
'Remy', S H 'Pongo', 'Kaa', 'Rudolph', 'Banzai',
co if
pie [Link] WAR
5. 'Courage', 'Nemo', sa 'Nala',
JA 'Alvin', 'Sebastian', 'Iago']
llo GT
6. three_letter_words = [w for
wed w in wordsAP if len(w) == 3]
! .
7. print(three_letter_words)
8.
9. main()

Th
is
Code Explanationdo
cu
men
tb
elo
This code combines an jif condition
n within a for loop into a single line. It will return:
No agta gs to
un pn N ILK
au il
tho kant AN
riz @
ed red TES
co if H
pie [Link] WAR
['Rex', 'Roo', 'Kaa']
sa JA
llo GT
we AP
d! .
Here’s another example. Consider the following file:

Demo 58: flow-control/Demos/states_with_spaces.py

1. Th
def main():
is
d
2. with oopen('../data/[Link]')
cu
m as f:
n e
3. lines t=[Link]().splitlines()
lon
4. N jag gs
5. states_with_spaces = []
6.
7. for line in lines:
8. # Split the line into a 2-item list containing the
9. # state name and abbreviation
10. state = [Link]('\t')
11.
Th
is # If the state name has a space, add it to states_with_spaces
12. do
cu
13. if m ' en
' in state[0]:
tb
14.
elo
states_with_spaces.append(state[0])
n
No jagta gs to
15. un p NI
au nilka LK
t
16. h o
# Print the states_with_spaces
riz
n t @ ANT list
ed red ES
17. for i, state_name cin op iff . H W
enumerate(states_with_spaces, 1):
ies com AR
18. print(f'{i}. {state_name}') all J AG
ow TA
ed P.
19. !
20. main()

Code Explanation
Th
is
This reads in thedcontent
oc
um of the [Link] file and then splits it into a list of lines. It then loops through that list to
create a new list of justenthe
t b states that have spaces in their names. It will output:
elo
n
No jagta gs to
un pn NI
au il LK
tho kant
1. New Hampshire riz @ ANT
ed re ES
co diff.c HW
2. New Jersey pie o AR
sa m JA
3. New Mexico llo GT
we AP
d! .
4. New York
5. North Carolina
6. North Dakota
7. Rhode Island
8. South Carolina
Th
is
9. South Dakota
d oc
me u
10. West Virginia n tb
elo
n
No agta gs to
j
un pn NI
auloopilwith LK
You could replace the for tho kant a couple of list comprehensions, like this:
riz @ ANT
ed r e E SH
co diff.c WA
p i
Demo 59: flow-control/Demos/states_with_spaces2.py
es o m R
all JA
ow GT
ed AP
! .
-------Lines 1 through 4 Omitted-------
5. states = [[Link]('\t')[0] for line in lines]
6. states_with_spaces = [state for state in states if ' ' in state]
-------Lines 7 through 12 Omitted-------
Th
is
do
cu
men
Code Explanation tb
elo
jag ng
N s
1. The first list comprehension gets all the state names from the lines in the file.

2. The second list comprehension then uses that list to get just the state names that have spaces in them.

This could also be done in a single step like this:

Th
Demo 60: flow-control/Demos/states_with_spaces3.py
is
do
cu
me
nt
-------Lines 1 through be 4 Omitted-------
lon
ja g
5. N ou
states_with_spacesg tap s to = [
na n N
6. uth ilkan ILKA # Get state
[Link]('\t')[0]
ori t@ N
z red TES
7. for line in edlines co if ForHeach line
#
pie [Link] WAR
8. sa
if ' ' in [Link]('\t')[0] JA# Where there is a space in state
llo GT
we AP
9. ] d! .
-------Lines 10 through 15 Omitted-------

Code Explanation

Th
is
While that’s a bit dharder
oc to read, the code is more efficient, because it doesn’t have to loop through lines and then
um
loop again through states.
en It just does all the work the first time through the loop.
tb
elo
N jag ngs
Conclusion o una tapnilk to NIL
uth a K
ori nt@ ANT
In this lesson, you have learned z r ES
e if-elif-else
edto write conditions and to loop through sequences. You also
co diff.c HW
learned about the enumerate() function, p i es o m A
generators,
R and list comprehensions.
all JA
ow GT
ed AP
! .

Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
jag ng
N s

You might also like