The sea does not like to be restrained.
Emektar Üye
- Katılım
- 15 Tem 2021
- Mesajlar
- 1,724
- Çözümler
- 86
- Tepki puanı
- 665
- Ödüller
- 10
- Yaş
- 25
- Sosyal
4 HİZMET YILI
In Python, loops are used to execute a block of code multiple times. The two main types of loops in Python are for loops and while loops.
Here's an example of a for loop:
In this example, we use the range() function to generate a sequence of numbers from 0 to 4, and then use a for loop to iterate over each number in the sequence. The output would be:
You can also use a for loop to iterate over the elements in a list or other iterable object. For example:
In this example, we define a list of fruits and use a for loop to iterate over each fruit in the list. The output would be:
Here's an example of a while loop:
In this example, we use a while loop to execute the code inside the loop as long as the condition i < 5 is true. The code inside the loop first prints the value of i and then increments i by 1 using the += operator. The output would be the same as the for loop example:
In both types of loops, you can use the break and continue statements to control the flow of the loop. The break statement is used to exit the loop completely, while the continue statement is used to skip over the current iteration of the loop and move on to the next one.
Here's an example of a for loop:
Python:
for i in range(5):
print(i)
In this example, we use the range() function to generate a sequence of numbers from 0 to 4, and then use a for loop to iterate over each number in the sequence. The output would be:
Python:
0
1
2
3
4
You can also use a for loop to iterate over the elements in a list or other iterable object. For example:
Python:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this example, we define a list of fruits and use a for loop to iterate over each fruit in the list. The output would be:
Python:
apple
banana
cherry
Here's an example of a while loop:
Python:
i = 0
while i < 5:
print(i)
i += 1
In this example, we use a while loop to execute the code inside the loop as long as the condition i < 5 is true. The code inside the loop first prints the value of i and then increments i by 1 using the += operator. The output would be the same as the for loop example:
Python:
0
1
2
3
4
In both types of loops, you can use the break and continue statements to control the flow of the loop. The break statement is used to exit the loop completely, while the continue statement is used to skip over the current iteration of the loop and move on to the next one.