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

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

While-loop

While keyword is used to repeatedly perform an action as long as a specified condition is met.
Expand/Shrink
Zdroj: (while-loop1.py)
  1   i = 0
  2   while i < 5:
  3       i += 1
  4       print "looping", i
  5   
  6   print "end", i
stdout:
looping 1
looping 2
looping 3
looping 4
looping 5
end 5
Doba běhu: 21.4 ms
The following example demonstrates usage of the while-loop in an iterative solution of an equation (x3-x-1=0). The computation is carried out until the difference between two successive steps is smaller than the specified value.
Expand/Shrink
Zdroj: (while-loop2.py)
  1   x = 2
  2   oldx = 1  # this value is immediatelly discarded, so almost any value will do
  3   while abs( oldx-x) > 0.000001:
  4       oldx = x
  5       x = (1+x)**(1/3.0)  # get the next iteration for x
  6       print "%f (%f)" % (x, abs( oldx-x))
stdout:
1.442250 (0.557750)
1.346677 (0.095573)
1.328876 (0.017801)
1.325507 (0.003369)
1.324868 (0.000639)
1.324746 (0.000121)
1.324723 (0.000023)
1.324719 (0.000004)
1.324718 (0.000001)
Doba běhu: 20.9 ms