alternative
  • Home (current)
  • About
  • Tutorial
    Technologies
    SQL -Structured Query Language
    Python
    Ethical Hacking
    Java
    .net Framework
    Placement Preparation
    Quantitative Aptitude
    View All Tutorial
  • Quiz
    SQL -Structured Query Language
    Quantitative Aptitude
    Java
    View All Quiz Course
  • Q & A
    Quantitative Aptitude
    Java
    View All Q & A course
  • Programs
  • Articles
    Artificial Intelligence & Machine Learning Project
    How to publish your local website on github pages with a custom domain name?
    How to download and install Xampp on Window Operating System ?
    How To Download And Install MySql Workbench
    How to install Pycharm ?
    How to install Python ?
    How to download and install Visual Studio IDE taking an example of C# (C Sharp)
    View All Post
  • Tools
    Program Compiler
    Sql Compiler
    Replace Multiple Text
    Meta Data From Multiple Url
  • Contact
  • User
    Login
    Register

Python - Decision control and looping statement - for loop Tutorial

 

The Python for loop is used to iterate over an element of sequence or data structure ( List, Tuple, String, Dictionary).

Classification of for loop using different type:-

1] Using Range(N) Function

Syntax-

range(start, stop, step size)

Start and Step size is optional.

By default, Start is 0 and Step size is 1 if not provided

 

If we use range(n), where n is an integer, then it will print an integer from 0 to n-1.

For example-

Using range(7), it will print an integer from 0 to 6

# Using range(n) will print  integer from 0 to n-1
for a in range(7):
    print(a)

 

Run Program

Output- 

0
1
2
3
4
5
6

If we use range(a, b), it will print an integer from a to b-1

For example-

Using range(3,6), it will print an integer from 3 to 5

# Using range(a,b) will print  integer from a to b-1
for a in range(3,6):
    print(a)

 

Run Program

Output- 

3
4
5

If we use range(a, b, c), it will print an integer from a to b-1 and will skip the number by c.

For example-

# Using range(start,stop, step size) or range(a,b,c)
# Will print integer from a to b-1.
# Will skip the number by c
for a in range(3,11,2):
    print(a)

Run Query

Output- 

3
5
7
9

To use the range function to output all items in the list.

For example-

# To use range function to output all items in the list.
# We can use List()
print(list(range(7)))
print(list(range(3,6)))
print(list(range(3,11,2)))

Run Program

Output-  

[0, 1, 2, 3, 4, 5, 6]
[3, 4, 5]
[3, 5, 7, 9]

Using For with else

Here, else will be only executed it for loop is exhausted

For Example -

for i in [1,2,3,4]:
    print('fresherbell')
else:
    print('hola')

Output-

fresherbell
fresherbell
fresherbell
fresherbell
hola

2] Using String

# Using String
String = 'Fresherbell'
# iterate over the String
for i in String:
    print(i)

Run Program

Output-   

F
r
e
s
h
e
r
b
e
l
l

3] Using List

  • Number
# List of number
number = [4, 1, 2, 27, 25, 73]
# iterate over the list of number
for val in number:
    print(val)

Run Program

Output-    

4
1
2
27
25
73
  • String
# List of String
String = ['Mon', 'Tue', 'Wednes', 'Thurs', 'Fri', 'Satur', 'Sun']
# iterate over the list of String
for val in String:
    print(val+"day")

Run Program

Output-     

Monday
Tueday
Wednesday
Thursday
Friday
Saturday
Sunday
  • Range Function

Printing the List using Range function combined with Len function.

# List of String
String = ['Mon', 'Tue', 'Wednes', 'Thurs', 'Fri', 'Satur', 'Sun']
# iterate over the list of String with range and len function
for val in range(len(String)):
    print(String[val]+"day")

Run Program

Output-      

Monday
Tueday
Wednesday
Thursday
Friday
Saturday
Sunday

4] Nested For Loop

For loop inside For loop is known as Nested For Loop. In the nested for loop, the inner loop will be executed n number of times for every iteration of the outer loop.

For example-

# a for loop will executed 3 time i.e from 1 to 3
# b for loop will executed 3 time i.e from 2 to 4
# Hence total time loop wil be executed is 3 * 3 = 9
for a in range(1,4):
    for b in range(2,5):
        print("a="+str(a)+" b="+str(b))

Run Program

Output-       

a=1 b=2
a=1 b=3
a=1 b=4
a=2 b=2
a=2 b=3
a=2 b=4
a=3 b=2
a=3 b=3
a=3 b=4

Accessing nested list using for loop

For Example-

a = [[10,20] , [20,30] , [30,40]]

for i in a:
    print(i)


