Page 247 - Ai_V1.0_Class9
P. 247
Different examples of for loop are:
Commands Output
for i in [1,2,3,4]: 1
print(i) 2
3
4
for words in ["hello", "friends", "how are you?"]: hello
print(words) friends
how are you?
for alphabets in "hello!": h
print(alphabets) e
l
l
o
!
• Using the range() Function: The range( ) function is an inbuilt function that is used to generate a sequence
of values between the specified range. The syntax to use the for loop with a range () function is:
for <Var> in range(<Start>, <End>, <Step>):
Statements
Where,
✶ for, in, and range are keywords.
✶ Start, End, and Step are parameters of range() function and will always be integers.
✶ Start is a starting value of loop, End is an ending value (not inclusive) of loop, and Step is the number of steps
taken to reach the end value.
✶ If only two parameters are used then Step value becomes 1 by default.
✶ If only one parameter is used the Start becomes 0 and Step becomes 1 by default.
✶ If Start > End then Step should be a negative integer.
✶ If Start < End then Step should be a positive integer.
✶ If Start >= End and Step value is not specified, the loop will not execute as this is an invalid condition.
Different examples of for loop with the range( ) function are:
Commands Output
for count in range(1,6,1): hello
hello
print("hello")
hello
print("Program ends")
hello
hello
Program ends
Introduction to Python 245

