Python for Keyword



The Python, for keyword is used for looping. It is a case-sensitive keyword. If we know the numbers of time the loop runs in advance, we use for in such cases. It is used to iterate over a sequence[list, tuple, string, dictionary, set].

Syntax

Following is the syntax of Python for keyword −

for 

Example

Following is an basic example of Python for keyword −

str1 = "Tutorialspoint"
for i in str1:
    print(i, end=" ")

Output

Following is the output of the above code −

T u t o r i a l s p o i n t

Using 'for' keyword in List

The for keyword can also be used in list to iterate it.

Example

Following is an example to iterate the list using for keyword −

list1 = ["Java", "C++", "Python", "HTML"]
for i in list1:
    print(i)

Output

Following is the output of the above code −

Java
C++
Python
HTML

Using 'for' Keyword in Functions

We can use for keyword inside the function, it will return the value based on the condition.

Example

Here, We have defined a function, natural_num it returned the list of natural number −

def natural_num(n):
    list1 = []
    for i in range(0,n):
                list1.append(i)
    return list1 

var1 = natural_num(9)
print(var1)

Output

Following is the output of the above code −

[0, 1, 2, 3, 4, 5, 6, 7, 8]

Using 'for' Keyword with range()

The for keyword is often used with the range() function to iterate over a sequence of numbers. The range() function generates a sequence of numbers, which the for loop can iterate over.

Example

Following is an of for keyword with range() function. Here, we have printed all even numbers below 20 −

n = 20
for i in range(0,n):
    if i%2==0:
        print(i, end=" ")

Output

Following is the output of the above code −

0 2 4 6 8 10 12 14 16 18
python_keywords.htm
Advertisements