Python-Ref > Basic usage > Looping > For-loop
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

For-loop

The for-loop is the most widely used form of loop. It sequentially takes all the values from an iterable object and assings them to a specified variable. This variable is then typically used in the body of the for-loop for further procesing.
In python there are several types of iterable objects, the most widely used being the list.
Expand/Shrink
Zdroj: (for-loop1.py)
  1   xs = [1, 2, 3, 'a', 'b', 'hippo']
  2   for x in xs:
  3       print x
stdout:
1
2
3
a
b
hippo
Doba běhu: 20.9 ms
Common iteration over a sequence of positive integers starting from 0 is conveniently performed by using the builtin range() function.
Expand/Shrink
Zdroj: (for-loop2.py)
  1   for i in range( 10):
  2       print i, i**2
  3   
  4   print "range( 8)", range( 8)
stdout:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
range( 8) [0, 1, 2, 3, 4, 5, 6, 7]
Doba běhu: 20.8 ms
Because for loop works for any sequence, it may be also used for strings. In this case it loops over individual characters.
Expand/Shrink
Zdroj: (for-loop3.py)
  1   text = "Hello, how are you?"
  2   for letter in text:
  3       print letter
stdout:
H
e
l
l
o
,
 
h
o
w
 
a
r
e
 
y
o
u
?
Doba běhu: 36.4 ms
Expand/Shrink
Zdroj: (for-loop4.py)
  1   text = "Hello, how are you?"
  2   for letter in text:
  3       print letter, letter.isalpha()
stdout:
H True
e True
l True
l True
o True
, False
  False
h True
o True
w True
  False
a True
r True
e True
  False
y True
o True
u True
? False
Doba běhu: 23.2 ms