CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

11 April, 2022

Python for loop

 Programing Coderfunda     April 11, 2022     Python     No comments   

Python for loop

The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

  1. for iterating_var in sequence:    
  2.     statement(s)    

The for loop flowchart

Python for loop

For loop Using Sequence

Example-1: Iterating string using for loop

  1. str = "Python"  
  2. for i in str:  
  3.     print(i)  

Output:

P
y
t
h
o
n

Example- 2: Program to print the table of the given number .

  1. list = [1,2,3,4,5,6,7,8,9,10]  
  2. n = 5  
  3. for i in list:  
  4.     c = n*i  
  5.     print(c)  

Output:

5
10
15
20
25
30
35
40
45
50s

Example-4: Program to print the sum of the given list.

  1. list = [10,30,23,43,65,12]  
  2. sum = 0  
  3. for i in list:  
  4.     sum = sum+i  
  5. print("The sum is:",sum)  

Output:

The sum is: 183

For loop Using range() function

The range() function

The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is given below.

Syntax:

  1. range(start,stop,step size)  
  • The start represents the beginning of the iteration.
  • The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4 iterations. It is optional.
  • The step size is used to skip the specific numbers from the iteration. It is optional to use. By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.

  1. for i in range(10):  
  2.     print(i,end = ' ')  

Output:

0 1 2 3 4 5 6 7 8 9 

Example - 2: Program to print table of given number.

  1. n = int(input("Enter the number "))  
  2. for i in range(1,11):  
  3.     c = n*i  
  4.     print(n,"*",i,"=",c)  

Output:

Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Example-3: Program to print even number using step size in range().

  1. n = int(input("Enter the number "))  
  2. for i in range(2,n,2):  
  3.     print(i)  

Output:

Enter the number 20
2
4
6
8
10
12
14
16
18

We can also use the range() function with sequence of numbers. The len() function is combined with range() function which iterate through a sequence using indexing. Consider the following example.

  1. list = ['Peter','Joseph','Ricky','Devansh']  
  2. for i in range(len(list)):  
  3.     print("Hello",list[i])  

Output:

Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh

Nested for loop in python

Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times for every iteration of the outer loop. The syntax is given below.

Syntax

  1. for iterating_var1 in sequence:  #outer loop  
  2.     for iterating_var2 in sequence:  #inner loop  
  3.         #block of statements     
  4. #Other statements    

Example- 1: Nested for loop

  1. # User input for number of rows  
  2. rows = int(input("Enter the rows:"))  
  3. # Outer loop will print number of rows  
  4. for i in range(0,rows+1):  
  5. # Inner loop will print number of Astrisk  
  6.     for j in range(i):  
  7.         print("*",end = '')  
  8.     print()  

Output:

Enter the rows:5
*
**
***
****
*****

Example-2: Program to number pyramid.

  1. rows = int(input("Enter the rows"))  
  2. for i in range(0,rows+1):  
  3.     for j in range(i):  
  4.         print(i,end = '')  
  5.     print()  

Output:

1
22
333
4444
55555

Using else statement with for loop

Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the for loop which can be executed only when all the iterations are exhausted. Here, we must notice that if the loop contains any of the break statement then the else statement will not be executed.

Example 1

  1. for i in range(0,5):    
  2.     print(i)    
  3. else:  
  4.     print("for loop completely exhausted, since there is no break.")  

Output:

0
1
2
3
4
for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2

  1. for i in range(0,5):    
  2.     print(i)    
  3.     break;    
  4. else:print("for loop is exhausted");    
  5. print("The loop is broken due to break statement...came out of the loop")    

In the above example, the loop is broken due to the break statement; therefore, the else statement will not be executed. The statement present immediate next to else block will be executed.

Output:

0

The loop is broken due to the break statement...came out of the loop. We will learn more about the break statement in next tutorial.


  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Python While loopPython While loopThe Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tes… Read More
  • Python LoopsPython LoopsThe flow of the programs written in any programming language is sequential by default. Sometimes we may need to alter the flow of the prog… Read More
  • Python break statementPython break statementThe break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loop… Read More
  • Python for loopPython for loopThe for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to tra… Read More
  • Python continue StatementPython continue StatementThe continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement sk… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh
    I had follow these steps to install an configure firebase to my cordova project for cloud messaging. https://medium.com/@felipepucinelli/how...
  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Validate Controller Requests with the Laravel Data Package - 5/19/2025
  • Deployer - 5/18/2025
  • Transform JSON into Typed Collections with Laravel's AsCollection::of() - 5/18/2025
  • Auto-translate Application Strings with Laratext - 5/16/2025
  • Simplify Factory Associations with Laravel's UseFactory Attribute - 5/13/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda