Looping in Python
Python provides two types of loops: for and while.
while
The while loop repeats a block until the test condition remains true. You can come out of the loop using break and continue.
Also, to decide if the loop repeats as per the test condition after which the else condition executes. This is an additional feature
in Python.
Example: Ask the user to enter a number and calculate its factorial.
The factorial of a number n is defined as 1 × 2 × 3 × ... × n
The factorial of a number, n, is the product of n terms starting from 1. To calculate the factorial of a given number, first of all the user is asked to input a number. The number is then converted into an integer.
n = input("Enter Number: ")
m = int(n)
factorial = 1
i = 1
while i <= m:
factorial = factorial * i
i = i + 1;
print("Factorial: " + str(factorial))
for
The for loop can be used to iterate through a list, tuple, string, or a dictionary.
for i in L:
#do something
When you write " i in L", where L is a list, i becomes the first element of the list and as the iteration progresses, i becomes the second element, the third element and so on.