for loop in python differs a bit from other programming languages. Like in C,the user has the ability to define the iterationstep as well as halting condition.
But as we see in Python, for loop statement iterates over the item of any sequences. Here sequences are list,tuple,string,set etc.
for loop is helpful in executing we can execute a set of statements, once for each item in the list,tuple,set etc.
for x in sequence:
body of for loop
Here x is the variable which takes the value of the item present in the sequences(list,tuple,set etc.)
The loop will run continously until it reaches the last item of the given sequence. Also in for loop, indentation is used to seperate the body of loop from the rest of code.
lang=["Java","Pascal","Python","Ruby"]
for x in lang:
print(x)
Output:
Java
Pascal
Python
Ruby
Example 2:Output:#program for sum of square
numbers=[5,7,9,11] sum=0 for x in numbers: square=x**2 #the operator ** is used for giving power sum=sum+square print("The sum of square of numbers:",sum)
The sum of square of numbers:276
range() is very helpful.This function is used to loop through a set of code for given number of times.
For example,range(5) will loop for 0 to 4 in the particular sequence.
Note:The given number in the range() is not taken, the range is upto preceding number.
range(stop)
range(start,stop,step_size)
start=starting point
stop=stopping point
step_size=interval between start & stop
Example:
print(range(7))
print(list(range(7)))
print(list(range(2,9))
print(list(range(2,16,2)))
Output
range(0,7)
[0,1,2,3,4,5,6]
[2,3,4,5,6,7,8]
[2,4,6,8,10,12,14]
We can also use len() function with the range() function.Let's see an example
Example:
mgenre=['Comedy','Thriller','Romance','Biography']
for x in range(len(mgenre)):
print("Movies of",mgenre[x])
Output:
Movies of Comedy
Movies of Thriller
Movies of Romance
Movies of Biography