Python – For Loops

The for loop in Python is different from other programming languages like C and Java. A for loop in Python is used to iterate over a sequence or a collection (list, tuple, dictionary, etc.).

Syntax of For Loop

for <variable> in <sequence>:
	#statements to be executed
	#multiple statements can execute

In the above for loop syntax, the variable takes the next value from sequence until the last sequence and repeats the statements.

Python For Loop with the List

For loops can use with any kind of collections in Python like list, tuple, dictionary, etc.

language=['Python','Java','C','C++','PHP']
for lang in language:
    print(lang)

#the variable lang takes the value from the List language one by one and print them until the last value.
numbers=[11,22,33,44,55,66,77]
sum=0
for n in numbers:
    sum+=n
print("Total :",sum)

#the variable n takes the value from the List numbers one by one and calculate the sum until the last value.

The range() Function

The range() function in Python generates a sequence of numbers starting from 0 to n-1. The syntax of range function in Python is range (start, stop, step).

  • start (optional) – Starting number of range(). the default value is 0 if we not provide.
  • stop (required) – Endpoint of the range() function..
  • step (optional) – Step size or increment. The default value is 1 if we not provide.

Example: Use of range() function in Python

a=range(5)      #start with 0
b=range(0,5)    #endpoint is 5
c=range(2,7)    #step size is 1
d=range(2,11,2) #step size is 2
e=range(5,0,-1) #step size is -1

print(a)
print(list(a))

print(b)
print(list(b))

print(c)
print(list(c))

print(d)
print(list(d))

print(e)
print(list(e))

list() – In Python, list() function takes sequence type as a parameter and converts it into List.

Python For Loop with the Range

We can use range() with for loop to generate a sequence of numbers.

Example: Example of range function with for loop.

#It will print 0 to 4
num=range(5)
for i in num:
    print(i)
    
#or you can write above example like this
for i in range(5):
    print(i)

#It will print 1 to 4
for i in range(1,5):
    print(i)

#It will print 2,4,6,8
for i in range(2,10,2):
    print(i)

#It will print 10 to 1
for i in range(10,0,-1):
    print(i)

100
Created on By S. Shekhar

Python - Quiz 11

1 / 4

Which of the following is not a collection in python?

2 / 4

[0, 1, 2, 3] is the output of which of the following?

3 / 4

What will be the output of the following commands?

a=range(5)

print(list(a))

4 / 4

Which of the following is true for range(1,10,2)?

Your score is

The average score is 68%

0%