100% found this document useful (1 vote)
5 views18 pages

Python Programs With Solutions

This document provides a comprehensive list of Python programming exercises along with their solutions, covering a variety of topics such as data manipulation, control structures, functions, classes, and libraries like NumPy and Pandas. Each program is numbered according to a practical examination format, allowing for easy reference. The document serves as a practical guide for students to enhance their programming skills through hands-on coding examples.

Uploaded by

khairnarnayan941
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
100% found this document useful (1 vote)
5 views18 pages

Python Programs With Solutions

This document provides a comprehensive list of Python programming exercises along with their solutions, covering a variety of topics such as data manipulation, control structures, functions, classes, and libraries like NumPy and Pandas. Each program is numbered according to a practical examination format, allowing for easy reference. The document serves as a practical guide for students to enhance their programming skills through hands-on coding examples.

Uploaded by

khairnarnayan941
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

Python Programming

Practical Examination – Programs with Solutions

This document contains all programs from the practical examination list along with correct Python solutions.
Each program is numbered to match the original question sheet.
Programs for Practical Examination

Q1. Find Second Largest and Second Smallest Number


numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
unique = list(set(numbers))
[Link]()

if len(unique) >= 2:
print("Second Smallest:", unique[1])
print("Second Largest:", unique[-2])
else:
print("Not enough unique numbers.")

Q2. Separate Even and Odd Numbers into Two Lists


numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))

even = [n for n in numbers if n % 2 == 0]


odd = [n for n in numbers if n % 2 != 0]

print("Even numbers:", even)


print("Odd numbers:", odd)

Q3. Swap Two Numbers using Tuple Assignments


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(f"Before swap: a = {a}, b = {b}")


a, b = b, a
print(f"After swap: a = {a}, b = {b}")

Q4. Find Frequency of an Element in a List


numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
element = int(input("Enter element to find frequency of: "))

frequency = [Link](element)
print(f"Frequency of {element}: {frequency}")

Q5. Read Prices of 5 Items – Sum, Product, Average


prices = []
for i in range(1, 6):
price = float(input(f"Enter price of item {i}: "))
[Link](price)

total = sum(prices)
product = 1
for p in prices:
product *= p

average = total / len(prices)

print(f"Sum of all prices: {total:.2f}")


print(f"Product of all prices: {product:.2f}")
print(f"Average price: {average:.2f}")

Q6. Count Number of Words in a Sentence


sentence = input("Enter a sentence: ")
word_count = len([Link]())
print(f"Number of words: {word_count}")

Q7. Count Number of Characters in a Sentence


sentence = input("Enter a sentence: ")
char_count = len(sentence)
char_no_spaces = len([Link](" ", ""))
print(f"Total characters (with spaces): {char_count}")
print(f"Total characters (without spaces): {char_no_spaces}")

Q8. Dictionary – Print RollNo Where Percentage > 50


students = {}
for i in range(10):
roll = int(input(f"Enter Roll No of student {i+1}: "))
perc = float(input(f"Enter Percentage of student {i+1}: "))
students[roll] = perc

print("\nRoll Numbers with Percentage > 50:")


for roll, perc in [Link]():
if perc > 50:
print(f" Roll No: {roll} -> {perc}%")

Q9. Prices of 5 Items – Sum, Product, Average (same as Q5)


# Same as Q5 – reusing for completeness
prices = []
for i in range(1, 6):
price = float(input(f"Enter price of item {i}: "))
[Link](price)

total = sum(prices)
product = 1
for p in prices:
product *= p
average = total / len(prices)

print(f"Sum : {total:.2f}")
print(f"Product : {product:.2f}")
print(f"Average : {average:.2f}")

Q10. Reverse a String (Without Slicing)


text = input("Enter a string: ")
reversed_text = ""
for ch in text:
reversed_text = ch + reversed_text
print("Reversed string:", reversed_text)

Q11. Check Whether a String is Palindrome or Not


text = input("Enter a string: ").lower().replace(" ", "")
reversed_text = text[::-1]

if text == reversed_text:
print(f'"{text}" is a Palindrome.')
else:
print(f'"{text}" is NOT a Palindrome.')

Q12. List of Numbers from 1 to 20 Divisible by 4


divisible_by_4 = [n for n in range(1, 21) if n % 4 == 0]
print("Numbers from 1 to 20 divisible by 4:", divisible_by_4)

Q13. Fibonacci Series – Store in List and Find Sum


n = int(input("How many Fibonacci numbers? "))
fib = [0, 1]

