• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Python Operators
  • Python Variables
  • Python Modules and Functions
  • Python Input and Output
  • Data Types in Python
  • String in Python
  • String Functions in python
  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements in Python
  • Looping in Python
  • Define Functions in Python
  • Python-Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object in Python
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding in Python
  • Polymorphism
  • static Keyword
  • Operator Overloading Python
  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File
  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object
  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy
  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions
  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL
Home >> python >> Looping in Python

Looping in Python

Welcome to another tutorial, here you will learn about Loops in Python. In programming, looping is a functionality that is frequently used to achieve repetitive task programming. Although, it might vary from iterating each element of an array or strings, to modifying a whole database.

The thumb rule for using loops is:

Suppose, if you are writing a program over and over again, you need to use loops.

Rather than doing this:

>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4

 

Do it like this:

>>> a = []
>>> {run a loop in this line to store 1, 2, 3, 4 in list 

In the second example, looping was used, where we only have to write tedious tasks we have to achieve. With looping, we can achieve an iterative flow for execution.

 

There are two ways to achieve iterative flow in Python.

  • Using the for loop
  • Using the while loop

 

The for loop

Below is the syntax:

for [ELEMENT] in [ITERATIVE-LIST]:
	[statement to execute]
else:
	[statement to execute when loop is over]
	[else statement is completely optional]

 

A for loop is frequently used to iterate elements of lists. Check out the example below with the syntax above.

>>> myList = [8, 9, 2, 3, 4, 6]

 

Suppose, we want to iterate all the elements of the myList list using the for a loop.

for i in myList:
	print (i)

From the above example, the variable i was used to represent all the elements stored in the list, one after the other. Now, our loop will run as many times as there are elements in the lists. E.g. the list myList has 6 elements, so the loop in the above example will run 6 times.

Also, in course of the first iteration, the value of i will be 8, and the next will be 9, and so on till 6, the last iteration. With the continuous action, anyone can easily use these individual list element values inside the loop, just like the above example, we have printed them.

Aside, from this, there are other ways of iterating. Recall, our old traditional way of accessing an element of the list by index i.e. myList[i]. But, in this case, we are using another function range() ( alternatively xrange() can be used). Check out the example below:

>>> range(5)

Output:

[0, 1, 2, 3, 4]

 

Or

>>> range(5, 10)

Output:

[5, 6, 7, 8, 9]

 

Or

>>> range(2, 12, 2)

Output:

[2, 4, 6, 8, 10]

 

Furthermore, we can make use range() function along with the for loop to iterate the index number from 0 to len(myList). Check out the example below:

for i in range(0, len(myList)):
	print (myList[i])

From the example, it is clear that we iterated over a temporary list that contains the index numbers of the original list. Thus, this temporary list is generated using the range() function.

 

The else block in for loop

The else block with the for loop, is executed, immediately after all the elements of the list are iterated, or when there are no elements left to iterate in the list. It is quite proper to say that the else statement is executed at the end of the loop. But, it is optional to use it and if used, it is not frequent.

Check out a more complex example below:

>>> bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]

Now, how do we access each element of the list? we can access each element by using the loop within another loop. This is because, there are lists within a list, thereby, the outer loop will help in accessing each list of the bigList. Also, inside the list, for each element, we will be using another loop.

for i in bigList:
	for j in i:
		print ("Element of list within a list - ", j)

Output:

Element of list within a list - 1 
Element of list within a list - 3 
Element of list within a list - 6 
Element of list within a list - 8 
Element of list within a list - 2 
Element of list within a list - 0 
Element of list within a list - 4 
Element of list within a list - 7 
Element of list within a list - 10 
Element of list within a list - 1 
Element of list within a list - 5 
Element of list within a list - 2 
Element of list within a list - 6

 

The while loop

Below is the syntax for the while loop. 

while [condition]:
	[statement to execute]
else:
	[statement to execute if condition is false]
	[else statement is completely optional]

Also, in the while loop, there is an else block, however, it is optional, and used rarely.

In the first statement, a while loop sets a condition, a statement, and the compiler following the flow of execution first checks the condition provided in the condition block, if the condition holds True, then the statement is executed.

 

After the statement is executed, the compiler checks the condition once more, and if it is True once more, then the statement is again executed, otherwise, the else block is executed (i.e. if provided) or simply the flow control breaks out of the while loop; that if the statement was not mentioned.

Check out the example below:

while True:
	print ("I am printing because the condition is True")

 

In the example, we set our condition to be True, so the compiler will execute the statement the first time. And for the next iteration, the condition will still be True again, and thus the statement will be executed once more. This iteration process will keep on repeating itself and will not end. This kind of loop is called an infinite loop and should be avoided in programs.

This is another example:

i = 0
while i < 5:
	i=i+1
	print ("i =", i)

 

In the example above, the first iteration condition i.e. i<5 is checked, because 0<5, thus the statement is executed. And then, during execution, the value of i is incremented by.

In addition, the for loop is commonly used for iterating elements of a list, and the while loop is capable of serving several purposes, and it can as well iterate a list. also, the logic is quite similar when accessing an element using indices. Check out the example below:

myList = [8, 9, 2, 3, 4, 6]
i = 0
while i < len(myList):
    print (myList[i])
    i = i+1;

 

Also, the below example is for lists within a list.

bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]
i = 0
j = 0
while i<len(bigList):
	while j<len(bigList[i]):
		print (“Element of list within a list -”,bigList[i][j])
		j=j+1;
	i=i+1

 

The continue keyword

This keyword is typically used within loops for altering the loop execution. When using the continue keyword inside the loop will skip the current statement execution, and it will check the condition again. Check out the example below:

>>> name = "TutorialWithExample Python"

 

The example below demonstrates the use of the continue keyword.

for i in name:
	continue
	print (i)

 

From the example above, the code will print nothing. Let’s know why it is so. Now, for the first iteration, the first element of the list name will be picked. (i.e. “s”), the next statement inside the for loop continues, therefore, once this keyword is found, the execution of the rest of the for loop statements is then skipped and the flow gets back to the for loop starting to get the next element and then check the condition. In addition, similar steps are followed by the next element of our string (“t”), and the continue interrupts the flow, and this will repeat all the time the execution flow reaches the continue keyword.

Let’s look at something else. Suppose you want to write a program with a loop that will print only the lowercase letters of the string stored in the name variable, you can use the continue keyword to skip those letters which are not lowercase. This is shown below:

for i in name:
	if not i.islower():
		continue
	print (i)

 

From the example above, the if condition checks if the element i is in lowercase, by using islower() function. But, if the element is not in lowercase then the rest of the statements are simply skipped and the print statement is never executed, but, if the element is in lowercase then the if statement returns False, and the continue statement will not be executed.

From all that we have seen, you will agree with me that the continue keyword works exactly as the while loop.

 

The break keyword

This keyword is used inside the loop to break out of the loop. Take for instance, while iterating over the characters of the string stored in the variable name, and you want to break out of it as soon as the character "T" is encountered. Check out the example below:

for i in name:
	if i == "T":
		break;
	print (i)

 

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.