0% found this document useful (0 votes)
21 views

Python Practical

The document contains Python programs to perform tasks like input/output, string manipulation, mathematical operations, conditional statements, loops, functions, lists, tuples, sets and dictionaries. Many programs demonstrate basic patterns like printing patterns, reversing numbers/lists, checking prime numbers, palindromes etc.

Uploaded by

mbhoomi23
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)
21 views

Python Practical

The document contains Python programs to perform tasks like input/output, string manipulation, mathematical operations, conditional statements, loops, functions, lists, tuples, sets and dictionaries. Many programs demonstrate basic patterns like printing patterns, reversing numbers/lists, checking prime numbers, palindromes etc.

Uploaded by

mbhoomi23
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/ 18

1. .

Input user's name and display "Hello <username>"

name = input("Enter your name: ")


print("Hello", name)

2. Concatenate two strings

str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str)

3. Program to convert USD to INR where 1 USD = 75 INR

usd_amount = float(input("Enter amount in USD: "))


inr_amount = usd_amount * 75
print("Equivalent amount in INR:", inr_amount)

4. Program to calculate square root of a number

num = float(input("Enter a number: "))


square_root = num ** 0.5
print("Square root:", square_root)

5. Program to calculate square root of a number using math module

import math
num = float(input("Enter a number: "))
square_root = math.sqrt(num)
print("Square root:", square_root)

6. Program to find greatest of three numbers

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
greatest = max(num1, num2, num3)
print("The greatest number is:", greatest)

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

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


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")

8. Program to find out if entered number is even or odd

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

if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")

9. Program to make use of conditional operator in Python

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


y = int(input("Enter another number: "))

max_num = x if x > y else y


print("The maximum number is:", max_num)

10. Program to calculate area of triangle, square, and rectangle

base = float(input("Enter base of triangle: "))


height = float(input("Enter height of triangle: "))
triangle_area = 0.5 * base * height
print("Area of triangle:", triangle_area)

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


square_area = side ** 2
print("Area of square:", square_area)

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


width = float(input("Enter width of rectangle: "))
rectangle_area = length * width
print("Area of rectangle:", rectangle_area)

11. Program to calculate square and cube of a number

num = float(input("Enter a number: "))


square = num ** 2
cube = num ** 3
print("Square:", square)
print("Cube:", cube)
12. Program to ask user to enter a number and display if the number is positive, negative, or
zero

num = float(input("Enter a number: "))

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

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

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"

print("Average score:", average_score)


print("Percentage:", percentage)
print("Grade:", grade)

15. Program to reverse a list without using built-in functions

original_list = [1, 2, 3, 4, 5]
reversed_list = []

for i in range(len(original_list) - 1, -1, -1):


reversed_list.append(original_list[i])

print("Original List:", original_list)


print("Reversed List:", 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"

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


prime_numbers = []

for num in numbers:


if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
prime_numbers.append(num)

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

n = int(input("Enter the number of elements: "))


random_list = [random.randint(1, 100) for _ in range(n)]
print("Random List:", random_list)

18. Program to print the table (up to 20) of any number that user enters

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

for i in range(1, 21):


print(num, "x", i, "=", num * i)

19. Program to print the following pattern:

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

rows = 5

for i in range(1, rows + 1):


print("*" * i)

for i in range(rows - 1, 0, -1):


print("*" * i)

20. Program to print the following pattern:

*
***
*****

rows = 3

for i in range(1, rows + 1):


print("*" * (2*i - 1))
21. Program to print the following pattern:
*****
***
*

rows = 3

for i in range(rows, 0, -1):


print("*" * (2*i - 1))

22. Program to print the following pattern:


*
**
***
****

rows = 4

for i in range(1, rows + 1):


print("*" * i)

23. Program to print the following pattern:

1
12
123
1234

rows = 4

for i in range(1, rows + 1):


for j in range(1, i + 1):
print(j, end="")
print()

24. Program to print the following pattern:


1
22
333
4444
55555

rows = 5
for i in range(1, rows + 1):
print(str(i) * i)

25. Program with a function to reverse the given number

def reverse_number(num):
return int(str(num)[::-1])

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


reversed_number = reverse_number(number)
print("Reversed number:", reversed_number)

26. Program to print reverse of a number but do not use any loops

def reverse_number(num):
return int(str(num)[::-1])

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


reversed_number = reverse_number(number)
print("Reversed number:", reversed_number)

27. Program to print the sum of digits of an entered number

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


sum_of_digits = sum(map(int, str(abs(number))))
print("Sum of digits:", sum_of_digits)

28. Program to print the product of digits of an entered number

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


product_of_digits = 1

for digit in str(abs(number)):


product_of_digits *= int(digit)

print("Product of digits:", product_of_digits)

29. Program to check if the entered number is a palindrome or not

def is_palindrome(num):
return str(num) == str(num)[::-1]

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


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

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]

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


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

