How To Use Loops in Python
Loops are a key programming construct in Python that allow you to execute a block of code repeatedly. The two most common types of loops are for
loops and while
loops. For
loops are used to iterate over a sequence of values, such as a list, and execute a block of code for each value.
While
loops are used to execute a block of code repeatedly while a certain condition is true. Nested loops, where a loop is contained within another loop, are also common. Looping is a powerful way to automate repetitive tasks in programming and is an essential concept to master in Python.
Here are examples of Python scripts that use different types of loops:
- For Loop
- # Example of a for loop that prints the numbers 1 to 5
- for i in range(1, 6):
- print(i)
- # Output:
- # 1
- # 2
- # 3
- # 4
- # 5
- Nested For Loop
- # Example of a nested for loop that prints a multiplication table
- for i in range(1, 11):
- for j in range(1, 11):
- print(i * j, end='\t')
- print()
- # Output:
- # 1 2 3 4 5 6 7 8 9 10
- # 2 4 6 8 10 12 14 16 18 20
- # 3 6 9 12 15 18 21 24 27 30
- # 4 8 12 16 20 24 28 32 36 40
- # 5 10 15 20 25 30 35 40 45 50
- # 6 12 18 24 30 36 42 48 54 60
- # 7 14 21 28 35 42 49 56 63 70
- # 8 16 24 32 40 48 56 64 72 80
- # 9 18 27 36 45 54 63 72 81 90
- # 10 20 30 40 50 60 70 80 90 100
- While Loop
- # Example of a while loop that prints the first 5 even numbers
- count = 1
- num = 0
- while count <= 5:
- if num % 2 == 0:
- print(num)
- count += 1
- num += 1
- # Output:
- # 0
- # 2
- # 4
- # 6
- # 8
In these examples, the for
loop is used to iterate over a sequence of values, the nested for
loop is used to create a multiplication table, and the while
loop is used to print the first 5 even numbers. Understanding how to use different types of loops is an important part of learning to program in Python.
Add new comment
- 297 views