For i in range()
Introduction:
- In Python, you can use the
range()function with aforloop to iterate over a sequence of numbers. This is a fundamental concept for looping and iteration in Python.
Syntax:
Here are some common ways to use
range()withforloops:pythonfor i in range(x): # statements(s) for i in range(x, y): # statements(s) for i in range(x, y, step): # statements(s) for i in range(start, stop, step): # statements(s)
Examples:
- for i in range(x):
- This loop iterates from
0tox-1. Python Program:
pythonfor i in range(5): print(i)Output:
0 1 2 3 4
- This loop iterates from
- for i in range(x, y):
- This loop iterates from
xtoy-1. Python Program:
pythonfor i in range(5, 10): print(i)Output:
5 6 7 8 9
- This loop iterates from
- for i in range(x, y, step):
- This loop iterates from
xtoy-1in steps ofstep. Python Program:
pythonfor i in range(5, 15, 3): print(i)Output:
5 8 11 14
- This loop iterates from
- for i in range(start, stop, step):
- This loop iterates from
starttostopin steps ofstep. Python Program:
pythonfor i in range(15, 5, -3): print(i)Output:
15 12 9 6
- This loop iterates from
Exercises:
- Print Even Numbers:
Write a program to print even numbers from 0 to 10 using
range().pythonfor i in range(0, 11, 2): print(i)
- Print Numbers in Reverse:
Write a program to print numbers from 10 to 1 using
range().pythonfor i in range(10, 0, -1): print(i)
- Print Multiples of 3:
Write a program to print multiples of 3 from 3 to 30 using
range().pythonfor i in range(3, 31, 3): print(i)
Summary:
- In this tutorial, we learned how to use the
forloop withrange()in Python. This is a basic and essential concept for looping and iteration in Python. Practice these examples to get comfortable withforloops andrange()in your Python programs!