In Python, loops are used to iterate over a sequence of values or to repeat a block of code a specified number of times. There are two types of loops in Python: for loops and while loops.
For Loops
The for loop is used to iterate over a sequence of values. The basic syntax for a for loop in Python is as follows:
for item in sequence: # code to be executed for each item in the sequenc
Here, sequence is the sequence of values to be iterated over, and item is a variable that will take on each value in the sequence in turn. For example, you might use a for loop to iterate over the characters in a string:
for char in "hello": print(char)
This code will output:
h
e
l
l
o
While Loops
The while loop is used to repeat a block of code as long as a specified condition is true. The basic syntax for a while loop in Python is as follows:
while condition: # code to be executed as long as the condition is true
Here, condition is the condition to be checked before each iteration of the loop. For example, you might use a while loop to repeat a block of code until a user enters a valid input:
while True: user_input = input("Enter a number between 1 and 10: ") if user_input.isdigit() and 1 <= int(user_input) <= 10: break else: print("Invalid input")
This code will keep asking the user to enter a number until they enter a valid number between 1 and 10.
Loop Control Statements
In addition to for and while loops, Python also provides several loop control statements that allow you to control the flow of a loop:
- break: Terminates the loop and exits the current block of code.
- continue: Skips the current iteration of the loop and moves on to the next one.
- pass: Does nothing and allows the loop to continue without executing any code.
For example, the following code will print the numbers from 0 to 4, but will skip the number 2:
for num in range(5): if num == 2: continue print(num)
This code will output:
0
1
3
4