Python Practical QB - Full Finall
Python Practical QB - Full Finall
Python Practical QB - Full Finall
Code:
if not name:
print("Enter Name first")
else:
print("Hello",name)
Code:
Code:
Code:
Code:
import math
no=int(input("Enter number for getting square root:"))
print("Square root of",no,"=",math.sqrt(no))
Code:
a=int(input("Enter Number 1:"))
b=int(input("Enter Number 2:"))
c=int(input("Enter Number 3:"))
Code:
year=int(input("Enter Year:"))
Code:
n=int(input("Enter Number:"))
if(n%2==0):
print("Number is even")
else:
print("Number is odd")
Code:
age = int(input("Enter your age: "))
eligible = "Yes" if age >= 18 else "No"
print("Are you eligible to vote? " + eligible)
Code:
no=int(input("Enter Number:"))
print("Square=",no*no)
print("Cube=",no*no*no)
12. Ask the user to enter a number and display if the number is positive,
negative or zero.
Code:
n=int(input("Enter Number:"))
if(n>0):
print("Number is positive")
elif(n<0):
print("Number is negative")
else:
print("Number is zero")
13. Ask the user to enter a number and display if it is a prime number or
not.
Code:
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if num % i == 0:
print("Not a prime")
break
else:
print("Prime Number")
else:
print("Not a prime number")
14. Ask user to enter their marks of 5 subjects, display average score &
percentage with their grade. Maximum marks per subject are 70.
Code:
marks = []
marks.append(int(input("Enter marks for subject 1: ")))
marks.append(int(input("Enter marks for subject 2: ")))
marks.append(int(input("Enter marks for subject 3: ")))
marks.append(int(input("Enter marks for subject 4: ")))
marks.append(int(input("Enter marks for subject 5: ")))
average_score = sum(marks) / 5
percentage = (sum(marks) / 350) * 100
Code:
list1 = [10, 20, 30, 40, 50]
print("Original List: ")
print(list1)
Code:
def is_prime(number):
if number > 1:
for i in range(2,number):
if number % i == 0:
return False
return True
else:
return False
numbers = [1,2,3,4,5,6,7,8,9,10]
prime_found = False
for num in numbers:
if is_prime(num):
print(num, " is a prime number")
prime_found = True
if not prime_found:
print("No prime number")
17. Write a program to ask user for a number (n) and then create a list of
random integers with n elements. Hint: use random module.
Code:
import random
n=int(input("Enter number:"))
random_list=[]
for i in range(n):
random_list.append(random.randint(1,100))
print("Random integers list:",random_list)
18. Write a program to print the table (upto 20) of any number that user
enters.
Code:
n=int(input("Enter Number u want to print table:"))
for i in range(1,21):
print(n, "x", i, "=", n*i)
size = 3
print_pattern(size)
OR
rows=int(input("Enter Rows: "))
half=rows//2
n1=1
for i in range(1,rows+1):
for j in range(half):
print("",end=" ")
for k in range(n1):
print("*",end="")
print()
if(i<=rows//2):
n1+=2
half-=1
else:
n1-=2
half+=1
Code:
k=1
for i in range(1, 4):
for j in range(1,k+1):
print("*",end='')
k+=2
print()
OR
for i in range(3):
for j in range(i*2+1):
print("*",end=" ")
print()
Code:
k=5
for i in range(3, 0,-1):
for j in range(k):
print("*",end='')
k-=2
print()
OR
for i in range(3,0,-1):
for j in range(i*2-1):
print("*",end=" ")
print()
Code:
for i in range(4):
for j in range(i+1):
print("*",end='')
print()
OR
for i in range(4):
for j in range(i+1):
print("*",end=" ")
print()
123
1234
Code:
for i in range(1,5):
for j in range(1,i+1):
print(j,end='')
print()
OR
for i in range(1,5):
for j in range(1,i+1):
print(j,end=" ")
print()
Code:
for i in range(1,6):
for j in range(1,i+1):
print(i,end='')
print()
OR
for i in range(1,6):
for j in range(i):
print(i,end=" ")
print()
Code:
def reversed_number(num):
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = (reversed_num * 10) + digit
num = num // 10
return reversed_num
print()
print("Original Number: ",number)
print("Reversed Number: ",reversed_number)
26. Write a program to print reverse of a number but do not use any
loops.
Code:
no=int(input("Enter Number:"))
rev=int(str(no)[::-1])
print("Reversed: ",rev)
Code:
number = input("Enter a number: ")
sum_of_digits = 0
for digit in number:
sum_of_digits = sum_of_digits + int(digit)
print("Sum: ",sum_of_digits)
Code:
number = input("Enter a number: ")
product_of_digits = 1
Code:
num = input("Enter a number: ")
if num == num[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
OR
number = int(input("Enter a number: "))
original_number = number
reverse_number = 0
while number > 0:
digit = number % 10
reverse_number = reverse_number * 10 + digit
number //= 10
if original_number == reverse_number:
print("The number is a palindrome.")
else:
print("The number is not a palindrome.")
30. Write a program with a function which returns True if the entered
number is a palindrome.
Code:
def is_palindrome(num):
return num == num[::-1]
OR
def ispalin():
number=int(input("Enter Number: "))
n1=number
rev=0
while number>0:
rem=number%10
rev=(rev*10)+rem
number//=10
if(rev==n1):
print(f"True,{n1} is an Palindrome")
else:
print(f"False,{n1} is not an Palindrome")
ispalin()
Code:
armstrong_sum = 0
number = int(input("Enter a number: "))
temp = number
num_digits = len(str(number))
if temp == armstrong_sum:
print("Armstrong Number")
else:
print("Not a armstrong number")
Code:
print("Matrix 1: ")
print(mat1)
print("Matrix 2: ")
print(mat2)
print("Addition:\n",mat1+mat2)
print("Subtraction:\n",mat1-mat2)
print("Multiplication:\n",mat1*mat2)
print("Division:\n",mat1/mat2)
Code:
mylist = [10,20,50,5]
print("List Items:",mylist)
print("Largest Number ",max(mylist))
Code:
mylist = [10,20,30,40,50]
print("List Items:",mylist)
mylist.sort(reverse=True)
print("Descending order ",mylist)
Code:
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print("Set 1: ",set1)
print("Set 2: ",set2)
print()
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
symm_diff = set1.symmetric_difference(set2)
print("Union: ",union_set)
print("Intersection: ",intersection_set)
print("Difference: ",difference_set)
print("Symmetric Difference: ",symm_diff)
36. Ask user for details like name, age, date of birth and save it in a
dictionary
Code:
37. Write a program to input a tuple of n items from the user and display
the sum of all digits of the tuple.
Code:
concatenated_tuple = tuple(tup)
print("Ttuple:", concatenated_tuple)
print("Sum of tuple: ",sum(tup))
38. Print the entered number in words. For example: 1234 => One Two
Three Four
Code:
39. Ask the user to enter a string. Count the number of uppercase, lower
case letters and digits in the string and display the data.
Code:
40. Ask the user to enter a password. Check the password for at least: 1. 1
lower case alphabet 2. 1 upper case alphabet 3. 1 special character 4. At
Least 8 characters long
Code:
while True:
lower = False
upper = False
special_char = False
password = input("Enter a password: ")
errors=[]
if not lower:
errors.append("Password must contain at least 1 lowercase alphabet.")
if not upper:
errors.append("Password must contain at least 1 uppercase alphabet.")
if not special_char:
errors.append("Password must contain at least 1 special character.")
if len(password) < 8:
errors.append("Password must be 8 characters long")
if errors:
print("\n".join(errors))
else:
print("Password is Valid")
break
41. Ask the user for a number and calculate its factorial using a function.
Code:
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num-1)
42. Write a Python module containing basic math functions such as: 1.
average of numbers 2. add n numbers 3. square of number 4. cube of
number 5. factorial of number Import the module in another file and
demonstrate use of all functions.
#math_functions.py:
def average(numbers):
return sum(numbers)/len(numbers)
def add(*numbers):
return sum(numbers)
def square(number):
return number**2
def cube(number):
return number**3
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
#main.py:
import math_functions as m
numbers = [1,2,3,4,5]
print("Average: ",m.average(numbers))
print("Sum: ",m.add(1,2,3,4,5))
number = 4
print("Square of 4: ",m.square(number))
print("Cube of 4: ",m.cube(number))
print("Factorial of 4: ",m.factorial(number))
Code:
import calendar
print ("The calendar of year 2020 is : ")
print (calendar.calendar(2020))
44. Write a program to print calendar of the month user wants. Ask user to
enter the month and year.
Code:
import calendar
year=int(input("Enter Year:"))
month=int(input("Enter Month:"))
print (calendar.month(year,month))
45. Write a program to overload a function named as 'greet'. It must
accept at most 2 and at least no parameters. 2 parameters namely: user's
name, message to print.
Code:
greet()
greet("John")
greet("John", "Good Morning")
46. Write a program with an overloaded function area() which can be used
to calculate area of square and rectangle.
Code:
class AreaCalculator:
def area(self, length, breadth=None):
if breadth is None:
sqr = length ** 2
print("The area of square:",sqr)
else:
rect = length * breadth
print("The area of square:",rect)
calculator = AreaCalculator()
calculator.area(5)
calculator.area(4, 6)
47.Write a program with an overloaded function volume() which can be used
to calculate area of cube, cuboid and cylinder. Hint: volume of cube = (side)^3
volume of cuboid = length * breadth * width volume of cylinder =
PI*(radius)^2*height
Code:
import math
class AreaCalculator:
elif length is not None and breadth is not None and height is not None:
cuboid = length * breadth * height
print("Volume of Cuboid: ",cuboid)
c = AreaCalculator()
c.volume(side=5)
c.volume(length=4, breadth=5, height=6)
c.volume(radius=7, height=7)
48. Write a program to create a class Person with basic attributes such as
name, age and address. Create another class Employee which is derived from
Person and store information like designation, company_name, salary.
Display all the information.
Code:
class Person:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
class Employee(Person):
def __init__(self, name, age, address, designation, company_name, salary):
super().__init__(name, age, address)
self.designation = designation
self.company_name = company_name
self.salary = salary
def display_info(self):
print("Name:", self.name)
print("Age:", self.age)
print("Address:", self.address)
print("Designation:", self.designation)
print("Company Name:", self.company_name)
print("Salary:", self.salary)
# Display information
emp.display_info()
49.Write a program to implement composition relation.
Code:
class Engine:
def start(self):
print("Engine Started")
class Car:
def __init__(self,engine):
self.engine = engine
def start(self):
print("Car Started")
self.engine.start()
engine = Engine()
my_car = Car(engine)
my_car.start()
class Degree:
def getDegree(self):
print("I got a degree")
class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")
class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")
ob1 = Degree()
ob1.getDegree()
ob2 = Undergraduate()
ob2.getDegree()
ob3 = Postgraduate()
ob3.getDegree()
51. Ask user to enter a password. If the password is not 8 characters long,
throw BadPasswordError. Note: Create user defined exception
BadPasswordError
Code:
class BadPasswordError(Exception):
pass
if len(pw) < 8:
raise BadPasswordError("Password must be 8 characters long")
else:
print("Password Accepted")
52. Write a program to ask user for a number to check if it is prime or not. If
user enters an alphabet or special character instead of the number, display
"only numbers are allowed"
Code:
try:
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not a prime")
break
else:
print("Prime Number")
else:
print("Not a prime number")
except ValueError:
print("Only numbers are allowed.")
53. Write a program to print Fibonacci series of n elements. Ask user to enter
value of n.
Code:
if not n.isdigit():
print("Only integers are allowed.")
else:
n = int(n)
fib_series = [0, 1]
for i in range(2, n):
fib_series.append(fib_series[-1] + fib_series[-2])
54. Write a program with a function which returns a list of fibonacci elements.
Code:
def fibonacci_list(n):
fib_series = [0, 1]
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return fib_series
else:
for i in range(2, n):
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
# Example usage
n = int(input("Enter the number of elements in Fibonacci series: "))
fib_series = fibonacci_list(n)
print("Fibonacci series of", n, "elements:", fib_series)
55. Write a program to write data into a file. Take the data from user
Code:
f=open("file1.txt","w")
f.write(str)
f.close()
Code:
file = open("file1.txt","r")
str = file.read()
file.close()
file = open("file2.txt","wt")
file.write(str)
file.close()
57. Write a program to print the number of digits in the file. For example, if
the file's contents are: "1 sheep and 2 cows were sold," the output would be 2
Code:
file = open("file.txt","r")
content = file.read()
file.close()
digit_count=0