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].
SyntaxFollowing is the syntax of Python for keyword −
forExample
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 tUsing 'for' keyword in List
The for keyword can also be used in list to iterate it.
ExampleFollowing 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 HTMLUsing 'for' Keyword in Functions
We can use for keyword inside the function, it will return the value based on the condition.
ExampleHere, 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.
ExampleFollowing 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4