Python Practical QB - Full Finall

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

1.

Input user's name and display "Hello "

Code:

name=input("Enter Your Name:")

if not name:
print("Enter Name first")
else:
print("Hello",name)

2. Concatenate two strings

Code:

str1=input("Enter string 1:")


str2=input("Enter string2:")
print(str1+str2)

3. Write a program to convert USD to INR where 1 USD = 75 INR

Code:

usd=float(input("Enter Dollar amount:"))


print("The INR amount of us dollar",usd,":",usd*75)

4. Write a program to calculate the square root of a number.

Code:

no=int(input("Enter number for getting square root:"))


print("Square root of",no,"=",no**0.5)

5. Write a program to calculate square root of a number using math


module

Code:
import math
no=int(input("Enter number for getting square root:"))
print("Square root of",no,"=",math.sqrt(no))

6. Write a program to find greatest of three numbers

Code:
a=int(input("Enter Number 1:"))
b=int(input("Enter Number 2:"))
c=int(input("Enter Number 3:"))

if(a>b) and (a>c):


l=a
elif(b>a) and (b>c):
l=b
else:
l=c
print("Greatest number=",l)

7. Write a program to find out if entered year is a leap year or not

Code:
year=int(input("Enter Year:"))

if(year%4==0 and year%100!=0 or year%400==0):


print("Year is leap")
else:
print("Year is not leap")

8. Write a program to find out if entered number is even or odd

Code:
n=int(input("Enter Number:"))

if(n%2==0):
print("Number is even")
else:
print("Number is odd")

9. Write a program to make use of conditional operator in Python

Code:
age = int(input("Enter your age: "))
eligible = "Yes" if age >= 18 else "No"
print("Are you eligible to vote? " + eligible)

10. Write a program to calculate area of triangle, square and rectangle


Code:
base = float(input("Enter triangle base: "))
height = float(input("Enter triange height: "))

t_area = 0.5 * base * height


print("Triangle Area: ",t_area)
print()

side = float(input("Enter side of square: "))


s_area = side * side
print("Square area: ",s_area)
print()

length = float(input("Enter rectangle length: "))


breadth = float(input("Enter rectangle width: "))
r_area = length * breadth
print("Rectangle area: ",r_area)

11. Write a program to calculate square and cube of a number

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

if percentage >= 90:


grade = 'A'
elif percentage >= 80:
grade = 'B'
elif percentage >= 70:
grade = 'C'
elif percentage >= 60:
grade = 'D'
else:
grade = 'F'

print("Average Score: {:.2f}".format(average_score))


print("Percentage: {:.2f}".format(percentage))
print("Grade: ", grade)

15. Write a program to reverse a list without using built in functions.

Code:
list1 = [10, 20, 30, 40, 50]
print("Original List: ")
print(list1)

print("Reversed List: ")


for i in range(4, -1, -1):
print(list1[i], end=" ")
OR
l1=[1,2,3]
print(l1[::-1])
16. Create a list of numbers and display every prime number from the list.
If there are no prime numbers in the list, display "No prime numbers
found"

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)

19. Write a program to print the following pattern:


*
***
*****
***
*
Code:
def print_pattern(n):
for i in range(-n+1, n):
print(" " * abs(i) + "*" * (2 * (n - abs(i)) - 1))

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

20. Write a program to print the following pattern:


*
***
*****

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()

21. Write a program to print the following pattern:


*****
***
*

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()

22. Write a program to print the following pattern:


*
**
***
****

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()

23. Write a program to print the following pattern:


1
12

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()

24. Write a program to print the following pattern:


1
22
333
4444
55555

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()

25. Write a program with a function to reverse the given number.

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

number = int(input("Enter a number: "))


reversed_number = reversed_number(number)

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)

27. Write a program to print the sum of digits of an entered number.

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)

28. Write a program to print the product of digits of an entered number.

Code:
number = input("Enter a number: ")
product_of_digits = 1

for digit in number:


product_of_digits = product_of_digits * int(digit)
print("Product: ",product_of_digits)

29. Write a program to check if the entered number is a palindrome or


not.

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]

number = input("Enter a number: ")