for i in a:
    for j in i:
        print(j)

Output-

[10, 20]
[20, 30]
[30, 40]
10
20
20
30
30
40

Pyramid using nested for loop

# a for loop will executed 5 time i.e from 1 to 5
# b for loop will executed a time
for a in range(1,6):
    for b in range(a):
        print("*",end=" ") #end=" " will print space after every *
    print() #Start with new Line

Run Program

Output-        

* 
* * 
* * * 
* * * * 
* * * * * 

5] Backward Iteration

To iterate the for loop in the backward direction, we will use the following for loop techniques-

  • Using reversed() function

The reversed function will reverse the whole element of sequence or data structure ( List, Tuple, String, Dictionary).

For example-

# List of String
String = ['Mon', 'Tue', 'Wednes', 'Thurs', 'Fri', 'Satur', 'Sun']
# iterate over the list of String in reverse order
for val in reversed(String):
    print(val+"day")

Run Program

Output-         

Sunday
Saturday
Friday
Thursday
Wednesday
Tueday
Monday
  • Using List Comprehension

In this, the loop will start from the end and go backward till the first position, because the start and stop are empty.

The step size is given as -1, hence it will decrement the loop by 1.

For example-

# List of String
String = ['Mon', 'Tue', 'Wednes', 'Thurs', 'Fri', 'Satur', 'Sun']
# iterate over the list of String in reverse order using list comprehension method
for val in String[::-1]:
    print(val+"day")

Run Program

Output-          

Sunday
Saturday
Friday
Thursday
Wednesday
Tueday
Monday

In this, the loop will start from 5 and will stop at 1, step size is given as -1, hence it will decrement the loop by 1.

For example-

# List of String
String = ['Mon', 'Tue', 'Wednes', 'Thurs', 'Fri', 'Satur', 'Sun']
# iterate particular list of String in reverse order using list comprehension method
for val in String[5:1:-1]:
    print(val+"day")

Run Program

Output-     

Saturday
Friday
Thursday
Wednesday
  • Using Range(N, -1, -1)

In this, the loop will start from the last position i.e ( length_of_list -1 ), and stop at the first position, the step size is given as -1, hence it will decrement the loop by 1.

For example-

# List of String
String = ['Mon', 'Tue', 'Wednes', 'Thurs', 'Fri', 'Satur', 'Sun']
# iterate particular list of String in reverse order using range(N,-1,-1)
for val in range(len(String)-1,-1,-1):
    print(String[val]+"day")

Run Program

Output-     

Sunday
Saturday
Friday
Thursday
Wednesday
Tueday
Monday

 

Python

Python

  • Introduction
  • Installation and running a first python program
    • How to install Python ?
    • Running 1st Hello World Python Program
    • How to install Pycharm ?
  • Things to know before proceed
    • Escape Characters/Special Characters
    • Syntax ( Indentation, Comments )
    • Variable
    • Datatype
    • Keyword
    • Literals
    • Operator
    • Precedence & Associativity Of Operator
    • Identifiers
    • Ascii, Binary, Octal, Hexadecimal
    • TypeCasting
    • Input, Output Function and Formatting
  • Decision control and looping statement
    • if-else
    • for loop
    • While loop
    • Break Statement
    • Continue Statement
    • Pass Statement
  • Datatype
    • Number
    • List
    • Tuple
    • Dictionary
    • String
    • Set
    • None & Boolean
  • String Method
    • capitalize()
    • upper()
    • lower()
    • swapcase()
    • casefold()
    • count()
    • center()
    • endswith()
    • split()
    • rsplit()
    • title()
    • strip()
    • lstrip()
    • rstrip()
    • find()
    • index()
    • format()
    • encode()
    • expandtabs()
    • format_map()
    • join()
    • ljust()
    • rjust()
    • maketrans()
    • partition()
    • rpartition()
    • translate()
    • splitlines()
    • zfill()
    • isalpha()
    • isalnum()
    • isdecimal()
    • isdigit()
    • isidentifier()
    • islower()
    • isupper()
    • isnumeric()
    • isprintable()
    • isspace()
    • istitle()
  • Python Function
    • Introduction
  • Lambda Function
    • Lambda Function
  • Python Advanced
    • Iterators
    • Module
    • File Handling
    • Exceptional Handling
    • RegEx - Regular Expression
    • Numpy
    • Pandas

About Fresherbell

Best learning portal that provides you great learning experience of various technologies with modern compilation tools and technique

Important Links

Don't hesitate to give us a call or send us a contact form message

Terms & Conditions
Privacy Policy
Contact Us

Social Media

© Untitled. All rights reserved. Demo Images: Unsplash. Design: HTML5 UP.