Friday, 6 September 2019

Examples of for loop in python | For loop Examples with Answers


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:

Display pattern using for loop in python


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:

For loop reverse pattern


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:
Display for loop pattern in python 3


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:

odd number using for loop


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=",")


Screenshot:

Example of even number using for loop in python



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:

Example of nested for loop in python


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:

Example of sum of numbers


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:

example of python


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:

Example of python program




No comments:

Post a Comment

Recent Post

Python Project | Banking System | Project on Banking System using python

  PYTHON PROJECT Banking System import csv import pandas as pd import matplotlib.pyplot as plt import sys import datetime found=False def ne...