if is_palindrome(number):
print("Palindrome")
else:
print("Not a Palindrome")

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()

31. Write a program to deteremine if an entered number is an armstrong


number or not.

Code:

armstrong_sum = 0
number = int(input("Enter a number: "))
temp = number
num_digits = len(str(number))

while number > 0:


digit = number % 10
armstrong_sum = armstrong_sum + digit**num_digits
number = number // 10

if temp == armstrong_sum:
print("Armstrong Number")
else:
print("Not a armstrong number")

32. Write a program to add, subtract, multiply and divide matrices.

Code:

from numpy import *


mat1 = array( [ [1,2], [3,4] ] )
mat2 = array( [ [5,6], [7,8] ] )

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)

33. Write a program to find the largest number from a list.

Code:
mylist = [10,20,50,5]
print("List Items:",mylist)
print("Largest Number ",max(mylist))

34. Write a program to sort a list in descending order.

Code:
mylist = [10,20,30,40,50]
print("List Items:",mylist)
mylist.sort(reverse=True)
print("Descending order ",mylist)

35. Write a program to perform set operatons.

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:

name = input("Enter your name: ")


age = int(input("Enter your age: "))
dob = input("Enter your date of birth (DD-MM-YYYY): ")
details = {
'Name': name,
'Age': age,
'Date of Birth': dob
}
print("\nUser Details:")
print(details)

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:

n = int(input("Enter no. of items u want to add in tuple: "))


tup=()
for i in range(n):
item = int(input(f"Enter item(number) {i+1}: "))
tup += (item,)

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:

# Dictionary mapping digits to words


digit_to_word = {
'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
'5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine'
}

# Function to print number in words


def print_number_in_words(number):
# Convert the number to a string
number_str = str(number)
# Iterate through each digit of the number and print its word representation
for digit in number_str:
print(digit_to_word[digit], end=' ')

# Take input from the user


number = int(input("Enter a number: "))

# Print the entered number in words


print("Number in words:", end=' ')
print_number_in_words(number)

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:

st = input("Enter a string: ")


upper = 0
lower = 0
digit = 0

for char in st:


if char.isupper():
upper += 1
elif char.islower():
lower += 1
elif char.isdigit():
digit += 1

print("Number of uppercase letters:", upper)


print("Number of lowercase letters:",lower)
print("Number of digits:",digit)

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: ")

for char in password:


if char.isupper():
upper = True
elif char.islower():
lower = True
elif char in "!@#$%^&*":
special_char = True

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

print("Please try again")

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)

number = int(input("Enter a number: "))


result = factorial(number)
print("Factorial: ",result)

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))

43. Write a program to print the calendar of year 2020

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:

def greet(name=None, message=None):


if name is None and message is None:
print("HELLO!")
elif message is None:
print("Hello, ",name)
else:
print(name,message)

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:

def volume(self, length=None, breadth=None, width=None, side=None,


radius=None, height = None):

if side is not None:


cube = side**3
print("Volume of Cube: ",cube)

elif length is not None and breadth is not None and height is not None:
cuboid = length * breadth * height
print("Volume of Cuboid: ",cuboid)

elif radius is not None and height is not None:


cylinder = math.pi * (radius**2) * height
print("Volume of Cylinder: ",cylinder)

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)

# Create an instance of Employee


emp = Employee("John Doe", 30, "123 Main St, City", "Software Engineer",
"ABC Corp", 50000)

# 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()

50. Write a Python program to create a class 'Degree' having a method


'getDegree' that prints "I got a degree". It has two subclasses namely
'Undergraduate' and 'Postgraduate' each having a method with the same
name that prints "I am an Undergraduate" and "I am a Postgraduate"
respectively. Call the method by creating an object of each of the three classes.
Code:

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

pw = input("Enter Password: ")

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:

n = input("Enter the number of elements in Fibonacci series: ")

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])

print("Fibonacci series of", n, "elements:", fib_series[:n])

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")

str = input("Enter text to be inserted in the file: ")

f.write(str)
f.close()

56. Write a program to copy contents of one file.

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

for char in content:


if char.isdigit():
digit_count += 1

print("Number of Digits in a file: ",digit_count)

You might also like