codescracker


python

Python for Loop



« Previous Tutorial Next Tutorial »


Python for loop is basically used to execute a sequence of code multiple times.

Python for Loop Syntax

Here is the general form to use for loop in python:

for iterating-var in sequence:
	statement(s)

Here, if the sequence contains an expression list, then it is evaluated first. And the first item in the sequence is assigned to the iterating variable, that is, iterating-var. Next, the statement(s) block is executed. Here, each item in the list is assigned to the iterating-var, and the statement(s) block is executed until the entire sequence is completed or exhausted.

Python for Loop Example

Here is an example program, illustrates the concept and use of for loop in python:

# Python for Loop - Example Program

for letter in 'python':
    print("The current letter is ", letter);

Here is the sample run of the above python program:

for loop in python

Here is another program, also demonstrates the use of python for loop. This program uses the range() function to return a list of consecutive integers. The range() function can have one, two, or three parameters/arguments. The range() function must have at least one parameters.

# Python for Loop - Example Program

for val in range(10):
    print(val)

Here is the output produced by the above python program:

python for loop

Here is one more example, also illustrates for loop in python:

# Python for Loop - Example Program

for val in range(10, 20):
    print(val)

Below is the output of the above python program:

python for loop example

More Examples

Here are the list of some more examples on python for loop:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test