for i in range(2, n):


[Link](fib[-1] + fib[-2])

fib = fib[:n]
print("Fibonacci series:", fib)
print("Sum of all values:", sum(fib))

Q14. Search for an Element in a List


numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
target = int(input("Enter element to search: "))

if target in numbers:
idx = [Link](target)
print(f"Element {target} found at index {idx}.")
else:
print(f"Element {target} not found in the list.")

Q15. Calculate Area of Rhombus


d1 = float(input("Enter diagonal 1: "))
d2 = float(input("Enter diagonal 2: "))
area = (d1 * d2) / 2
print(f"Area of Rhombus = {area:.2f}")

Q16. Inverted Right Triangle Pattern


rows = int(input("Enter number of rows: "))
for i in range(rows, 0, -1):
print("* " * i)

Q17. Hollow Right Triangle Pattern


rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
if j == 1 or j == i or i == rows:
print("*", end=" ")
else:
print(" ", end=" ")
print()

Q18. Continuous Number Pattern


rows = int(input("Enter number of rows: "))
num = 1
for i in range(1, rows + 1):
for j in range(i):
print(num, end=" ")
num += 1
print()

Q19. Binary Pattern


rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
for j in range(i):
print((i + j) % 2, end="")
print()

Q20. Continuous Alphabet Pattern


rows = int(input("Enter number of rows: "))
ch = 65 # ASCII for 'A'
for i in range(1, rows + 1):
for j in range(i):
print(chr(ch), end=" ")
ch += 1
print()

Q21. Same Number Row Pattern


rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
print((str(i) + " ") * i)

Q22. Sum of Squares of First N Natural Numbers


n = int(input("Enter N: "))
total = sum(i**2 for i in range(1, n + 1))
print(f"Sum of squares of first {n} natural numbers = {total}")

Q23. Check if a Given Number is Prime or Not


n = int(input("Enter a number: "))
if n < 2:
print(f"{n} is NOT a prime number.")
else:
is_prime = all(n % i != 0 for i in range(2, int(n**0.5) + 1))
print(f"{n} is {'a PRIME' if is_prime else 'NOT a prime'} number.")

Q24. Check Armstrong Number Using Function


def is_armstrong(n):
digits = str(n)
power = len(digits)
return n == sum(int(d)**power for d in digits)

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


if is_armstrong(n):
print(f"{n} is an Armstrong number.")
else:
print(f"{n} is NOT an Armstrong number.")

Q25. Function – Sum of All Even Numbers in a List


def sum_even(numbers):
return sum(n for n in numbers if n % 2 == 0)

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))


print("Sum of even numbers:", sum_even(nums))

Q26. Function – Check Whether a Number Falls Within a Range


def in_range(n, start, end):
return start <= n <= end

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


start = int(input("Enter range start: "))
end = int(input("Enter range end: "))

if in_range(n, start, end):


print(f"{n} is within the range [{start}, {end}].")
else:
print(f"{n} is outside the range [{start}, {end}].")
Q27. Function – Sum All Numbers in a List
def sum_list(numbers):
total = 0
for n in numbers:
total += n
return total

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))


print("Sum:", sum_list(nums))

Q28. Function – Return List with Distinct Elements


def distinct(lst):
seen = []
for item in lst:
if item not in seen:
[Link](item)
return seen

nums = list(map(int, input("Enter numbers separated by spaces: ").split()))


print("Distinct elements:", distinct(nums))

Q29. Calculate Simple Interest with Default Arguments


def simple_interest(principal, rate=5, time=1):
si = (principal * rate * time) / 100
return si

p = float(input("Enter principal: "))


r = float(input("Enter rate (press Enter for default 5%): ") or 5)
t = float(input("Enter time in years (press Enter for default 1): ") or 1)

print(f"Simple Interest = {simple_interest(p, r, t):.2f}")

Q30. Factorial of a Number Using Recursion


def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

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


print(f"Factorial of {n} = {factorial(n)}")

Q31. Fibonacci of a Number Using Recursion


def fibonacci(n):
if n <= 0:
return 0
if n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)

n = int(input("Enter position (n): "))


print(f"Fibonacci({n}) = {fibonacci(n)}")

Q32. Pass a List to a Function – Max, Min, Average


def list_stats(numbers):
return max(numbers), min(numbers), sum(numbers) / len(numbers)

nums = list(map(float, input("Enter numbers separated by spaces: ").split()))


