0% found this document useful (0 votes)
17 views26 pages

Python Final

The document contains a series of practical programming questions and solutions in Python, covering various topics such as calculating averages, conditional statements, string manipulation, exception handling, and using libraries like NumPy and pandas. Each question includes a brief description and corresponding code snippet to demonstrate the solution. The questions range from basic input/output operations to more advanced concepts like classes, inheritance, and data manipulation with DataFrames.

Uploaded by

aanku5835
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views26 pages

Python Final

The document contains a series of practical programming questions and solutions in Python, covering various topics such as calculating averages, conditional statements, string manipulation, exception handling, and using libraries like NumPy and pandas. Each question includes a brief description and corresponding code snippet to demonstrate the solution. The questions range from basic input/output operations to more advanced concepts like classes, inheritance, and data manipulation with DataFrames.

Uploaded by

aanku5835
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PRACTICAL QUESTION :-1

Write a Program to calculate average marks of a student.(5 subjects) Hint-


add marks of all five subjects divide by 5.

m1 = int(input("Enter marks 1:
")) m2 = int(input("Enter marks
2: ")) m3 = int(input("Enter
marks 3: ")) m4 =
int(input("Enter marks 4: ")) m5
= int(input("Enter marks 5: "))

average = (m1 + m2 + m3 + m4 + m5) / 5


print("Average marks =",average)
PRACTICAL QUESTION :-2

Write a program to input a number and print whether it is positive,


negative, or zero.

num = float(input("enter number:"))

if num > 0:
print("positive number")
elif num < 0:
print("negative number")
else:
print("zero")
PRACTICAL QUESTION :-3

Input marks (5 Subjects) from the user , calculate average and print the grade
based on the following scale of average marks.
a) A: 90 and above
b) B: 80–89
c) C: 70–79
d) D: 60–69
e) F: Below 60

avg = float(input("enter average marks"))


if avg >=90:
print("Grade: A")
elif avg >=80:
print("Grade: B")
elif avg >=70:
print("Grade: C")
elif avg >=60:
print("Grade: D")
else:
print("Grade: f”)
PRACTICAL QUESTION :-4

Write a program that takes a person’s age and classifies them as:
a) Child (0–12)
b) Teen (13–19)
c) Adult (20–59)
d) Senior (60+)

age = int(input("Enter age: "))

if age <= 12:


print("Child")
elif age <=19:
print("Teen")
elif age <=59:
print("Adult")
else:
print("Senior")
PRACTICAL QUESTION :-5

Input three numbers and print the largest one.

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


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:


print("largest =", a)
elif b >= a and b >= c:
print("largest =",b)
else:
print("largest =",c)
PRACTICAL QUESTION :-6

Input two numbers and an operator (+, -, , /). Perform the operation based on
the operator.

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


num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")

# Operation
if op == "+":
print("Result:", num1 + num2)

elif op == "-":
print("Result:", num1 - num2)

elif op == "*":
print("Result:", num1 * num2)

elif op == "/":
if num2 !=
0:
print("Result:", num1 / num2)
else:
print("Error: Division by zero")

else:
print("Invalid operator")
PRACTICAL QUESTION :-7

Ask the user to input a password and evaluate its strength:


a) Weak (less than 6 characters)
b) Medium (6–10 characters)
c) Strong (more than 10 characters with symbols).

password = input("Enter your password: ")


if len(password) < 6:
print("weak")
elif len(password) <= 10:
print("Medium")
elif len(password) > 10 and not [Link]():
print("Strong")
else:
print("Medium")
PRACTICAL QUESTION :-8

Print Multiplication Table of a Given Number


a) Input: A number n
b) Output: n x 1 = n …….

n = int(input("Enter number:"))
for i in range(1, 11):
print(n, "x", i, "=", n*i)
PRACTICAL QUESTION :-9

Print Even and Odd Numbers between 1 and 100


Output: Two lists, one for even numbers, one for odd

even = []
odd = []

for i in range(1, 101):


if i % 2 == 0:
[Link](i)
else:
[Link](i)
print("Even:", even)
print("Odd:",odd)
PRACTICAL QUESTION :-10

Count Vowels in a String Input: A string Output: Number of vowels

s = input("Enter a string: ")


count = 0

