Repetition in Python
Repetition 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)
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
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)
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)