31. Program to determine if an entered number is an Armstrong number or not

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

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


if is_armstrong(number):
print("Armstrong number")
else:
print("Not an Armstrong number")

32. Program to add, subtract, multiply, and divide matrices

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

33. Program to find the largest number from a list

numbers = [5, 8, 2, 10, 3]


largest_number = max(numbers)
print("Largest number:", largest_number)

34. . Program to sort a list in descending order

numbers = [5, 8, 2, 10, 3]


sorted_numbers = sorted(numbers, reverse=True)
print("Sorted list in descending order:", sorted_numbers)

35. Program to perform set operations

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

print("User details:", user_details)

37. Program to input a tuple of n items from the user and display the sum of all digits of the
tuple

tuple_elements = tuple(input("Enter elements separated by spaces: ").split())

total_sum = 0
for item in tuple_elements:
for char in item:
if char.isdigit():
total_sum += int(char)

print("Sum of digits:", total_sum)

38. Print the entered number in words

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'
}

return ' '.join(words_dict[char] for char in str(number))

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


print("Number in words:", number_to_words(number))

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.

string = input("Enter a string: ")


upper_count = sum(1 for char in string if char.isupper())
lower_count = sum(1 for char in string if char.islower())
digit_count = sum(1 for char in string if char.isdigit())

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


print("Number of lowercase letters:", lower_count)
print("Number of digits:", digit_count)

40. Ask the user to enter a password. Check the password for the given conditions.

import re

password = input("Enter a password: ")

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)

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


print("Factorial of", number, "is", factorial(number))

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

43. Program to print the calendar of the year 2020.

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

year = int(input("Enter the year: "))


month = int(input("Enter the month: "))

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.

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


if name and message:
print(f"Hello {name}, {message}")
elif name:
print(f"Hello {name}")
else:
print("Hello")

# 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.

def area(length, width=None):


if width is None:
# Calculate area of square
return length ** 2
else:
# Calculate area of rectangle
return length * width

# 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

def volume(shape, *args):


if shape == "cube":
# Calculate volume of cube
side = args[0]
return side ** 3
elif shape == "cuboid":
# Calculate volume of cuboid
length, width, height = args
return length * width * height
elif shape == "cylinder":
# Calculate volume of cylinder
radius, height = args
return math.pi * radius ** 2 * height

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

# Composition: Car "has a" Engine


engine = Engine(200)
car = Car("Toyota", "Camry", engine)
car.display_info()

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

password = input("Enter a password: ")

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

n = int(input("Enter the number of elements: "))


print("Fibonacci series of", n, "elements:", fibonacci(n))

54. . Program with a function which returns a list of Fibonacci elements.

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

n = int(input("Enter the number of elements: "))


print("Fibonacci series:", fibonacci_list(n))

55. Program to write data into a file. Take the data from the user.

data = input("Enter data to write into the file: ")

with open("data.txt", "w") as file:


file.write(data)

print("Data has been written to the file.")

56. Program to copy contents of one file to another.

source_file = input("Enter source file name: ")


destination_file = input("Enter destination file name: ")

with open(source_file, "r") as source:


with open(destination_file, "w") as destination:
destination.write(source.read())

print("Contents copied from", source_file, "to", destination_file)

57. Program to print the number of digits in the file.

filename = input("Enter file name: ")

with open(filename, "r") as file:


content = file.read()
digit_count = sum(1 for char in content if char.isdigit())

print("Number of digits in the file:", digit_count)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy