Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - For Loop

Python

python logo

In this tutorial we will learn about for loop in Python.

We use for loop in Python to iterate over a sequence which can be a string, list, tuple, set or dictionary.

The for syntax

Following is the syntax of for loop in Python.

for iterate_variable in sequence:
  #
  # body of the for loop
  #

On every iteration an item is taken from the sequence and assigned to the iterate_variable. Then the code inside the body of the for loop is executed.

String and for loop

We can use the for loop to iterate over the characters of a string and print the characters.

In the following Python program we are listing all the characters of a string.

# string
str = 'Hello World'

for ch in str:
  print(ch)

print("End of code.")

The above code will print the following output.

H
e
l
l
o
 
W
o
r
l
d
End of code.

List and for loop

We can use the for loop to iterate over the items of a list.

In the following Python program we are listing all the items of the list.

# list
list = [1, 2, 3, 1, 3]

for item in list:
  print(item)

print("End of code.")

We will get the following output.

1
2
3
1
3
End of code.

Tuple and for loop

We can use the for loop to iterate over the items of the tuple.

In the following Python code we are printing out all the items of the tuple.

# tuple
tuple = ('Yusuf Shakeel', 9.1, True)

for item in tuple:
  print(item)

print("End of code.")

The above code will print the following output.

Yusuf Shakeel
9.1
True
End of code.

Set and for loop

We can use for loop to access the items of the set.

In the following Python code we are listing all the items of the set.

# set
set = {1, 2, 3, 'Hello'}

for item in set:
  print(item)

print("End of code.")

We will get the following output.

1
2
3
Hello
End of code.

Dictionary and for loop

We can use for loop to iterate through the key-value pairs of a dictionary.

In the following example we are listing all the key value pairs of a dictionary.

# dictionary
dictionary = {
    'name': 'Yusuf Shakeel',
    'score': 9.1,
    'isOnline': True
}

for key in dictionary:
  print(key, "=", dictionary[key])

print("End of code.")

The above code will print the following result.

name = Yusuf Shakeel
score = 9.1
isOnline = True
End of code.

When working with dictionary we will get the key of the dictionary in each iteration.

To get the value of a particular key we use dictionaryVariableName[key].

The break statement

We use the break statement to jump out of the for loop.

In the following Python program we are printing the letters present in a name. But we will exit the for loop as soon as we encounter any vowel (both lowercase and uppercase).

name = 'Yusuf Shakeel'

for l in name:

    # check
    if l in "aeiouAEIOU":
        break

    # print
    print(l)

print("End of code.")

This will print only the letter Y as the second letter is one of the vowel and we will break out of the for loop.

Y
End of code.

The continue statement

We use the continuestatement to skip an iteration and move to the next item in the for loop sequence.

In the following example we have a name and we are printing the letters in the name. But we are skipping all the vowels (lowercase and uppercase).

name = 'Jane Doe'

for l in name:

    # check
    if l in "aeiouAEIOU":
        continue

    # print
    print(l)

print("End of code.")

We will get the following output.

J
n
 
D
End of code.

The range function

The range function returns a sequence of numbers starting from 0 and incrementing by 1.

Syntax

Following is the syntax of range() function.

range(start, stop, step)

Where, start is the starting number. Default is 0.

stop is the number at which position range will stop but not including it.

step is the incrementation. Default is 1.

If we want to have a sequence 0, 1, 2, 3 and 4 we will write the following.

range(0, 5)

Note! We are writing 5 as range() will begin from start and end at stop - 1.

If we want to have a sequence 5, 4, 3, 2 and 1 we will write the following.

range(5, 0, -1)

The else in for

The else block with the for loop contains piece of code that is executed after the for loop ends.

In the following Python program we will get "End of for loop" after the for loop ends iterating the items in the sequence.

for i in range(1, 4):
  print(i)
else:
  print("End of for loop")

print("End of code.")

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT