7.2. Looping - JulTob/Python GitHub Wiki
In Python, we can iterate in different forms.
π While the statement is True, the code inside the block will be executed
while <TestExpression>: 0 to β times
<Block>
Romani_ite_domum = 1
while Romani_ite_domum <= 100:
print("Romani ite domum")
Romani_ite_domum += 1
print("And don't do it again")
loop_condition = True
while loop_condition:
print("Loop Condition True")
loop_condition = False
else:
print("Loop Condition False")
π¦ The loop condition is True so it keeps iteratingβββuntil we set it to False.
i=0
while i<10:
print i
i= i+1
def print_numbers(n):
i=1
while i<=n:
print i
i= i+1
def factorial(n):
fact=1
i=1
while i<=n:
fact=i*fact
i= i+1
return fact
while <TestExpression>: 0 to β times
<Block>
if <BreakTest>:
break
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
for i in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10:
print(i)
for i in range(1, 100): # 1 .. 99
print(i)
for i in range(1, 100, 2): # 1, 3, 5, ..+2.. , 96, 99
print(i)
for i in range(100): # 0 .. 99
print(i)
for i in range(1, -100, -1): # 1 , 0, -1 .. -99
print(i)
for i in range(21, 0, -3)
print(n, end=' ')
# 21 18 15 12 9 6 3
primes = [2, 3, 5, 7]
for number in primes:
print(number)
for c in βwordβ:
print(c)
> w
> o
> r
> d
Terminates loop.
Skip iteration.
Null statement.
for i in range(100): # 0 .. 100
if i % 4 = 0:
continue
print(i )
if i > 90:
break
for n in numbers:
if n % 2 == 0:
print (n)
if n == 237:
break
Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status