REPETITIONS IN PYTHON
CHAPTER 7
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.
Syntax
range(start, stop, step)
start Optional. Default is 0
stop Required.
step Optional. Default is 1
Increment or Decrement operators -
In Python += is used for incrementing, and -= for decrementing. In some other languages, there is
even a special syntax ++ and -- for incrementing or decrementing by 1
a += 1
a -= 1
The ‘for loop’
A for loop is used for iterating over a sequence
With the for loop we can execute a set of statements, once for each item in a list.
Syntax
for variable in range (start,stop,step):
print(variable)
EXAMPLE
for x in range(1, 101, 1):
print(x)
Output
1
2
3
:
:
:
100
Displaying numbers horizontally -
Syntax
print(x,end=” ”)
EXAMPLE
for x in range(1, 101, 1):
print(x,end=” ”)
Output
1 2 3 ……………………… 1oo
NOTE - Do example 1 to example 7 in the notebook.
QD: Write the following programs in Python :
1. Program to finds the sum of natural numbers from 21 to 30 (both numbers
inclusive.
SOLUTION
Sum = 0
for x in range(21,31,1):
Sum = sum + x
print(“ The sum of natural numbers from 21 to 30 is :”, Sum)
2. Program to finds the sum of natural numbers m to n, where m and n are input
by the user.
SOLUTION
m= int(input(“Enter a number”))
n = int(input(“Enter second number”))
Sum = 0
for x in range(m,n+1,1):
Sum = sum + x
print(“ The sum of natural numbers from m to n is :”, Sum)
3. Program to finds the sum of all even numbers from m to n, where m and n are
input by the user.
SOLUTION
m= int(input(“Enter a number”))
n = int(input(“Enter second number”))
Sum = 0
for x in range(m,n+1,1):
if(x%2==0):
Sum = sum + x
print(“ The sum of natural numbers from”, m, “to”, n, “is :”, Sum)
4. Program to display the multiplication table of a number entered by the user,
upto 10 times
SOLUTION
m= int(input(“Enter a number for table”))
for i in range(1,11,1):
print(m, "x",i, "=", m*i)
5. Program to display the multiplication table of m, upto n times, where the
number m and n entered by the user.
SOLUTION
m= int(input(“Enter a number for table”))
n = int(input(“Enter second number to print upto…. ”))
Sum = 0
for i in range(1,n+1,1):
print(m, "x",i, "=", m*i)