Python For Loop With Example Part-1 of 3
[vc_row][vc_column][vc_custom_heading source=”post_title” font_container=”tag:h1|text_align:center” use_theme_fonts=”yes”][vc_column_text]Python for loop is one the basic concept or building block of Python. Learning any language is not a challenge when you have enough details with an example to understand the concept. Python is no different. In fact, Python is one of the easiest languages with the efficiency of powerful language. In this tutorial, I will try to explain the concept of Python for loop. This will not only help your language but also save you time when you have to do the repetitive task in the program.
Loops in any traditional programming language (Python, in our case) is used when you need a specific set of code lines to be executed for a specific number of times.
There are two kinds of loops in Python
- For Loop – When the number of iterations is known
- While loop – When the iteration is decided at condition base.
What is a Python for Loop?
A for loop is used to repeat a piece of code n number of times. The for loop is usually used with a list of things. The basic syntax for the for loop looks like this:for item in list: things to doTranslated into common English, this would be: “For each item that is present in the list, do the thing”. There are a few things to note here:
- Every for loop must reference a list or a range.
- Every for loop must close with a colon.
Python for Loop Example – 01
Print each fruit in a fruit list:fruits = ["apple", "banana", "litchi"] for x in fruits: print(x)
Looping Through a String
String is the most common data type used but one of the most complex data types in any programming language. But, Thanks to Python which made this complex object also very simple. You can consider string as group (array) of characters and they contain a sequence of characters:Python for Loop Example – 02
Loop through the letters in the word “banana”:for x in "litchi": print(x)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:Python for Loop Example – 03
Print all numbers from 0 to 16, and print a message when the loop has ended:for x in range(17): print(x) else: print("it’s over")[/vc_column_text][/vc_column][/vc_row][vc_row][vc_column][vc_column_text]You can test your knowledge with our handcrafted Python Interview Questions[/vc_column_text][/vc_column][/vc_row]