while loopswhile statements and
for statements.while loop has this form:
while condition:
statements
while statement must be followed by a colon,
the remainder must be indented with respect to the first line, and it
may be a simple statement or a block.
>>> n = 0 >>> while n < 5: print(n) n = n + 1 0 1 2 3 4
n = n + 1 and n = n * 3 using the operators +=, -=, *= and /=, for example, n += 1,
n *= 3
return statement.
def square_until(x, bound):
"""Keep squaring x till it goes over bound, returning that number."""
while True:
if x > bound:
return x
x = x**2
break statement.
def squares_until(x, bound):
"""Keep squaring x till it goes over bound, printing out all the results."""
while True:
if x > bound:
break
print(x)
x = x**2
Answers to problems in these notes