Professional Documents
Culture Documents
3-4 For Loop
3-4 For Loop
for k in range(1,6):
print(k)
Basic for construct
•for k in range(first, last-1):
• The basic for construct •for k in range(first, last-1, increment):
for index in range( j, k): •loop 수행횟수
statements floor((last-first)/increment)+1
•floor(x)
for index in range( j, k, m): rounds x down towards –inf
statements ex) for k in range(1, 6, 2)
floor((6-1)/2)+1=floor(5/2)+1=3
for k in range(1,5):
print(k) 1
2
for k in range(1,5,2): 3
print(k) 4
1
* Program displays 1 – 100? 3
Looping Through Arithmetic Progres-
sion of Numbers
Example
• Factorials!
fact = 1
for k in range(1,10):
fact = k * fact
• Compute 10! print(fact)
More general for
• more general for
for index in v
– v: list or vector
for k in [2, 3, 5, 7]: x = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(k) n=[2, 3, 5, 7]
for k in n:
print(x[k])
Example
• Compute the sum of 1, 3, 7 using for-
loop and list [1, 3, 7].
num = 0
for k in [1, 3, 7]:
num = ????????
ch3.4
51, 55, 56, 59, 60, 64, 67, 72, 73
Relational and Logical Operators
• A condition is an expression
– Involving relational operators (such as < and
>=)
– Logical operators (such as and, or, and not)
– Evaluates to either True or False
• Conditions used to make decisions
– Control loops
– Choose between options
The for Loop
• Used to iterate through a sequence of val-
ues
• General form
of a for loop
• Sequence can be
– Arithmetic progression of numbers
– String
– List
– File object
The for Loop
• Variable is successively assigned each
value in the sequence
:
Looping Through Arithmetic Progression
of Numbers
• Example 2: Program displays a table
showing the population each year until
2018.
Looping Through Arithmetic Progression
of Numbers
• Example 3, cont.
Step Values for the range Function