mx, mn, avg = list_stats(nums)
print(f"Max: {mx} | Min: {mn} | Average: {avg:.2f}")

Q33. Displaying Student Profiles Using **kwargs


def student_profile(**kwargs):
print("\nStudent Profile:")
for key, value in [Link]():
print(f" {[Link]()}: {value}")

student_profile(name="Alice", rollno=101, grade="A", marks=92)


student_profile(name="Bob", rollno=102, grade="B", marks=78)

Q34. Bank Account Class


class BankAccount:
def __init__(self, owner, balance=0):
[Link] = owner
[Link] = balance

def deposit(self, amount):


[Link] += amount
print(f"Deposited {amount}. New balance: {[Link]}")

def withdraw(self, amount):


if amount > [Link]:
print("Insufficient funds!")
else:
[Link] -= amount
print(f"Withdrew {amount}. Remaining balance: {[Link]}")

def enquire(self):
print(f"Account holder: {[Link]}, Balance: {[Link]}")

acc = BankAccount("Alice", 1000)


[Link]()
[Link](500)
[Link](300)
[Link](2000)
Q35. Employee Class with Rating Based on Salary
class Employee:
def __init__(self, name, emp_id, salary):
[Link] = name
self.emp_id = emp_id
[Link] = salary

def get_rating(self):
if [Link] >= 80000:
return "Excellent"
elif [Link] >= 50000:
return "Good"
elif [Link] >= 30000:
return "Average"
else:
return "Below Average"

def display(self):
print(f"Name: {[Link]} | ID: {self.emp_id} | "
f"Salary: {[Link]} | Rating: {self.get_rating()}")

e1 = Employee("Alice", "E001", 90000)


e2 = Employee("Bob", "E002", 45000)
[Link]()
[Link]()

Q36. Product Class – Accept and Display 3 Products


class Product:
def __init__(self, product_id, name, price):
self.product_id = product_id
[Link] = name
[Link] = price

def display(self):
print(f"ID: {self.product_id} | Name: {[Link]} | Price: {[Link]:.2f}")

products = []
for i in range(3):
pid = input(f"Enter Product ID {i+1}: ")
name = input(f"Enter Product Name {i+1}: ")
price = float(input(f"Enter Price {i+1}: "))
[Link](Product(pid, name, price))

print("\n--- Product Details ---")


for p in products:
[Link]()

Q37. Student Class with Grade Calculation


class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks

def get_grade(self):
if [Link] >= 90:
return "A+"
elif [Link] >= 80:
return "A"
elif [Link] >= 70:
return "B"
elif [Link] >= 60:
return "C"
elif [Link] >= 50:
return "D"
else:
return "F"

def display(self):
print(f"Name: {[Link]} | Marks: {[Link]} | Grade: {self.get_grade()}")

s1 = Student("Alice", 92)
s2 = Student("Bob", 75)
s3 = Student("Carol", 45)
[Link]()
[Link]()
[Link]()

Q38. Calculate Area of Triangle Using a Class Method


class Triangle:
def area(self, base, height):
return 0.5 * base * height

t = Triangle()
b = float(input("Enter base: "))
h = float(input("Enter height: "))
print(f"Area of Triangle = {[Link](b, h):.2f}")

Q39. Parameterized Constructor in Car Class


class Car:
def __init__(self, make, model, year, color):
[Link] = make
[Link] = model
[Link] = year
[Link] = color

def display(self):
print(f"Car Details -> Make: {[Link]}, Model: {[Link]}, "
f"Year: {[Link]}, Color: {[Link]}")
car = Car("Toyota", "Camry", 2022, "White")
[Link]()

Q40. NumPy – Player Scores Array


import numpy as np

scores = [Link]([85, 92, 78, 95, 88, 72, 90, 84, 76, 91])

print("All scores: ", scores)


print("First player score: ", scores[0])
print("Last player score: ", scores[-1])
print("First five scores (slicing):", scores[:5])
print("Alternate scores: ", scores[::2])

Q41. NumPy – Employee Salaries Array


import numpy as np

salaries = [Link]([35000, 42000, 58000, 67000, 75000, 90000])

print("All salaries: ", salaries)


print("First employee salary: ", salaries[0])
print("Fourth employee salary: ", salaries[3])
print("First three salaries: ", salaries[:3])
print("Salaries in reverse order: ", salaries[::-1])

Q42. Display All Odd Elements from 1 to 100 (NumPy)


import numpy as np

arr = [Link](1, 101)


