Python Practice Examples (Part 1)

I always did something I was a little not ready to do. I think that's how you grow

Contributed By: Alia Kashifi

Q1: Write a Python program to find the reverse of a number (without using built-in function).

E.g. 123 to 321.

Solution:

print ” Reverse of a number ”

num = int(raw_input(“Enter a number: “))

reverse = 0

while num:

rem = num%10

reverse = reverse*10+rem

num = num//10;

print “reverse= “,reverse

 

Q2:  Write a Python program to find if  a number is Palindrome number.

Tips: A palindromic number is a number that remains the same when its digits are reversed. Like 16461, 121 etc.

Solution:

num = int(raw_input(“Enter a number: “))

n = num

reverse = 0

while n>0:

rem = n%10

reverse = reverse*10+rem

n = n/10

if num == reverse:

print num, ” is Palindrome”

else:

print num, ” is not Palindrome”

 

Q3: Write a Python program to find Prime number in range 0 to an upper limit.

Tips: A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.

 

Solution:

upper = int(raw_input(“Enter a number: “))  #Takes the upper limit from user

for i in range (2,upper):

for j in range (2,i):

if i%j==0:

break

else:

print i,

 

Q4: Write a python program to check if a number is Perfect Number.

Tips:  a perfect number is a positive integer that is equal to the sum of its proper positive divisors. E.g. 6, 28, 496…

 Solution:

num = int(raw_input(“Enter a number: “))

sum = 0

for i in range(1,num):

if num%i == 0:

sum = sum+i

if sum==num:

print sum, ” = “, num

print num, “is a perfect number”

else:

print num, ” is not a perfect number”

 

Q5: Write a Python program that finds Fibonacci number from 0 to 50.

Tips: a series of numbers in which each number  ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.

 Solution:

num1= 1

num2= 1

fibo= 0

print num1

print num2

for i in range (1,50):

fibo = num1+num2

print fibo

num1=num2

num2=fibo

 

Q6:  Write a Python program to find factorial of a number.

Solution:

num = int(raw_input(“Enter a number to find it’s factorial: “))

counter = 1

factorial = 1

for i in range(counter,num+1):

factorial = factorial*counter

counter= counter+1

print ” The factorial of ” + str(num) + “is: ” +str(factorial)

Leave a Reply

Your email address will not be published.