Python Interview Programs

Disclaimer – There are always multiple approaches to solve a problem. We have used only one out of those. You can try other logic based on your understanding. Please comment your concern to us, we may help you in your understanding on Python Programming.
Allthe programs below are center indented. Please type it while implementing in py.

1.       Write a program to print a string in Python ?
Ans –  Strings can be printed using double quotes or single quote. Please refer the below example for trying dfferent variables.
a = "Hello World"
print a
Output : python main.py
Hello World

The choice between single and double quotes often comes down to convenience, especially when your string contains quotes. For example:

  • If your string contains a single quote, you might use double quotes to avoid escaping:
    print("It's a beautiful day!")
    
  • Conversely, if your string contains double quotes, you might use single quotes:
    print('He said, "Hello!"')
2.      Write a program to accept two numbers from user and print their sum?
Ans –
a=int(input("Enter a number\n"))
print(a)
b=int(input("Enter a number\n"))
print(b)
sum=a+b
print("Sum of both the numbers is ",+sum)
Output : python main.py
Enter a number
345
Enter another number
100
Sum of both the numbers is 445
3.       Write a program to accept two strings from user and print their difference?
Ans -
a= int(input('Enter a number\n'))
print(a)
b= int(input("Enter another number\n"))
print(b)
diff=a-b
print("Difference between above numbers is : ",diff)
Output : python main.py
Enter a number
89
Enter another number
90
Difference between both the numbers is -1
4.      Write a program to accept two strings from user and print their product(multiply) and quotient(divide)?
Ans –
a= int(input('Enter a number\n'))
print(a)
b= int(input("Enter another number\n"))
print(b)
product=a*b
quotient=a/b
print("Product of both the numbers is ")
print(product)
print("Quotient of both the numbers is ")
print(quotient)
Output : python main.py
Enter a number
10
Enter another number
10
Product of both the numbers is
100
Quotient of both the numbers is
1
5.     Write a program to print(area of a circle. A(circle)= 3.14 * R * R ?
          Ans –
radius= int(input('Enter radius\n'))
area=3.14*radius*radius
print("Area of the given circle is ")
print(area)
Output : python main.py
Enter radius
2
Area of the given circle is
12.56
6.      Write a program to print(area of a triangle A(Triangle)= 0.5 * B * H
Ans -
B= int(input('Enter Base\n'))
H=int(input("Enter Height\n"))
area=0.5*B*H
print("Area of the given traingle is ")
print(area)
Output : python main.py
Enter Base
2
Enter Height
2
Area of the given triangle is
2.0
7.      Write a program to print(simple interest SI = (PNR)/100
       Ans –
P= int(input('Enter Principal\n'))
R=int(input("Enter Rate\n"))
N=int(input("Enter Time in Months\n"))
SI=(P*N*R)/100
print("Simple Interest is ")
print(SI)
Output : python main.py
Enter Principal
100
Enter Rate
100
Enter Time in months
3
Simple Interest is
300
8.      Write a program to accept two values AND swap them using 3rd variable
     Ans –
a=int(input ("Enter 1st number\n"))
b=int(input("Enter 2nd number\n"))
print("Before swapping value of a and b are", a,"and",b, "respectively")
temp =a
a=b
b=temp
print("After swapping value of a and b are", a,"and",b, "respectively")
Output : python main.py
Enter 1st number
1290
Enter 2nd number
9090
Before swapping value of a and b are 1290 and 9090 respectively
After swapping value of a and b are 9090 and 1290 respectively

Note: Same program using function :

def swap(a,b) :
    var=a
    a=b
    b=var
    print(a,b)

swap(1000,19999)
Output : 19999,1000
9.      Write a program to accept roll and marks of 3 subjects of a student. Calculate total of 3 subjects and average.
Ans –
#Calculate marks of a student
roll=int(input("Enter roll\n"))
mark1=int(input("Enter mark1\n"))
mark2=int(input("Enter mark2\n"))
mark3=int(input("Enter mark3\n"))
total=mark1+mark2+mark3
average=total/3
print("Student Roll Number :",roll)
print("Phy marks = ",mark1,"Math Marks = ",mark2,"Chem Marks = ",mark3)
print("Total Marks In All Subjects = ",total)
print("Average Marks =",average)
Output: python main.py
Enter roll number
122
Enter marks 1
90
Enter marks 2
90
Enter marks 3
90
Student Roll Number : 122
Phy Marks = 90, Math Marks = 90, Chem Marks = 90
Total Marks in all Subjects = 270
Average Marks = 90 
10.  print(following outputs : http://www.google.com using Python)
Ans –
print(“http://www.google.com”)
#Still puzzled ? Please try this again to find the difference

11.  print(largest of 2 numbers)
Ans –
print("largest of two numbers")
a=int(input("Enter 1st number\n"))
b=int(input("Enter 2nd number\n"))
print("Numbers Entered are ",a,b)
if a>b :
    print("Largest number is ",a)
else :
    print("Largest number is ",b)
Output: python main.py
Enter 1st number
8989
Enter 2nd number
9
Numbers Entered are 8989 and 9
Largest number is 8989 
12.  Write a program to find if positive or negative.
Ans –
#Entered positive or negative number?
a=int(input("Enter a number\n"))
print("Numbers Entered is ",a)
if a>0 :
print(a,"is positive")
else :
 print(a,"is negative")
Output: python main.py
Enter a number
90
Number Entered is 90
90 is positive

or

try:
    def pn():
        i=0
        N=int(input("Enter how many numbers you want to check"))
        while i<N-1:
            n=int(input("Enter a number to chk: "))
            if n>0:
                print(n," is a positive number")
            elif n<0:
                print(n," is a negative number")
            else:
                print(n," is a whole number")
    pn()
except Exception as error:
        print("Please enter a valid number ",error)

13.  Write a program to check if it is >10, <10 or equals 10.
Ans –
#Entered number is greater than 10?
a=int(input("Enter a number\n"))
print("Numbers Entered is ",a
if a>10 :
    print(a,"is greater than 10")
elif a<10 :
    print(a,"is less than 10")
else :
    print(a,"is equal to 10")
Output: python main.py
Enter a number
90
Number Entered is 90
90 is greater than 10

14.  Write a program to find if a number is even or odd.
Ans –
#Entered number is even or odd?
a=int(input("Enter a number\n"))
print("Numbers Entered is ",a)
if a%2==0 :
    print(a,"is even")
else :
    print(a,"is Odd")
Output : Enter a number
9
Number Entered is 9
Number is Odd

15.  Write a program to find numbers divisible by 5
Ans –
#Divisible by 5?
a=int(input("Enter a number\n"))
print("Numbers Entered is ",a)
if a%5==0 :
    print(a,"is divisible by 5")
else :
    print(a,"is not divisible by 5")
Output :
Enter a number
90
Number Entered is 90
Number is divisible by 5

within a range of 100 if you are trying to print which ones are divisible by 5 then use the following program.
i=1
while i<=100:
    if i%5==0:
        print(f"{i} is divisible by 5")
    i=i+1
16.  Write a program to accept 2 numbers from user and compare them.
Ans –
#Compare two numbers ?
a=int(input("Enter a number\n"))
b=int(input("Enter another number\n"))
print("Numbers Entered are ",a,b)
if a>b :
    print(a,"is greater than",b)
elif b>a :
    print(b,"is greater than ",a)
else :
    print(a,"and ",b,"are equal")
Output : python main.py
Enter a number
89
Enter another number 9
Numbers Entered are 89 and 9
a is greater than b 

17.  Write a program to accept 3 numbers and print(in ascending Order).
Ans –
#Sort in ascending Order
try:
    a=int(input("Enter a number: "))
    b=int(input("Enter another number: "))
    c=int(input("Enter third number: "))
    listme=[]
    listme.append(a)
    listme.append(b)
    listme.append(c)
    listme.sort()
    print(listme)
except Exception as error: 
    print(error)
Output : python main.py
Enter a number
5
Enter another number
4
Enter third number
3
Ascending Order is:  3 4 5

Accept 100 numbers and print in asc order.

# Initialize an empty list to store the numbers numbers = [] # Loop to accept 100 numbers from the user for _ in range(100): num = int(input("Enter a number: ")) numbers.append(num) # Sort the list in ascending order numbers.sort() # Print the sorted list print("Numbers in ascending order:") for num in numbers: print(num)

18.  Write a Program to accept a number and print(its reverse using while loop)
Ans –
try:
    n=int(input("Enter a number"))
    while n>0:
        rem=int(n%10)
        print(int(rem),end='')
        n=int(n/10)
except Exception as error:
   print(error)

Output: python main.py
Enter a number890
098

Note: Above program using function:
def reverse(num) :
    while num>0 :
        rem=num%10
        print(rem)
        num=num/10

num=int(input("enter a number"))
reverse(num)


19.  Write a Program to accept a number and print(sum of its digits)
Ans –
try:
    n=int(input("Enter a number "))
    sum=0
    while n>0:
        rem=int(n%10)
        sum=int(sum+rem)
        n=int(n/10)
    print("sum of the numbers is: ",sum)
except Exception as error:
    print(error)

Output : python main.py
Enter a number 921224
sum of the numbers is:  20
   
20.  Write a program to check if it is Armstrong number – 153=1^3 + 5^3 + 3^3
Ans -
n=int(input("Enter a number\n"))
sum=0
i=2
temp=n
while n>0 :
    rem=n%10
    sum=sum+(rem*rem*rem)
    n=n/10
if temp==sum :
    print("It is an Armstrong Number")
else :
    print("It is not an Armstrong Number")


Output : python main.py

Enter a number
153
It is an Armstrong Number

21.   Write a program to check if its vowel.
Ans –
a = input("Enter any alphabet\n")
alphabet=['a','e','i','o','u',"A","E","I","O","U"]
if a in alphabet :
    print(a,": is vowel")
else :
    print(a,": is Consonant, not vowel")

Output :
Enter any alphabet
“a”
a: is vowel
#or use below func
import re 
def is_vowel(char): 
    if re.match(r'[aeiouAEIOU]', char): 
        return True
    return False
  
print(is_vowel('a'))  # Output: True  
print(is_vowel('b'))  # Output: False 


22.  Check if a year is leap year or not
Ans –
#Leap Year
year=int(input("Enter a year\n"))
excep=[1800,1900,2100,2200,2300]
if year%4==0 and year not in excep :
    print(year," is leap year")
else :
    print(year," is not leap year")

Output :
Enter a year
1800
1800 is not a leap year

23.  Find out the factorial of a number.
Ans –
#Factorial
num=int(input("Enter a number\n"))
fact=1
for i in range (1,num+1) :
    fact=fact*i
print(fact)

Output :
Enter a number
5
120


24.  Find HCF of a number
Highest number divisible by both the given numbers if HCF or Highest Common Factor or GCD or Greatest Common Divisor
Ans –
#HCF
num1=int(input("Enter a number\n"))
num2=int(input("Enter another number\n"))
for i in range (1,num1+1) :
    for i in range (1,num2+1) :
        if num1%i==0 and num2%i==0 :
            hcf=i
print(hcf)

Output :
Enter a number
100
Enter another number
500
100

Note : Another approach of same program using built-in function
#HCF
from itertools import chain ; #built-in
num1=int(input("Enter a number\n"))
num2=int(input("Enter another number\n"))
for i in chain (range(1,num1+1),range(1,num2+1)) :
    if num1%i==0 and num2%i==0 :
        hcf=i
print(hcf)

Output :
Same as above

25.   Find out the LCM of a number.
Ans –
#Multiple of both given numbers by HCF gives us LCM of the number.
from itertools import chain ; #built-in
num1=int(input("Enter a number\n"))
num2=int(input("Enter another number\n"))
for i in chain (range(1,num1+1),range(1,num2+1)) :
    if num1%i==0 and num2%i==0 :
        hcf=i
lcm=(num1*num2)/hcf
print(“LCM is ”,lcm)

Output :
Enter a number
100
Enter another number
500
LCM is 500

26.  Decimal to Binary, Octal, Hexadecimal, Decimal conversions
Ans –

a=int(input("Enter a number\n"))
print("Binary form of above number is ",bin(a))
print("Hexa-Decimal form of above number is ",hex(a))
print("Octal form of above number is ",oct(a))
print("Decimal form of above number is ",int(bin(a),2))

Output :
Enter a number                                                                                                                                                                  
25                                                                                                                                                                             
Binary form of above number is  0b11001                                                                                                                                         
Hexa-Decimal form of above number is  0x19                                                                                                                                      
Octal form of above number is  031                                                                                                                                             
Decimal form of above number is  25

27.  Check if a number is Palindrome
Ans –
#Palindrome
def Palindrome_Number():
    n = int(input('Enter Number to check for palindrome'))
    m=n
    a = 0
    while(m!=0):
        a = m % 10 + a * 10
        m = m / 10

    if( n == a):
        print('%d is a palindrome number' %n)
    else:
        print('%d is not a palindrome number' %n)
Palindrome_Number()

Output :
Enter Number to check for palindrome213                                                                                                                                        
213 is not a palindrome number

28. Convert a word to UpperCase if it is in LowerCase and ViceVersa.
print('Case changer(Capital to small and vice versa)')
line1 = input('Enter here: ')
g = ""
for ch in line1 :
    if ord(ch) >=ord('A') and ord(ch) <=ord('Z') :
        low=ord(ch)+32
        print(chr(low),end=""),
    else:
        print(ch,end="")

print("\n")
line2=input("Enter another word : ")
for ch in line2 :
    if ord(ch) >=ord('a') and ord(ch) <=ord('z') :
        high=ord(ch)-32
        print(chr(high),end=""),
    else:
        print(ch,end="")

Output :

Case changer(Capital to small and vice versa)
Enter here: SuCHi
suchi

Enter another word : KauR
KAUR
Process finished with exit code 0

29. Write a program to accept two values AND swap them without using 3rd variable

try:
    a=int(input("Enter a number"))
    b=int(input("Enter another number"))
    print("Value of a and b is",a,b)
    b=a+b
    a=b-a
    b=b-a
    print("Swapped Value of a and b is",a,b)
except Exception as error:
    print("Enter a valid number",error)

Same program using function :
try:
    a=int(input("Enter a no."))
    b=int(input("Enter another number"))
    print("Value of a and b is ",a,b)
    def swap(a,b):
            a=a+b
            b=a-b
            a=a-b
            print("Swapped Value of a and b is",a,b)
    swap(a,b)
except Exception as error:
    print("Please enter a valid number : ",error)

30. Write a program to accept n values AND find largest
largest of n numbers
n_max=""
def largenum(n_max):
    i=0
    N=int(input("Enter how many numbers you want to check?"))
    n_max=int(input("Enter first number :"))
    while i<N-1:
        n=int(input("Enter another number: "))
        if n>n_max:
            n_max=n
        i+=1
    print("max value is",n_max)
    return n_max
largenum(n_max)

31. Smallest of n numbers
n_min=""
def smallest(n_min):
    i=0
    N=int(input("Enter how many numbers you want?"))
    n_min=int(input("Enter first number: "))
    while i<N-1:
        n=int(input("Enter another number: "))
        if n<n_min:
            n_min=n
        i+=1
    print("The smallest number is ",n_min)
    return n_min
smallest(n_min)
#or use this function in case of list
num=[1,2,90,80,800]
print(max(num))
print(min(num))

32. Write a program to print fibonacci series upto n terms in python
num = 10
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
    n3 = n1 + n2
    n1 = n2
    n2 = n3
    print(n3, end=" ")

print()

Output :
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 


33. print 12345 in pattern
n=5 #no. of rows
for i in range(0,n+1):
    for j in range(i):
        print(i,end="")
    print()
""" Output is
1
22
333
4444
55555
"""

34. Palindrome
num=int(input("Enter a number to check palindrome: "))
temp=num
rem=0
while num>0:
    n=int(num%10)
    #print(n)
    rem=int(n+(rem*10))
    print(rem)
    num=int(num/10)
    #print(num)
if temp==rem:
    print("palindrome")

Enter a number to check palindrome: 123

3

32

321 

35. IPaddress

import ipaddress

def validate(ip_string):

    ip_object=ipaddress.ip_address(ip_string)

    print("IP Address",ip_string," is valid")

    

validate("2001:db8:3333:4444:5555:6666:7777:8888")

validate("192.168.10.1")


Output - 

IP Address 2001:db8:3333:4444:5555:6666:7777:8888  is valid

IP Address 192.168.10.1  is valid

36. List slicing
a=[1,2,3,4]
print(a[-1])

Output :
4

37. create,read,write,append file

#create new file if doesnt exist
#f = open("myfile.txt", "x")
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

import os
os.remove("demofile2.txt")

Output:
Now the file has more content!

Comments

  1. Will be timely updating this with even more programs ....

    ReplyDelete

Post a Comment

Popular posts from this blog

TCL Interview Programs

-: Networking interview questions :-