create a loop in python

Python has two types of loops: for loop and while loop.

For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Here's an example:

main.py
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
  print(fruit)
75 chars
4 lines

Output:

main.py
apple
banana
cherry
20 chars
4 lines

While Loop

A while loop is used to repeat a set of statements as long as a given condition is True.

Here's an example:

main.py
i = 0
while i < 5:
  print(i)
  i += 1
39 chars
5 lines

Output:

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

In the example above, the loop will continue to run as long as i is less than 5. Inside the loop, we print the current value of i, and then increment i by 1.

gistlibby LogSnag