.feed-links {display:none !important;} -->

Python for and while loops

 loop (or loop ) allows you to repeat instructions endlessly as needed.

The while loop

In English " while " means "As long as". To create a loop , you must therefore use this keyword followed by an indication that says when the loop stops.

An example will be more telling:

We want to write this sentence 100 times:

I must not ask a question without raising my hand "

Writing by hand takes a lot of time and a lot of time x 100 is really time consuming, and unreliable, even for the lucky ones who know how to copy and paste. And a good programmer is always a bit of a lazy perfectionist, he'll look for the most elegant way not to repeat code.

>>>  i  =  0 
>>>  while  i  <  10 : 
...      print ( "I must not ask a question without raising the hand" ) 
...      i  =  i  + 1 
... 
I  would  have  not  put  a  issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand 
I  do  have  not  put  a issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand 
I  born do  not  pose  an  issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand 
I  do  have  not  put  an  issue  without  raising  the  hand

The for loop

The loop for allows iterating on an element, such as a character string or a list .

Example:

>>>  v  =  "Hello you" 
>>>  for  letter  in  v : 
...      print ( letter ) 
... 
B 
o 
n 
j 
o 
u 
r

t 
o 
i

Tidy

It is possible to create a loop easily with range :

for  i  in  range ( 0 , 100 ): 
  print ( i )

Stop a loop with break

To immediately stop a loop you can use the keyword break :

>>>  list  =  [ 1 , 5 , 10 , 15 , 20 , 25 ] 
>>>  for  i  in  list : 
...      if  i  >  15 : 
...              print ( "We stop the loop" ) 
...              break 
...      print ( i ) 
... 
1 
5 
10 
15 
We  stop  the  loop

No comments:

Post a Comment