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

121 lines
2.6 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

status: #doc #unfinished
Tags: : #python #programming
links:[[python]]
Date: 2023-05-01
___
# [loop](https://www.w3schools.com/python/python_while_loops.asp) in python
Python has two primitive loop commands:
- while loops
- for loops
## The while Loop
it run if condition is true
```python
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
```sh
1
2
3
4
5
```
## Python For Loops
A `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:
```python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
```
and here is the [[`in` usage in python|in]] usage
### [range()](https://www.w3schools.com/python/ref_func_range.asp) loop specific number of times
To loop through a set of code a specified number of times, start from 0 to N
```python
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:
```python
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:
```python
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1
```
- how it work
![[Pasted image 20230501160831.png|300]]
## continue statement
With the continue statement we can stop the current iteration of the loop, and continue with the next:
- Do not print banana:
```python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
```
--->output
```sh
apple
cherry
```
how it work
![[Pasted image 20230501160908.png|300]]
---
## 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.
```python
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