odd_elements = arr[arr % 2 != 0]
print("Odd elements from 1 to 100:")
print(odd_elements)

Q43. Display All Even Elements from 1 to 100 (NumPy)


import numpy as np

arr = [Link](1, 101)


even_elements = arr[arr % 2 == 0]
print("Even elements from 1 to 100:")
print(even_elements)

Q44. Mean, Median, and Standard Deviation of a NumPy Array


import numpy as np

arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
print("Array: ", arr)
print("Mean: ", [Link](arr))
print("Median: ", [Link](arr))
print("Standard Deviation: ", [Link](arr))

Q45. Filter Pandas Series Values Greater Than 20


import pandas as pd

data = [Link]([5, 15, 25, 35, 10, 45, 20, 30])


result = data[data > 20]
print("Original Series:")
print(data)
print("\nValues greater than 20:")
print(result)

Q46. Apply Function to Series – Square of Values


import pandas as pd

data = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])


squares = [Link](lambda x: x ** 2)
print("Original Series:")
print(data)
print("\nSquares:")
print(squares)

Q47. DataFrame of 5 Students – Filter, Add Column, Sort


import pandas as pd

data = {
'Name': ['Alice', 'Bob', 'Carol', 'Dave', 'Eve'],
'Age': [20, 21, 19, 22, 20],
'Marks': [85, 72, 91, 65, 88]
}
df = [Link](data)
print("Original DataFrame:")
print(df)

# a) Students scoring above 80


print("\na) Students scoring above 80:")
print(df[df['Marks'] > 80])

# b) Add Grade column


def assign_grade(m):
if m >= 90: return 'A'
elif m >= 80: return 'B'
elif m >= 70: return 'C'
else: return 'D'

df['Grade'] = df['Marks'].apply(assign_grade)
print("\nb) DataFrame with Grade column:")
print(df)

# c) Sort by marks descending


print("\nc) Sorted by Marks (descending):")
print(df.sort_values('Marks', ascending=False))

Q48. Load CSV with Pandas and Display Basic Statistics


import pandas as pd

df = pd.read_csv("[Link]") # replace with your CSV file path


print("First 5 rows:")
print([Link]())
print("\nBasic Statistics:")
print([Link]())

Q49. Line Graph of Monthly Sales


import [Link] as plt

months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec']
sales = [1500,1800,1700,2100,2400,2200,
2600,2800,2500,2300,2700,3000]

[Link](figsize=(10, 5))
[Link](months, sales, marker='o', color='steelblue', linewidth=2)
[Link]("Monthly Sales")
[Link]("Month")
[Link]("Sales")
[Link](True)
plt.tight_layout()
[Link]()

Q50. Bar Chart for Student Marks


import [Link] as plt

students = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']


marks = [85, 72, 91, 65, 88]

[Link](figsize=(8, 5))
[Link](students, marks, color=['#1976d2','#43a047','#fb8c00','#e53935','#8e24aa'])
[Link]("Student Marks")
[Link]("Student")
[Link]("Marks")
[Link](0, 100)
plt.tight_layout()
[Link]()

Q51. Pie Chart for Subject-Wise Marks


import [Link] as plt

subjects = ['Math', 'Science', 'English', 'History', 'Computer']


marks = [85, 92, 78, 70, 95]

[Link](figsize=(7, 7))
[Link](marks, labels=subjects, autopct='%1.1f%%',
startangle=140, shadow=True)
[Link]("Subject-wise Marks")
plt.tight_layout()
[Link]()

Q52. Scatter Graph for Age vs Salary


import [Link] as plt

age = [22, 25, 28, 30, 35, 38, 42, 45, 50, 55]
salary = [25000,32000,40000,45000,55000,
60000,70000,75000,80000,90000]

[Link](figsize=(8, 5))
[Link](age, salary, color='coral', edgecolors='black', s=100)
[Link]("Age vs Salary")
[Link]("Age")
[Link]("Salary")
[Link](True)
plt.tight_layout()
[Link]()

Q53. Histogram of Random Numbers


import [Link] as plt
import numpy as np

data = [Link](1000)

[Link](figsize=(8, 5))
[Link](data, bins=30, color='teal', edgecolor='black')
[Link]("Histogram of Random Numbers")
[Link]("Value")
[Link]("Frequency")
plt.tight_layout()
[Link]()

Mock Practical Questions

QM1. Sum of Two Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"Sum = {a + b}")
QM2. Manage Student Records Using Tuples and Lists
students = []
n = int(input("Enter number of students: "))

