More Looping Structures: While Continue Break
More Looping Structures: While Continue Break
False
<indentedcodeblock>
<nonindentedstatement>
while loop
Example: compute the
smallest multiple of 7
greater than 37.
Idea: generate multiples of 7
until we get a number
greater than 37
>>>i=7
>>>whilei<=37:
>>>
i+=7
>>>i
42
i=7
True
i<=37?
i+=7
False
Exercise
Write function getNegativeNumber() that uses a
while loop to:
prompt a user for input as many times as
necessary to get a negative number
return the negative number
Should the return statement be inside the while
loop or after it? Why?
1
+
2
+
3
+
5
+
8
+
13
+
21
+
34
+
55 . . .
+
Fibonacci
less than
Fibonacci
Whatisyourname?
Whatisyourname?Tim
What
is your name? Tim
HelloTim
Hello
Tim
Whatisyourname?
What
is your name? Alex
Hello Alex
What is your name?
def hello2():
'''a greeting service that repeatedly request the name
of the user and then greets the user'''
while True:
name = input('What is your name? ')
print('Hello {}'.format(name))
>>> cities()
Enter city: Lisbon
Enter city: San Francisco
Enter city: Hong Kong
Enter city:
['Lisbon', 'San Francisco', 'Hong
Kong']
>>>
whileTrue:
city=input('Entercity:')
ifcity=='':
returnlst
lst.append(city)
defcities2():
lst=[]
whileTrue:
city=input('Entercity:')
ifcity=='':
break
lst.append(city)
returnlst
In both cases, if the current loop is nested inside another loop, only the
innermost loop is affected
def before0(table):
for row in table:
for num in row:
if num == 0:
break
print(num, end=' ')
print()
>>> table = [
[2, 3, 0,
[0, 3, 4,
[4, 5, 6,
6],
5],
0]]
def ignore0(table):
for row in table:
for num in row:
if num == 0:
continue
print(num, end=' ')
print()
>>> before0(table)
2 3
4 5 6
>>>
2 3
3 4
4 5
ignore0(table)
6
5
6