for loopswhile loop.for loop.
In its simplest form, a for loop looks like this.
for var in sequence:
statements
def print_elements(seq):
"""Print each of the elements of a sequence."""
for element in seq:
print(element)
This function does the same thing as the following one:
def print_elements_while(seq):
"""Print each of the elements of a sequence."""
index = 0
while index < len(seq):
print(seq[index])
index += 1
for loopsfor loop.
def get_first_name(last_name, names):
'''Get the first name for a last name from a sequence of name pairs.'''
for last, first in names:
if last_name == last:
return first
print(last_name, 'not found in database')
>>> get_first_name('Tanaka', ( ('Smith', 'Ed'), ('Wang', 'Fei'), ('Portillo', 'Constanza') ))
Tanaka not found in database
>>> get_first_name('Portillo', ( ('Smith', 'Ed'), ('Wang', 'Fei'), ('Portillo', 'Constanza') ))
'Constanza'
>>> are_chars_in_positions('Ministry of Silly Walks', [('n', 2), (' ', 8), ('M', 0)])
True
>>> are_chars_in_positions('Ministry of Silly Walks', [('n', 2), (' ', 13), ('M', 0)])
False
rangerange is handy.
range returns a simple tuple-like sequence of integers.
range returns a
sequence of integers from 0 to one less than its argument.
We can see the behavior of range most easily by
converting it to a list or tuple.
>>> list(range(8)) [0, 1, 2, 3, 4, 5, 6, 7]
range returns a sequence of integers from a to
b-1.
>>> list(range(3, 8)) [3, 4, 5, 6, 7]
range returns a sequence of integers from a to
b-1, skipping over every c integers.
>>> list(range(3, 8, 2)) [3, 5, 7]
range is useful when you want to do the same thing a certain number of times;
you can use range(times) as the sequence in the header of a for loop.
>>> list_with_ranges([(2, 6), (10, 15), (22, 25)]) [2, 3, 4, 5, 10, 11, 12, 13, 14, 22, 23, 24]
Answers to problems in these notes