for _ in range(n):
sid = int(input("Enter student ID: "))
name = input("Enter student name: ")
m1, m2, m3 = map(float, input("Enter marks in 3 subjects: ").split())
[Link]((sid, name, m1, m2, m3))

print("\nStudent Records:")
for s in students:
avg = (s[2] + s[3] + s[4]) / 3
print(f"ID: {s[0]} | Name: {s[1]} | "
f"Marks: {s[2]}, {s[3]}, {s[4]} | Average: {avg:.2f}")

QM3. Simple Shopping Cart System Using Tuples and Lists


products = []
n = int(input("Enter number of products: "))

for _ in range(n):
pid = input("Enter product ID: ")
name = input("Enter product name: ")
price = float(input("Enter price: "))
[Link]((pid, name, price))

print("\n--- Shopping Cart ---")


total = 0
for p in products:
print(f"ID: {p[0]} | Name: {p[1]} | Price: {p[2]:.2f}")
total += p[2]
print(f"Total bill: {total:.2f}")

QM4. Check Whether a Number is Positive, Negative, or Zero


n = float(input("Enter a number: "))
if n > 0:
print(f"{n} is Positive.")
elif n < 0:
print(f"{n} is Negative.")
else:
print("The number is Zero.")

QM5. Student Names, Marks in 3 Subjects, Average Using List of Dicts


n = int(input("Enter number of students: "))
students = []
for _ in range(n):
name = input("Enter student name: ")
marks = list(map(float, input("Enter marks in 3 subjects: ").split()))
[Link]({"name": name, "marks": marks})
print("\nStudent Averages:")
for s in students:
avg = sum(s["marks"]) / len(s["marks"])
print(f" {s['name']}: Average = {avg:.2f}")

QM6. Display Unique Vowels in a String Using Set


text = input("Enter a string: ").lower()
vowels = set(ch for ch in text if ch in "aeiou")
print("Unique vowels present:", sorted(vowels))

QM7. Check if a Number is Prime


n = int(input("Enter a number: "))
if n < 2:
print(f"{n} is NOT prime.")
else:
is_prime = all(n % i != 0 for i in range(2, int(n**0.5) + 1))
print(f"{n} is {'PRIME' if is_prime else 'NOT prime'}.")

QM8. Fibonacci Series up to N Terms Using Function


def fibonacci(n):
series = []
a, b = 0, 1
for _ in range(n):
[Link](a)
a, b = b, a + b
return series

n = int(input("Enter number of terms: "))


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

QM9a. Function to Add Two Numbers with Docstring


def add(a, b):
"""Returns the sum of two numbers a and b."""
return a + b

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


y = int(input("Enter second number: "))
print("Sum:", add(x, y))
print("Docstring:", add.__doc__)

QM9b. Function Returning Square, Cube, and Square Root


import math

def compute(n):
return n**2, n**3, [Link](n)
n = float(input("Enter a number: "))
sq, cu, sr = compute(n)
print(f"Square: {sq} | Cube: {cu} | Square Root: {sr:.4f}")

QM9c. Function with Default Arguments for Student Details


def student_details(name, age=18, grade="N/A"):
print(f"Name: {name} | Age: {age} | Grade: {grade}")

student_details("Alice")
student_details("Bob", 20, "A")
student_details("Carol", grade="B")

QM10a. Demonstrate Local and Global Variables


x = 10 # global

def show_local():
x = 50 # local
print("Local x:", x)

def modify_global():
global x
x = 99
print("Global x inside function:", x)

show_local()
print("Global x:", x)
modify_global()
print("Global x after modification:", x)

QM10b. Built-in Functions – max, min, sum, len on a List


nums = list(map(int, input("Enter numbers: ").split()))

print(f"Max: {max(nums)}")
print(f"Min: {min(nums)}")
print(f"Sum: {sum(nums)}")
print(f"Length: {len(nums)}")

QM11a. Lambda Functions – Square and Addition


square = lambda x: x ** 2
add = lambda x, y: x + y

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


a = int(input("Enter first number for addition: "))
b = int(input("Enter second number for addition: "))

print(f"Square of {n}: {square(n)}")


print(f"Sum of {a} and {b}: {add(a, b)}")
QM11b. Sort a List Using Lambda
nums = list(map(int, input("Enter numbers: ").split()))
[Link](key=lambda x: x)
print("Sorted list:", nums)

# Sort in descending order


[Link](key=lambda x: -x)
print("Sorted descending:", nums)

You might also like