Examples of for loop in python
Question 1. Write a program to print following pattern
*
**
***
****
Answer:
x=int( input("Enter Number"))
for i in range(1,x+1):
for j in range(1,i+1):
print("*",end="")
print("/n")
Screenshot:
x=int( input("Enter Number"))
for i in range(1,x+1):
for j in range(1,i+1):
print("*",end="")
print("/n")
Screenshot:
Question 2. Write a program to print following
####
###
##
#
Answer:
x=int(input("Enter number"))
for i in range(x-1,-1,-1):
for j in range(i-1,-1,-1):
print("#",end=" ")
print("\n")
Screenshot:
x=int(input("Enter number"))
for i in range(x-1,-1,-1):
for j in range(i-1,-1,-1):
print("#",end=" ")
print("\n")
Screenshot:
Question 3. Write a program to print pattern as
1
12
123
1234
Answer:
x=int(input("Enter number"))
for i in range(1,x+1):
for j in range(1,i+1):
print(j,end=" ")
print("/n")
Screenshot:
x=int(input("Enter number"))
for i in range(1,x+1):
for j in range(1,i+1):
print(j,end=" ")
print("/n")
Screenshot:
Question 4. Write a program to display all odd numbers from
1 to 30?
Answer:
for i in range(1,31):
if(i%2 !=0):
print(i,end=",")
Screenshot:
for i in range(1,31):
if(i%2 !=0):
print(i,end=",")
Screenshot:
Question 5. Write a program to display all even numbers from
1 to 30?
Answer:
for i in range(1,31):
if(i%2==0):
print(i,end=",")
for i in range(1,31):
if(i%2==0):
print(i,end=",")
Screenshot:
Question 6. Write a program that uses exactly four for loops
to print the sequence of letters below.
AAAAAAABBBBBBCCCCCEEEE
Answer:
for i in range(1,8):
print("A",end="")
for i in range(1,7)
print("B",end="")
for i in range(1,6)
print("C",end="")
for i in range(1,5)
print("E",end="")
Screenshot:
for i in range(1,8):
print("A",end="")
for i in range(1,7)
print("B",end="")
for i in range(1,6)
print("C",end="")
for i in range(1,5)
print("E",end="")
Screenshot:
Question 7. Write a program to display sum of all numbers
from 1 to 10?
Answer:
sum=0
for i in range(1,11):
sum=sum+i
print("Sum of 1 to 10 :",sum)
Screenshot:
sum=0
for i in range(1,11):
sum=sum+i
print("Sum of 1 to 10 :",sum)
Screenshot:
Question 8. Write a program to display Average of all
numbers from 1 to 10?
Answer:
sum=0
for i in range(1,11):
sum=sum+i
avg=sum/10
print("Average of 1 to 10 : ",avg)
Screenshot:
sum=0
for i in range(1,11):
sum=sum+i
avg=sum/10
print("Average of 1 to 10 : ",avg)
Screenshot:
Question 9. Write a program to display table of N number?
Answer:
num=int(input("Enter any number"))
for i in range(num,num*11,num):
print(i)
Screenshot:
num=int(input("Enter any number"))
for i in range(num,num*11,num):
print(i)
Screenshot:
No comments:
Post a Comment