Introduction

Setup

Operators

variable

String

Number

Dtype & Comment

Lists

Tuples

Sets

Dictionaries

if else statement

For Loop

While Loop

iterator & iterable

Pre-Built functions

Function

Decorators

generators

Types of errors

Exceptions Handling

OOP

Regular expression

Create module

OS module

Date module

Random module

Math

Statistics module

Exercise 1

Exercise 2

Exercise 3

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Python for loop

What is for loop?

For loop is used for iterating over a sequence. Here sequence means list, tuple, dictionary, string, or a set. By using for loop a set of statements can be executed.

How for loop works?

In for loop, you will write "for" and then you will take a variable to store the value(like i in the example 1). You can use any word or letter as a variable but can't use a number.
Then write "in" and then that variable name from where you want to take a value and in the end use a colon(:). " in" is used to take values from that variable(from where you want to take the values) and put it in that variable which you wrote after for( in the example i).
In for loop, value comes one by one. If you have 5 values then the first time i variable will have the first value then the second time i will have the second value. This way the process goes on. For each value, all the code written inside the loop will run completely. Suppose you have three values and inside for loop you have three math equations. So each time the loop runs, each time the three equations will be executed. When the loop runs first time, it will work with the three equations and will give an output. When the loop runs second times with the second value it will execute those three equations again. This will happen each time the loop runs. So we can say that if the loop runs three times then the equation or code written inside the loop will also completely run 3 times. The code we write inside the loop execute line by line. It means, first line then the second line then the third line and this way the process goes on.

Example:1
Input
z="Rafsun"
for i in z:
  print(i)
Output
R
a
f
s
u
n

In example 1, we have a string in the z variable. We took the string value characters one by one in a for loop and then print it. The first time R goes to i and then it prints i value means R. Then second time a goes in i and print i means a. This way this process happens.

Example:2
Input
z=["a","b","c","d"]
for i in z:
  print(i)
Output
a
b
c
d

In example 2, you took z variable values in i, one by one and print i(means z variable value which is present in i). So when the loop is running, the first value of z will go in i and will print it and then second and then third and so on. z have first value a then b then c, d. So that's why you got the result
a
b
c
d

Example:3
Input
x=int(input("Enter number:"))
y=0
for i in range(x):
  z=input("Enter your value:")
  y=y+int(z)
  print(y)
Output
Enter number:3
Enter your value:1
1
Enter your value:2
3
Enter your value:3
6
Example:4
Input
x=input("Enter string:")
y=list(x)
for i in range(len(y)):
  if i%2==0
    print(y[i])
Output
Enter string:Spread
S
r
a
Example:5
Input
x=[45,455,233,56745,566,34]
y=x[0]
for i in range(len(x)):
  if x[i]>y:
    y=x[i]
print(y)
Output
56745
Example:6
Input
li=input("Enter:")
for i in range(len(li)):
  print(f"{li[i]}:{i}")
Output
Enter:4321
4:0
3:1
2:2
1:3
Example:7
Input
li=[[1,2,3],[4,5,6],[7,8,9]]
for sublist in li:
  print(sublist)
Output
[1, 2]
[4, 5]
[7, 8]
Example:8
Input
for sublist in l1:
  for i in sublist:
    print(i)
Output
1
2
4
5
7
8

break statement

While using the for loop, if we want to stop the loop at a particular point then use the break statement. Give a condition in for loop and if the condition get matched then the loop will break.

Example:1
Input
num = [1,2,3,4]
for x in num:
  print(x)
  if x == 3:
     break
Output
1
2
3

In the example, the num variable has a list. List have numbers 1-4. You want to print num variable value by using for loop. So you are taking value one by one from num in x. But you want that, if x has value 3 then the loop will stop. So when x gets values 1, 2 it will print the values but when x got value 3 it prints 3 and then the break function runs and the loop is stopped. So you got outputs 1, 2, and 3.

Example:2
Input
num = [1,2,3,4]
for x in num:
  if x == 3:
  print(x)
     break
Output
1
2

continue statement

While using the for loop if we want that the loop will do its work but when it gets a particular value, it will ignore that value but the loop will continue. It means, if there is any work after that point it will do it. In this type of case, we will use continue.

