Blog

Python for and while loop

loop is exactly a iteration, which means executing the same block of code over and over, potentially many times. In python we use while and for loop for repeating the process.

For Loop

For loop is the type of iteration to repeat the process, In python we use for and in keyword unlike other programming language. For example we take an name of student in a list :

student = ['ram','hari','sita']
for i in student:
    print(i)

Here i is declared as a new variable to get the value from the student list.

To print the value in range we can declare as :

for x in range(1, 10):
    print(x)

Two dimensional list example that may help you :

students = [
    ['ram', 'hari', '24234'],
    ['sita', 'gita', '12434'],
    ['A', 'B', 'C'],
    ['1', '2', '3']
]

for student in students:
    for user in student:
        print(user)

print(students[2][1])   #to find the index value

While Loop

For the iteration process while loop is easy to implement in python programming language, Comparing to the for loops it performs differently but understanding mechanism is same.

Do while concept only: you can not access directly like other programming language do, but can created using a function. 

Example of while loop

x = 0
while x < 10:
    print(x)
    x += 1

Simple program to understand more on while loop :
Here in the below example , we take the number of student to hold the data in a list and and take the name from users to append in list and finally print the name.

n = int(input("enter how many number :"))
x = 1
users = []
while x <= n:
    lists = input("enter the name in lists:")
    users.append(lists)
    x += 1

for u in users:
    print(u)