for ch in [Link]():
if ch in "aeiou" :
count += 1

print("vowels:", count)
PRACTICAL QUESTION :-11

Write a program to reverse a string

text = input("Enter a string: ")


print("Reversed:", text[::-1])
PRACTICAL QUESTION :-12

Accept a string and check if it is a palindrome (e.g., "madam").

text = input("Enter a string: ")

if text == text[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
PRACTICAL QUESTION :-13

Write a program to search for an element in a list.

lst = [1, 2, 3, 4, 5]
x = int(input("Enter number to search: "))

if x in lst:
print("Found")
else:
print("Not found")
PRACTICAL QUESTION :-14

Write a program to find the sum and average of elements in a list.

lst = [50, 70, 30, 40]

total = sum(lst)
avg = total / len(lst)

print("Sum:", total)
print("Average:", avg)
PRACTICAL QUESTION :-15

Write a program to demonstrate functions with and without return values.

def greet():
print("Prince")

def add(a, b):


return a + b

greet()
print(add(15,80))
PRACTICAL QUESTION :-16

Write a program to demonstrate variable-length arguments using


*args.

def add_numbers(*args):
total = 0
for num in args:
total +=num
return total

print("sum of 2 numbers:",add_numbers(5,10))
print("sum of 3 numbers:",add_numbers(5,6,7))
print("sum of 5 numbers:",add_numbers(49,89,90,60))
PRACTICAL QUESTION :-17

Write a program to demonstrate global and local variables.

x = 10

def show():
x=5
print("Local x:", x)

show()
print("Global x:", x)
PRACTICAL QUESTION :-18

Write a program to handle division by zero using exception handling.

try:
a = int(input("Enter number: "))
b = int(input("Enter divisor: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
PRACTICAL QUESTION :-19

Write a program to handle multiple exceptions using try-except.

try:
a = int(input("Enter number: "))
b = int(input("Enter divisor: "))
print(a / b)
except ZeroDivisionError:
print("Division by zero error")
except ValueError:
print("Invalid input! Enter numbers only")
PRACTICAL QUESTION :-20

Write a program demonstrating the use of finally block.

try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed (finally block runs always)")
PRACTICAL QUESTION :-21

Write a program using constructor ( init ) to initialize object values.

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

def display(self):
print("Name:", [Link])
print("Marks:", [Link])

s1 = Student("Prince", 85)
[Link]()
PRACTICAL QUESTION :-22

Write a program to demonstrate inheritance in Python.

class Parent:
def show(self):
print("This is parent class")

class Child(Parent):
def display(self):
print("This is child class")

c = Child()
[Link]()
[Link]()
PRACTICAL QUESTION :-23

Write a program to create and display 1D and 2D arrays using NumPy.

import numpy as np

arr1 = [Link]([10, 20, 30, 40, 50])


print("1D Array:")
print(arr1)

arr2 = [Link]([[1, 2, 3],


[4, 5, 6]])
print("\n2D Array:")
print(arr2)
PRACTICAL QUESTION :-24

Write a program to perform basic operations (addition, multiplication) on


arrays.

import numpy as np

arr1 = [Link]([1, 2, 3])


arr2 = [Link]([4, 5, 6])

addition = arr1 + arr2


print("Addition of arrays:", addition)

multiplication = arr1 * arr2


print("Multiplication of arrays:", multiplication)
PRACTICAL QUESTION :-25

Write a program to create a DataFrame and Series from a dictionary.

import pandas as pd
data = {
'Name': ['vaishnavi', 'riya', 'sneha'],
'Age': [19, 20, 18],
'City': ['Delhi', 'Mumbai', 'Chennai']
}
df =
[Link](data)
print("DataFrame:")

series_data = {'a': 10, 'b': 20, 'c': 30}


series = [Link](series_data)
print("\nSeries:")
print(series)
PRACTICAL QUESTION :-26

Write a program to read data from a CSV file using pandas.

import pandas as pd

names =["vaishnavi","sahil","surbhi","mayank","sofee"]
ages=[19,20,18,17,22]
marks=[85,78,89,90,75]

data={"Name":names,"Age":ages,"Marks":marks}

df=[Link](data)
df.to_csv("[Link]",index=False)

df2=pd.read_csv("[Link]")
print([Link]())
print([Link])

You might also like