For example, if we want to print numbers 1-5 but don't want to print 3 then we will give the condition if variable==3 then continue. It means don't print it(3). So we will get the output 1,2,4,5. Look one thing, there are two numbers 4 and 5 after 3. It means that continue doesn't break the loop it just ignores the value or work that is given in the condition.

Example:
Input
num = [1,2,3,4,5]
for x in num:
  print(x)
  if x == 3:
     continue
Output
1
2
4
5

range() function

In the range function, we give a range to get numbers. For example, if we want to get numbers 0-10 then we will write 11 in the range function and it will generate numbers 0-10. The range function starts generating numbers from 0(default). So if you write 10 it means 10 numbers. So range function will give numbers from 0-9. So if we want 10 then we have to write 11 in the bracket.

Example:1
Input
for x in range(3):
  print(x)
Output
0
1
2

You can also pass the staring point as like ending point in the range function.

Example:2
Input
for x in range(2, 6):
  print(x)
Output
2
3
4
5

In example 2 we gave starting number 2 and ending number 6. It means the range function will generate numbers from 2-5. So we get results 2,3,4,5

You can also give an increment sequence in the end.

Example:3
Input
for x in range(2,12,3):
  print(x)
Output
2
5
8
11

In example 3 you gave a starting number 2 and ending number 12 and the increment of number is 3. Because the increment number is 3, it means the difference between these two numbers is 3. It means the range function will generate numbers from 2-12 and the number increment is 3 . So you got results 2,5,8,11.

Use of pass

for loop cannot be empty, but if we have for loop with no content, then put the pass statement to avoid getting an error.

Example:
Input
for x in [0, 1, 2]:
   pass
Output

Nested for loop in python

We can use for loop inside a for loop and it's called nested for loop.
Working process is, at first main for loop or outer loop will run 1 time then the inner loop will run completely. Then the main loop or outer loop will run again and then the inside or inner loop will run completely again. This process will continue until the main loop ends.

Example:1
Input
num = [1,2,3]
content = ["yes", "no", "very good"]
for x in num:
  for y in content:
    print(x, y)
Output
1 yes
1 no
1 very good
2 yes
2 no
2 very good
3 yes
3 no
3 very good

Here the main loop is x and the inner loop is y and in num and content variable both have 3 values. So this loop will run three times. So at first, the main loop or outer will run once and the inner loop will three times. After the inner loop is completed its maximum run then again the main loop or outer will run once then again inner loop will run three times. Then again main loop and then inner loop. This way nested loop works.

Example:2
Input
for x in range(1,5):
  for y in range(1,5):
    print(x, y)
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Example:3
Input
for x in range(1,11):
  for y in range(1,11):
    print(i*j,end=" ")
  print("\t\t")
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
Example:4
Input
for i in range(4):
  for j in range(i+1):
    print("@", end=" ")
  print()
Output
@
@ @
@ @ @
@ @ @ @
Example:5
Input
for i in range(4):
  for j in range(4-1):
    print("@",end=" ")
  print()
Output
@ @ @
@ @ @
@ @ @
@ @ @
Example:6
Input
l1=[9,1,4,2,5,6,8]
l2=[5]
l3=[]
for i in range(len(l1)):
  for j in range(len(l2)):
    if l1[i]==l2[j]:
      l3.append(l1[i])
      print(l3,"--------" "index number is:",i)
Output
[5] --------index number is: 4
Example:7
Input
l1=[1,2,3,4,5,6,7,8,9]
l2=[11,12,13,14,15,16,17,18,19]
a=[]
for i in range(len(l1)):
  if l1[i]%2!=0:
    a=l1[i]
for j in range(len(l2)):
  if l1[j]%2!=0:
    a=l1[j]
print(a)
Output
9

Python else statement in for loop

By else statement you can run a block of code one time when the condition become false or not true.

Example:8
Input
for i in range(6):
   print("Love SelfTaught.com",i)
else:
  print("Finish.You reached the maximum number")
Output
Love this site1
Love this site2
Love this site3
Love this site4
Love this site5
Finish.You reached the maximum number

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.