Loops and Iterations


Loops(repeated steps) have iteration variable that change time through a loop . Often these iteration variable go through a sequence of number

Example 1

n= 5
while n > 0:
    print(n)
    n = n -1
print('Blasoff!')
print (n)

If n > 0 it will do the code inside the loop ,first it will print n then subtract 1 then it will go back to ask if the conditional it still true then it will do this again and again until the conditional it false

Output

5
4
3
2
1
Blasoff!
0

Example 2: infinite loop

n= 5
while n > 0:
    print('monday')
    print('tuesday')
print('Blasoff!')

In this case it will print out monday and tuesday over and over again never stop but you can stop it by use Ctrl + C to interrupt the keybaord


Breaking out of loop

  • The break statement ends the current loop and jump to the statement immediately following the loop
  • It’s like a loop test that can happen anywhere in the body of the loop

Question:

  • What will the following code print out?:

      n = 0
      while True:
          if n == 3:
              break
          print(n)
          n = n + 1
    
  • Ans

      0
      1
      2
    

Notes mentioning this note


ນີ້ຄືກຣາຟທີ່ລິ້ງໄປຫາທຸກໜ້າໃນ garden ນີ້ 🕸️.