Python for Loop

Python for Loop

Python for Loop

In this tutorial, you will learn about what is Python for Loop ? and different variations of using it in your code.

What is Python for loop?

Python for loop is used to repeat or iterate a list, tuple or string in a sequential manner.

 

Syntax of for loop


Now I will explain what the above Python for loop syntax means. Here the variable repeating_variable we use you can use whatever you want now in sequence we will set the limit of time for we want to iterate the block of code. The block of for loop keeps iterate until the limit we set in the sequence finished.

Python for loop FlowChart

Python-for-Loop-flow-chart

Example: Python for Loop

When you execute the code you will get the following results:

Python range() function

The range() function is also handy in generating numbers sequentially.

For example range(20) displays the numbers on the screen from 0 to 19 (all 20 numbers).  In some cases, we want to define the numbers from where to start, where stop and what should be the step size of the range(). But if we don’t define step size it is 1 by defaults.

Remember: The range() function generates the up-coming number by remembering the start, stop and step size and it does not keep/store all the record in his memory

Recommended:  Python Variables,Data Types and Type Conversion

See the example below:

The range() function can also be combined with for loop to iterate numbers sequentially through the loop. len() function is used to iterate using the indexing.
See the below example:

When you execute the code the output will be as:

Recommended:  Decision Making Statements In Python Programming Language

for loop with else

An optional else statement can also be used with loop statement available in python programming.  The else block executed right after the iteration of for loop finishes execution. At any point in the code, you want to stop the for loop you can use break statement but in this case, all the else part will be ignored.

See the below example:

After the code is executed the following result will be displayed.

 

Jack Sparrow

Hay I am Admin Of This Website. I am very passionate about Computers and technology. This website is the result of my passion. I love to eliminate the barriers comes in the for seeking education. This website is the free source of learning about new technology and up to date knowledge.

Leave a Reply

Close Menu