Python loops

Repeat one or more statements


Python loops repeat code, there are two common loops which are for and while loops which we go over in this article.

Loops are a way to do iteration, to repeat code. In general developers follow the priniciple of dont repeat yourself (dry). This means they would rather use a loop than type the same lines of code 1000 times.

Related course: Complete Python Programming Course & Exercises

While loops

While loops look like this:

n = 6
while n > 0:
    print(n)
    print('check it')
    n = n - 1
print('Loop out')
print(n)

The outputs are.

6  
Check it.  
5  
Check it.  
4  
Check it.  
3  
Check it.  
2  
Check it.  
1  
Check it.  
Loop out  
0

python loops

_ Fact 2: _ Loop-break
For example.

while True:
    line = input('>>')
    if line == 'done':
        break
    print(line)
print('Done!')

The output is.

> > asdaa  
> > asdaa
> 
> > sdfsd  
> > sdfsd
> 
> > done  
> > Done!

* * * *

Note: BREAK is jumping out of the current loop! Move to the last line of the module. (Jumping down), in contrast to CONTINUE.

_ Fact 3: _ Jump to the top of the current loop, continue

while True:
    line = input('>>')
    if line[0] == '#':
        continue
    elif line == 'done':
        break
    print(line)
print('Done!')

The output is.

> > qwe  
> > qwe
> 
> > > #Hello  
> > Hello  
> > Hello
> 
> > done  
> > Done!

But the prerequisite is that there is no other loop under that loop, because it essentially jumps out of the current loop and onto the next one.

For loop

_Fact 4: _ Definite loop, which is the for loop

friends = ['Gary' , 'Tom' , 'Curry']
for friend in friends:
    print(friend)
print('Done!')

The output is.

Gary.  
Tom.  
Curry.  
Done!  
for is mainly used for strings, arrays, etc.

_Fact 5: _ The usefulness of the several for's given, such as counting numbers, summing, averaging, filtering out the numbers that fit the requi

_ Fact 6: _ introduces another type of variable, Boolean type, only True and False

_ Fact 7: _ introduces another type of variable, which is None, for example.

smallest = None # is equivalent to a flag value
for value in [2,5,35,23,678,54,12 , 0 , -3]:
    if smallest is None: #judgment is the first time into for loop, which can be understood as start, trigger.
        smallest = value
    elif value < smallest:
        smallest = value
print(smallest)
print('Done')
  • Usually the comparative size is assigned a value to the smallest at the first, but this value is not universal, so use None
  • Note that the IS, here, is very similar to the "==", but much stronger
  • Similarly, there is also is not
  • the double equivalence sign is a common mathematical thing. **