Professional Documents
Culture Documents
Python Practical
Python Practical
Python Practical
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str)
import math
num = float(input("Enter a number: "))
square_root = math.sqrt(num)
print("Square root:", square_root)
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Zero")
13. Program to ask user to enter a number and display if it is a prime number or not
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
14. . Program to ask user to enter their marks of 5 subjects, display average score &
percentage with their grade
marks = []
for i in range(5):
subject_mark = float(input("Enter marks for subject {}: ".format(i + 1)))
marks.append(subject_mark)
total_marks = sum(marks)
average_score = total_marks / 5
percentage = (total_marks / (5 * 70)) * 100
grade = ""
if percentage >= 90:
grade = "A+"
elif percentage >= 80:
grade = "A"
elif percentage >= 70:
grade = "B"
elif percentage >= 60:
grade = "C"
elif percentage >= 50:
grade = "D"
else:
grade = "F"
original_list = [1, 2, 3, 4, 5]
reversed_list = []
16. Program to 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"
if prime_numbers:
print("Prime numbers:", prime_numbers)
else:
print("No prime numbers found")
17. Program to ask user for a number (n) and then create a list of random integers with n
elements
import random
18. Program to print the table (up to 20) of any number that user enters
*
***
*****
***
*
rows = 5
*
***
*****
rows = 3
rows = 3
rows = 4
1
12
123
1234
rows = 4
rows = 5
for i in range(1, rows + 1):
print(str(i) * i)
def reverse_number(num):
return int(str(num)[::-1])
26. Program to print reverse of a number but do not use any loops
def reverse_number(num):
return int(str(num)[::-1])
def is_palindrome(num):
return str(num) == str(num)[::-1]
30. Program with a function which returns True if the entered number is a palindrome
def is_palindrome(num):
return str(num) == str(num)[::-1]
def is_armstrong(num):
num_str = str(num)
power = len(num_str)
sum_of_digits = sum(int(digit) ** power for digit in num_str)
return sum_of_digits == num
import numpy as np
# Define matrices
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# Addition
print("Addition:")
print(np.add(matrix1, matrix2))
# Subtraction
print("Subtraction:")
print(np.subtract(matrix1, matrix2))
# Multiplication
print("Multiplication:")
print(np.matmul(matrix1, matrix2))
# Division
print("Division:")
print(np.divide(matrix1, matrix2))
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union
print("Union:", set1.union(set2))
# Intersection
print("Intersection:", set1.intersection(set2))
# Difference
print("Difference (set1 - set2):", set1.difference(set2))
print("Difference (set2 - set1):", set2.difference(set1))
# Symmetric Difference
print("Symmetric Difference:", set1.symmetric_difference(set2))
36. Program to ask the user for details like name, age, date of birth, and save it in a
dictionary
user_details = {}
user_details['name'] = input("Enter your name: ")
user_details['age'] = int(input("Enter your age: "))
user_details['date_of_birth'] = input("Enter your date of birth (YYYY-MM-DD): ")
37. Program to input a tuple of n items from the user and display the sum of all digits of the
tuple
total_sum = 0
for item in tuple_elements:
for char in item:
if char.isdigit():
total_sum += int(char)
def number_to_words(number):
words_dict = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}
39. Ask the user to enter a string. Count the number of upper case, lower case letters and
digits in the string and display the data.
40. Ask the user to enter a password. Check the password for the given conditions.
import re
if len(password) < 8:
print("Password should be at least 8 characters long.")
elif not re.search("[a-z]", password):
print("Password should contain at least one lowercase letter.")
elif not re.search("[A-Z]", password):
print("Password should contain at least one uppercase letter.")
elif not re.search("[!@#$%^&*]", password):
print("Password should contain at least one special character.")
else:
print("Valid password.")
41. Program to ask the user for a number and calculate its factorial using a function.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
42. Write a Python module containing basic math functions such as average of numbers,
add n numbers, square of a number, cube of a number, factorial of a number. Import the
module in another file and demonstrate the use of all functions.
math_functions.py:
def average(*args):
return sum(args) / len(args)
def add(*args):
return sum(args)
def square(num):
return num ** 2
def cube(num):
return num ** 3
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
main.py:
import math_functions
numbers = [1, 2, 3, 4, 5]
print("Average:", math_functions.average(*numbers))
print("Sum:", math_functions.add(*numbers))
print("Square of 2:", math_functions.square(2))
print("Cube of 3:", math_functions.cube(3))
print("Factorial of 5:", math_functions.factorial(5))
import calendar
year = 2020
print(calendar.calendar(year))
44. Program to print the calendar of the month the user wants. Ask the user to enter the
month and year.
import calendar
print(calendar.month(year, month))
45. Program to overload a function named as 'greet'. It must accept at most 2 and at least
no parameters. If two parameters are given, it should print a message with the user's
name and the message to print.
# Test cases
greet()
greet("Alice")
greet("Bob", "Good morning!")
46. Program with an overloaded function area() which can be used to calculate the area of
square and rectangle.
# Test cases
print("Area of square (side 5):", area(5))
print("Area of rectangle (length 4, width 6):", area(4, 6))
47. Program with an overloaded function volume() which can be used to calculate the area
of cube, cuboid, and cylinder.
import math
# Test cases
print("Volume of cube (side 4):", volume("cube", 4))
print("Volume of cuboid (3x4x5):", volume("cuboid", 3, 4, 5))
print("Volume of cylinder (radius 2, height 6):", volume("cylinder", 2, 6))
48. 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, and salary. Display all the information.
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)
# Test case
emp = Employee("Alice", 30, "123 Main St", "Manager", "ABC Inc.", 50000)
emp.display_info()
49. Program to implement composition relation.
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
class Car:
def __init__(self, make, model, engine):
self.make = make
self.model = model
self.engine = engine
def display_info(self):
print("Make:", self.make)
print("Model:", self.model)
print("Engine Horsepower:", self.engine.horsepower)
50. 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.
class Degree:
def get_degree(self):
print("I got a degree")
class Undergraduate(Degree):
def get_degree(self):
print("I am an Undergraduate")
class Postgraduate(Degree):
def get_degree(self):
print("I am a Postgraduate")
# Test cases
degree = Degree()
degree.get_degree()
undergrad = Undergraduate()
undergrad.get_degree()
postgrad = Postgraduate()
postgrad.get_degree()
51. Ask the user to enter a password. If the password is not 8 characters long, throw
BadPasswordError.
class BadPasswordError(Exception):
pass
if len(password) < 8:
raise BadPasswordError("Password should be at least 8 characters long.")
else:
print("Password is valid.")
52. Write a program to ask the user for a number to check if it is prime or not. If the user
enters an alphabet or special character instead of the number, display "only numbers are
allowed".
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
try:
num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
except ValueError:
print("Only numbers are allowed.")
53. Program to print Fibonacci series of n elements. Ask the user to enter the value of n.
def fibonacci(n):
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
def fibonacci_list(n):
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
55. Program to write data into a file. Take the data from the user.