Python Lab Manual Answers (22616) Practical 5

 Python Lab Manual (22616)

Practical 5 : Write Python Program to demonstrate  use of looping statements : 'While ' Loop ,'for' Loop, and Nested loop.


*Practical Related Questions.

1) 1. What would be the output from the following Python code segment?
x=10
while x>5:
 print x,
 x-=1
Ans=>  SyntaxError: Missing parentheses in call to 'print'. Did you mean print(x, end=" ")?



2. Change the following Python code from using a while loop to for loop:
x=1
while x<10:
 print x
 x+=1
Ans=> for x in range(1,10)
                print(x)





*Exercise 

1) Print the following patterns using loop:
a. *
    **
    ***
    ****
Ans =>

for i in range(0,5):
    for j in range(0,i+1):
        print("*",end="")
    print("")

 
b.
     *
   ***
 *****
   ***
     *
Ans =>

for i in range(3):
    print(' '*(3-i-1)+'*'*(2*i+1))

for j in reversed(range(2)):
    print(' '*(2-j)+'*'*(2*j+1))

101010110101011010101
c.
1010101
 10101
   101
     1 
Ans =>

i=3
k=0
while(i>=0):
    a=" "*k+"10"*i+"1"
    print(a)
    i=i-1
    k=k+1

2. Write a Python program to print all even numbers between 1 to 100 using while 
loop.
Ans =>

i = 2
while i <= 100:
  if i%2==0:
   print(i)
  i += 1


3. Write a Python program to find the sum of first 10 natural numbers using for loop.
Ans =>

sum = 0
n = 10

while(n >= 0):
    sum=sum+n
    n=n-1

print("Sum of first 10 natural number : ",sum)
4. Write a Python program to print Fibonacci series.
Ans =>

num=int(input("Enter terms : "))
x=0
y=1
c=2

print("Fibonacci sequence is : ")
print(x)
print(y)
while(c<num):
    z=x+y
    print(z)
    x=y=z
    c+=1
5. Write a Python program to calculate factorial of a number
Ans =>


n = int(input("Enter a number : "))
factorial = 1
if n >= 1 :
    for i in range(1,n+1):
        factorial = factorial * i
print("Factorial : ",factorial)

6. Write a Python Program to Reverse a Given Number
Ans =>

n = int(input("Enter a number : "))
rev = 0
while(n>0):
    dig=n%10
    rev=rev*10+dig
    n=n//10
print("Reverse of the number : ",rev)

7. Write a Python program takes in a number and finds the sum of digits in a 
number.
Ans =>

n = int(input("Enter a number : "))
sum = 0
for digit in str(n):
    sum=sum+int(digit)
print("Sum of the number : ",sum)

8. Write a Python program that takes a number and checks whether it is a palindrome 
or not
Ans =>

n = int(input("Enter number:"))
temp=n
rev=0
while(n>0):
    dig=n%10
    rev=rev*10+dig
    n=n//10
if(temp==rev):
    print("Palindrome Number!")
else:
    print("Not Palindrome Number!")
               

Post a Comment

0 Comments