Net-informations.com
SiteMap  | About    

Python Loop Statements

Loops are one of the most important features in programming. Loops offer a quick and easy way to do something repeatedly. It can execute a >block of code ]] a number of times.

for loop

In Python for loop is used to iterate over the items of any sequence including the Python list, string, tuple etc.

example

output

In the above example workingDays is a sequence contains a list of working days. When the for loop executed the first item (i.e. Monday) is assigned to the variable "day". After this, the print statement will execute and the process will continue until we rich the end of the list.

range() function in for loop

The range function is actually a very powerful function when it comes to creating sequences of integers. It can take one, two, or three parameters

One parameter

stop: Number of integers to generate upto the specified number(not included).

example

output

Two parameter

example

output

Three Parameter

example

output

While loop

In Python, while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. That means, while loop tells the computer to do something as long as the condition is met.

example

output

Here we have our conditional of x < =5 and x was previously declared and set equal to 0. So, our first item printed out was 0, which makes sense. Next, we increment x and ran the loop again. Of course, once a becomes equal to 5, we will no longer run through the loop.

Else clause on Python while statement

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

example

output

example

output

example

output

Python Infinite Loop

We can program an infinite loop using while statement. If the condition of while loop is always True, we get an infinite loop.

example









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.