loop in python

There are two ways to implement loops in python:

For Loop

For loop is used to iterate over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Here's the general syntax for a for loop:

main.py
for element in sequence:
    # code to execute in each iteration
65 chars
3 lines

Example:

main.py
# loop through a list of numbers and print each number
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)
116 chars
5 lines

Output:

main.py
1
2
3
4
5
10 chars
6 lines

While Loop

While loop is used when we don't know the number of iterations we need to perform. It keeps iterating until a certain condition is met. Here's the general syntax for a while loop:

main.py
while condition:
    # code to execute in each iteration
57 chars
3 lines

Example:

main.py
# print numbers from 1 to 5 using while loop
num = 1
while num <= 5:
    print(num)
    num += 1
97 chars
6 lines

Output:

main.py
1
2
3
4
5
10 chars
6 lines

gistlibby LogSnag