for loop

We can iterate the items of any sequence using the for loop.

Example: characters in a string, items in the list etc.




Syntax

for iterating_variable in any_sequence:
   #statements 



Iterating String

Example

#iterating a string using for loop

for char in "Python3":
   print(char)




Iterating List

Example

#iterating a list in python

names = ["C", "C++", "Java", "Python"]

for i in names:
   print(i)





range() function

Using the range() function, we can iterate the sequence of numbers.

range(N) will print numbers from 0 to N-1.


Example

#range() function example

for i in range(10):
 print(i)

1. We can set the starting value in range function.

Example

range(5, 10) will print the following numbers 5, 6, 7, 8, 9.

2. We can also set the different increment values.

Example

range(5, 10, 2) will print the following numbers 5, 7, 9.

range(0,7,3) will print the following numbers 0, 3, 6.


Topics You Might Like