ob-vaults/Phoenix/Python/loop in python.md
2024-09-12 17:54:01 +03:30

2.6 KiB

status: #doc #unfinished Tags: : #python #programming links:python Date: 2023-05-01


loop in python

Python has two primitive loop commands:

  • while loops
  • for loops

The while Loop

it run if condition is true

i = 1
while i < 6:
  print(i)
  i += 1

here it run till i = 6 so if i is less then 6 condition is true else it become false --->output

1
2
3
4
5

Python For Loops

for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) its not like other programming language

  • Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]  
for x in fruits:  
  print(x)

and here is the [[in usage in python|in]] usage

range() loop specific number of times

To loop through a set of code a specified number of times, start from 0 to N

for x in range(6):  
  print(x)

Note

range(6) is not the values of 0 to 6, but the values 0 to 5.

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

  • Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):  
  print(x)  
else:  
  print("Finally finished!")

Note

The else block will NOT be executed if the loop is stopped by a break statement.

break statement

With the break statement we can stop the loop even if the condition is true:

  • Exit the loop when i is 3:
i = 1  
while i < 6:  
  print(i)  
  if i == 3:  
    break  
  i += 1

continue statement

With the continue statement we can stop the current iteration of the loop, and continue with the next:

  • Do not print banana:
fruits = ["apple", "banana", "cherry"]  
for x in fruits:  
  if x == "banana":  
    continue  
  print(x)

--->output

apple  
cherry

how it work !Pasted image 20230501160908.png


The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:  
  pass

References

https://www.w3schools.com/python/python_while_loops.asp https://www.w3schools.com/python/python_for_loops.asp https://www.programiz.com/python-programming/break-continue