0% found this document useful (0 votes)
4 views16 pages

Python Practice Question

The document contains a series of Python programming exercises covering various topics such as string manipulation, mathematical calculations, and data structures. Each exercise includes a brief description and corresponding code implementation. The exercises range from basic tasks like printing strings and calculating areas to more complex problems like finding perfect numbers and checking for prime numbers.

Uploaded by

rahulmmmut
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

Python Practice Question

The document contains a series of Python programming exercises covering various topics such as string manipulation, mathematical calculations, and data structures. Each exercise includes a brief description and corresponding code implementation. The exercises range from basic tasks like printing strings and calculating areas to more complex problems like finding perfect numbers and checking for prime numbers.

Uploaded by

rahulmmmut
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1. Write a Python program to print the following string in a specific format (see the output).

Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the
world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what
you are" Output :

Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a
diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are

print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \


n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \
nTwinkle, twinkle, little star, \n\tHow I wonder what you are!")

1. Write a Python program to get the Python version you are using
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)

1. Write a Python program to display the current date and time.


import datetime
now = datetime.datetime.now()
print ("Current date and time : ",now)

1. Write a Python program which accepts the radius of a circle from the user and compute
the area
import numpy as np
def areaofcircle():
radius=float(input('Enter the radius of Circle:'))
area=np.pi *radius*radius
return area

areaofcircle()

1. Write a Python program which accepts the user's first and last name and print them in
reverse order with a space between them.
def reversethestring():
first_name=input('Enter your first name')
last_name=input('Enter your last name')
return last_name[::-1],first_name[::-1]

reversethestring()

## Another way
f_name = input("Input your First Name : ")
l_name = input("Input your Last Name : ")
print ("Hello " + l_name + " " + f_name)
1. Write a Python program which accepts a sequence of comma-separated numbers from
user and generate a list with those numbers
values = input("Input some comma seprated numbers : ")
list1 = values.split(",")
print(list1)

1. Write a Python program to accept a filename from the user and print the extension of
that
file_name=input('Enter the name of file')
a=file_name.split('.')
print(a[1])

1. Write a Python program to display the first and last colors from the following list
color_list = ["yellow","Green","grey" ,"orange"]
color_list = ["yellow","Green","grey" ,"orange"]
print(color_list[0])
print(color_list[-1])

1. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn
x = int(input("Input an integer : "))
n1 = int( "%s" % x )
n2 = int( "%s%s" % (x,x) )
n3 = int( "%s%s%s" % (x,x,x) )
print (n1+n2+n3)

Input an integer : 12
122436

10.Write a program to demonstrate different number data types in Python.

a=True
b=12
c=34.56
d='Data sciience'
print('The datatype of a is ',type(a))
print('The datatype of b is ',type(b))
print('The datatype of c is ',type(c))
print('The datatype of d is ',type(d))

The datatype of a is <class 'bool'>


The datatype of b is <class 'int'>
The datatype of c is <class 'float'>
The datatype of d is <class 'str'>

1. Python Program to find sum of array


def sumofarray(b):
add=0
for i in b:
add=add+i
return add

sumofarray(np.array([1,2,3]))

12.Write a program to create, concatenate and print a string and accessing sub-string from a
given string

s1=input('Enter the first string')


s2=input('Enter the second string')
print('The first string entered is',s1)
print('The second string entered is ',s2)
print('concatenation of two entered string',s1+s2)
print('Substring of s1',s1[1:3])
print('substring of s2',s2[2:3])

Enter the first stringshubhangi


Enter the second stringsakarkar
The first string entered is shubhangi
The second string entered is sakarkar
concatenation of two entered string shubhangisakarkar
Substring of s1 hu
substring of s2 k

13.Create and explain the working of tuple.

14.Write a python program to find largest of three numbers.

num1=float(input('Enter first number'))


num2=float(input('Enter second number'))
num3=float(input('Enter third number'))

if (num1>=num2) and (num1>=num3):


print('The highest number is',num1)
elif (num2>=num1) and (num2>=num3):
print('The highest number is ',num2)
else:
print('The higest number is ',num3)

Enter first number2


Enter second number3
Enter third number5
The higest number is 5.0
15.Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [ Formula:
c = (f-32)(5/9)]

temp=float(input('Enter temprature'))
unit=input('Enter unit')

if unit=='C' or unit=='c':
newtemp=9/5*temp+32
print('Temprature in ferenhite is',newtemp)
elif unit=='F' or unit=='f':
newtemp=5/9*(temp-32)
print('Temparture is celsius is',newtemp)
else:
print('unknown unit passed')

Enter temprature38
Enter unitc
Temprature in ferenhite is 100.4

1. Write a Python program to construct the following pattern, using a nested for loop


max = 6
for i in range(0,max+1):
print("* "*i)
for i in range(max+1,0,-1):
print("* "*i)

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

17.Write a program that accepts the lengths of three sides of a triangle as inputs. The program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).

base=float(input('Enter the base of triangle:'))


height=float(input('Enter the height of triangle:'))
hypo=float(input('Enter the hypo of triangle:'))
if hypo**2==((base**2)+(height**2)):
print('Entered dimensions of right angle triangle')
else:
print('The trianle is not right angled triganle')

Enter the base of triangle:3


Enter the height of triangle:4
Enter the hypo of triangle:5
Entered dimensions of right angle triangle

1. Given a range of the first 10 numbers, Iterate from the start number to the end number,
and In each iteration print the sum of the current number and previous number
def sumofnum(num):
previousnum=0
for i in range(num):
sum=previousnum+i
print('The current number is:',i ,'Previous
numbers:',previousnum,'Sum is:',sum)
previousnum=i

sumofnum(20)

The current number is: 0 Previous numbers: 0 Sum is: 0


The current number is: 1 Previous numbers: 0 Sum is: 1
The current number is: 2 Previous numbers: 1 Sum is: 3
The current number is: 3 Previous numbers: 2 Sum is: 5
The current number is: 4 Previous numbers: 3 Sum is: 7
The current number is: 5 Previous numbers: 4 Sum is: 9
The current number is: 6 Previous numbers: 5 Sum is: 11
The current number is: 7 Previous numbers: 6 Sum is: 13
The current number is: 8 Previous numbers: 7 Sum is: 15
The current number is: 9 Previous numbers: 8 Sum is: 17
The current number is: 10 Previous numbers: 9 Sum is: 19
The current number is: 11 Previous numbers: 10 Sum is: 21
The current number is: 12 Previous numbers: 11 Sum is: 23
The current number is: 13 Previous numbers: 12 Sum is: 25
The current number is: 14 Previous numbers: 13 Sum is: 27
The current number is: 15 Previous numbers: 14 Sum is: 29
The current number is: 16 Previous numbers: 15 Sum is: 31
The current number is: 17 Previous numbers: 16 Sum is: 33
The current number is: 18 Previous numbers: 17 Sum is: 35
The current number is: 19 Previous numbers: 18 Sum is: 37

19.Given a string, display only those characters which are present at an even index number.

def printEveIndexChar(str):
for i in range(0, len(str)-1, 2):
print("index[",i,"]", str[i] )

inputStr = "shubhangi"
print("Orginal String is ", inputStr)

print("Printing only even index chars")


printEveIndexChar(inputStr)

Orginal String is shubhangi


Printing only even index chars
index[ 0 ] s
index[ 2 ] u
index[ 4 ] h
index[ 6 ] n

20.Return the count of sub-string “Shubhangi” appears in the given string

str = "Shubhangi is good developer. Shubhangi is a Data Scientist"

cnt = str.count("Shubhangi")
print(cnt)

21.Write a program (function!) that takes a list and returns a new list that contains all the
elements of the first list minus all the duplicates.

## Function to remove duplicates from given list


def listduplicate(x):
y = []
for i in x:
if i not in y:
y.append(i)
return y

listduplicate([1,1,2,3,4,4])

[1, 2, 3, 4]
#this one uses sets
def v2(x):
return list(set(x))

v2([1,1,2])

[1, 2]

22.Print multiplication table of 12 using recursion

def table(n,i):
print(n*i)
i=i+1
if i<=10:
table(n,i)

table(20,1)

20
40
60
80
100
120
140
160
180
200

1. Write a function to calculate area and perimeter of a rectangle.


def rectangle(a,b):
print('The area of given rectangle is:' ,a*b)
print('The perimeter of given rectangle is:',2*(a+b))

rectangle(12,2)

The area of given rectangle is: 24


The perimeter of given rectangle is: 28

24.Write a function to calculate area and circumference of a circle

def circle():
import numpy as np
radius=float(input('Enter the radius of circle'))
area=np.pi*radius*radius
return area

circle()
Enter the radius of circle4

50.26548245743669

25.Write a function to calculate power of a number raised to other

def powerof(n,p):
power=n**p
return power

powerof(2,3)

26.Write a function to tell user if he/she is able to vote or not.

age=float(input('Enter your age'))


if age >=18:
print('You are eligible to vote')
else:
print('Not eligible to vote')

Enter your age21


You are eligible to vote

27.Write a function “perfect()” that determines if parameter number is a perfect number. Use
this function in a program that determines and prints all the perfect numbers between 1 and
1000. [An integer number is said to be “perfect number” if its factors, including 1(but not the
number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].

4 //2

def find_factors(num):
if num//2 > 2:
added = False
for i in range(2,num//2,1):
if num % i != 0:
continue
factors.append(i)
added = True
break
if(added):
find_factors(int(num//i))
else:
factors.append(num)
else:
factors.append(num)

def find_perfect(num):
factorials = []
for i in range(1,num//2+1):
if num%i == 0:
factorials.append(i)
if sum(factorials) == num:
return(True)
else:
return(False)

for i in range(1,10000):
if find_perfect(i):
print(i)

6
28
496
8128

for i in range(1000):
factors = [1]
find_factors(i)
if sum(factors) == i:
print(i)

fi(28)

[1, 2, 4, 7, 14]

num = mainNum
factors = []

def perfect(n):
sum=0
for i in range(n,1):
if n%i == 0:
sum=sum+i
if sum==n:
return True
else:
return False
for i in range(1,1001):
if perfect(i):
print(i)

28.Write a function to check if a number is even or not.

def even():
n=int(input('Enter the number'))
if n%2 == 0:
print('The given number is even')
else:
print('Odd number')

even()

Enter the number3


Odd number

29.Write a function to check if a number is prime or not

def odd():
n=int(input('Enter the number'))
if n%2 != 0:
print('The given number is odd')
else:
print('Even number')

odd()

Enter the number3


The given number is odd

30.Given a list of numbers, return True if first and last number of a list is same

def isFirst_And_Last_Same(numberList):
print("Given list is ", numberList)
firstElement = numberList[0]
lastElement = numberList[-1]
if (firstElement == lastElement):
return True
else:
return False

numList = [10, 20, 30, 40, 10]


print("result is", isFirst_And_Last_Same(numList))

Given list is [10, 20, 30, 40, 10]


result is True

1. Write a program to check if each word in a string begins with a capital letter?
print( 'The Hilton'.istitle() )
print( 'The dog'.istitle() )
print( 'sticky rice'.istitle() )

True
False
False

1. Write a program to Check if a string contains a specific substring


print( 'plane' in 'The worlds fastest plane' ) #=> True
print( 'car' in 'The worlds fastest plane' ) #=> False

True
False

1. Capitalize the first character of a string


'florida dolphins'.capitalize()

'Florida dolphins'

1. Reverse the string “hello world”


''.join(reversed("hello world"))

'dlrow olleh'

1. Remove vowels from a string


string = 'Hello 1 World 2'
vowels = ('a','e','i','o','u')
''.join([c for c in string if c not in vowels])

'Hll 1 Wrld 2'

1. Iterate through a string Using for Loop.


h_letters = []

for letter in 'shubhangi':


h_letters.append(letter)

print(h_letters)

['s', 'h', 'u', 'b', 'h', 'a', 'n', 'g', 'i']

1. Iterate through a string Using List Comprehension


h_letters = [ letter for letter in 'shubhangi' ]
print( h_letters)
['s', 'h', 'u', 'b', 'h', 'a', 'n', 'g', 'i']

1. Transpose of Matrix using Nested Loops


transposed = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]

for i in range(len(matrix[0])):
transposed_row = []

for row in matrix:


transposed_row.append(row[i])
transposed.append(transposed_row)

print(transposed)

[[1, 4], [2, 5], [3, 6], [4, 8]]

1. Write a program to check whether a number is divisible by 7 or not.


num=int(input("Enter your age"))
if num%7==0:
print("Number is divisible")
else:
print("Number is not divisible")

Enter your age33


Number is not divisible

1. Write a program to calculate the electricity bill (accept number of unit from user)
according to the following criteria : Unit Price
First 100 units no charge Next 100 units Rs 5 per unit After 200 units Rs 10 per unit (For
example if input unit is 350 than total bill amount is Rs2000)
amt=0
nu=int(input("Enter number of electric unit"))
if nu<=100:
amt=0
if nu>100 and nu<=200:
amt=(nu-100)*5
if nu>200:
amt=500+(nu-200)*10
print("Amount to pay :",amt)

Enter number of electric unit344


Amount to pay : 1940

1. Write a program to display the last digit of a number. (hint : any number % 10 will return
the last digit)
num=int(input("Enter any number"))
print("Last digit of number is ",num%10)

Enter any number234


Last digit of number is 4

1. Write a program to check whether an years is leap year or not.


yr=int(input("Enter the year"))
if yr%100==0:
if yr%400==0:
print("Entered year is leap year")
else:
print("Entered year is not a leap year")
else:
if yr%4==0:
print("Entered year is leap year")
else:
print("Entered year is not a leap year")

Enter the year2008


Entered year is leap year

1. Write a program to accept a number from 1 to 7 and display the name of the day like 1 for
Sunday , 2 for Monday and so on.
num=int(input("Enter any number between 1 to 7 : "))
if num==1:
print("Sunday")
elif num==2:
print("Monday")
elif num==3:
print("Tuesday")
elif num==4:
print("Wednesday")
elif num==5:
print("Thursday")
elif num==6:
print("Friday")
elif num==2:
print("Saturday")
else:
print("Please enter number between 1 to 7")

Enter any number between 1 to 7 : 3


Tuesday

1. Write a program to check whether a number entered is three digit number or not.
num1 = (input("Enter any number"))
l=len(num1)
if l != 3:
print("Entered number is not 3 digit")
else:
print("Entered number is 3 digiy and Middle digit is ",
(int(num1)%100//10))

Enter any number3


Entered number is not 3 digit

1. Write a program to check whether a number (accepted from user) is positive or negative..
num1 = int(input("Enter first number"))
if num1 > 0 :
print("Number is positive")
else:
print("Number is negative")

Enter first number345


Number is positive

1. Write a program to whether a number (accepted from user) is divisible by 2 and 3 both.
num1 = int(input("Enter first number"))
if num1%2==0 and num1%3==0:
print("Number is divisible by 2 and 3 both")
else:
print("Number is not divisible by both 2 and 3")

Enter first number45


Number is not divisible by both 2 and 3

1. Write a Python program to check the validity of a password (input from users).

Validation :

At least 1 letter between [a-z] and 1 letter between [A-Z]. At least 1 number between [0-9]. At
least 1 character from [$#@]. Minimum length 6 characters. Maximum length 16 characters.

import re
p= input("Input your password")
x = True
while x:
if (len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",p):
break
elif not re.search("[0-9]",p):
break
elif not re.search("[A-Z]",p):
break
elif not re.search("[$#@]",p):
break
elif re.search("\s",p):
break
else:
print("Valid Password")
x=False
break

if x:
print("Not a Valid Password")

1. Write a Python program to print alphabet pattern 'A'.





result_str="";
for row in range(0,7):
for column in range(0,7):
if (((column == 1 or column == 5) and row != 0) or ((row == 0
or row == 3) and (column > 1 and column < 5))):
result_str=result_str+"*"
else:
result_str=result_str+" "
result_str=result_str+"\n"
print(result_str)

***
* *
* *
*****
* *
* *
* *

1. Write a Python program to print alphabet pattern 'G'.


result_str="";
for row in range(0,7):
for column in range(0,7):
if ((column == 1 and row != 0 and row != 6) or ((row == 0 or
row == 6) and column > 1 and column < 5) or (row == 3 and column > 2
and column < 6) or (column == 5 and row != 0 and row != 2 and row !=
6)):
result_str=result_str+"*"
else:
result_str=result_str+" "
result_str=result_str+"\n"
print(result_str);

***
* *
*
* ***
* *
* *
***

1. Write a Python program to calculate a dog's age in dog's years. Go to the editor Note:
For the first two years, a dog year is equal to 10.5 human years. After that, each dog year
equals 4 human years. Expected Output:

Input a dog's age in human years: 15


The dog's age in dog's years is 73

h_age = int(input("Input a dog's age in human years: "))

if h_age < 0:
print("Age must be positive number.")
exit()
elif h_age <= 2:
d_age = h_age * 10.5
else:
d_age = 21 + (h_age - 2)*4

print("The dog's age in dog's years is", d_age)

Input a dog's age in human years: 34


The dog's age in dog's years is 149

You might also like