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

PYTHON

The document contains a series of Python programming exercises covering various topics such as generating personalized greetings, calculating perimeters, managing task lists, performing arithmetic operations, and handling errors. It includes code snippets for each exercise, demonstrating the use of functions, conditionals, loops, and data structures like lists, dictionaries, and NumPy arrays. Additionally, it addresses concepts like set operations, divisibility checks, factorial computation, and statistical calculations.

Uploaded by

hcrack617
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)
4 views

PYTHON

The document contains a series of Python programming exercises covering various topics such as generating personalized greetings, calculating perimeters, managing task lists, performing arithmetic operations, and handling errors. It includes code snippets for each exercise, demonstrating the use of functions, conditionals, loops, and data structures like lists, dictionaries, and NumPy arrays. Additionally, it addresses concepts like set operations, divisibility checks, factorial computation, and statistical calculations.

Uploaded by

hcrack617
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
You are on page 1/ 20

1) Write a python code to generate Personalized Greeting for a student asking his/her name and

branch.

CODE:-

title=input('Enter Your Title (Mr. / Mrs. / Ms./ Prof. /Dr. )')


fname=input('Enter Your First Name')
lname=input('Enter Your Last Name')
print('Welcome ', title,fname,lname, '!')
print('We are glad to be associated with you')
2) Write a python program to calculate perimeter of circle, rectangle and triangle.

CODE:-

def circle_perimeter(radius)

return 2 * math.pi * radius

def rectangle_perimeter(length, width):

return 2 * (length + width)

def triangle_perimeter(side1, side2, side3):

return side1 + side2 + side3

radius = float(input("Enter the radius of the circle: "))

print(f"Perimeter of circle: {circle_perimeter(radius)}")

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

width = float(input("Enter the width of the rectangle: "))

print(f"Perimeter of rectangle: {rectangle_perimeter(length, width)}")

side1 = float(input("Enter the first side of the triangle: "))

side2 = float(input("Enter the second side of the triangle: "))

side3 = float(input("Enter the third side of the triangle: "))

print(f"Perimeter of triangle: {triangle_perimeter(side1, side2, side3)}")


3) Write a Python program to calculate the gross salary of an employee knowing that it is the sum of

basic salary (BS) ,dearness allowance (DA) 80% of BS, the travel allowance (TA) 20% of BS,

and the house rent allowance (HRA) 10% of BS.

CODE:-

basicSal=input("Enter your Basic Salary:")


BS=float(basicSal)
print("Entered Basic Salary is:",BS)
DA=0.8*BS
TA=0.2*BS
HRA=0.1*BS
gross= BS+DA+TA+HRA
print("Computed Dearness Allowance:",DA)
print("Computed Travelling Allowance:",TA)
print("Computed House Rent Allowance:",HRA)
print("Your Gross Salary is:",gross)
4) Write a Python program to explore basic arithmetic operations. The program should prompt the

user to enter two numbers and then perform addition, subtraction, multiplication, division, and

modulus operations on those numbers.

CODE:-

a=int(input('Enter First Number'))


b=int(input('Enter second Number'))
print('The sum is :',a+b)
print('The difference is :',a-b)
print('The product is :',a*b)
print('The division is :',a/b)
print('The Modulus is :',a%b)
5) Develop a Python program to manage a task list using lists including adding and removing tasks.

CODE:-

print('Lets create a task list ')


T1=input('Enter Task 1:')
T2=input('Enter Task 2:')

list= [T1,T2]
print('The Tasks Are:',list)
print('Adding a new task')
T3=input('Enter Task 3:')
list.append(T3)
print('Updated Task List:',list)
print('---------------------------------')

print('Deleting a task')
rem=input('Enter Task to be deleted:')
list.remove(rem)
print('Updated Task List:',list)
6) Develop a Python program to manage a task list using lists including updating and sorting tasks.

CODE:-

print('Lets create a task list ')


T1=input('Enter Task 1:')
T2=input('Enter Task 2:')

list= [T1,T2]
print('The Tasks Are:',list)
print('Sorting Task List')
list.sort()
print('Sorted Task List:',list)
print('---------------------------------')

print('Changing/Updating a task')
no=int(input('Enter the Task number to be updated:'))
newtask=input('Enter the updated value of Task:')
list[no-1]=newtask
print('Updated Task List:',list)
print('---------------------------------')
7) Create a Python code to demonstrate the use of sets and perform set operations (union,
difference)

to manage student enrollments in multiple courses / appearing for multiple entrance exams like

CET, JEE, NEET etc.

CODE:-

set_cet = {112, 114, 116, 118, 115}


print('Student appearing for CET:', set_cet)

set_neet = {113, 114, 117, 119, 115,120,122}


print('Student appearing for NEET:', set_neet)

set_jee = {112,113, 114, 115,116}


print('Student appearing for JEE:', set_jee)
print('----------------------------------------------------------------
')
print('Set of students appearing for CET or Neet or JEE :', set_cet |
set_neet | set_jee)
print('----------------------------------------------------------------
')
print('Set of students appearing for CET BUT NOT NEET :', set_cet -
set_neet)
8) Create a Python code to demonstrate the use of sets and perform set operations ( intersection,

difference) to manage student enrollments in multiple courses / appearing for multiple entrance

exams like CET, JEE, NEET etc.

CODE:-

set_cet = {112, 114, 116, 118, 115}


print('Student appearing for CET:', set_cet)

set_neet = {113, 114, 117, 119, 115,120,122}


print('Student appearing for NEET:', set_neet)

set_jee = {112,113, 114, 115,116}


print('Student appearing for JEE:', set_jee)
print('----------------------------------------------------------------
')
print('Set of students appearing for CET AND Neet AND JEE :', set_cet &
set_neet & set_jee)
print('----------------------------------------------------------------
')
print('Set of students appearing for CET BUT NOT NEET :', set_cet -
set_neet)
9) Write a Python program to create, update, and manipulate a dictionary of student records,

including their grades and attendance.

CODE:-

stu = {101: "Aditi", 102: "Aman", 103: "Vishal"}


stu_marks = {101: 78, 102: 88, 103: 79}
stu_att = {101: 90, 102: 81, 103: 72}

print("Roll No: Name",stu)


print("Roll No: Marks",stu_marks)
print("Roll No: Attendence%",stu_att)

print('Adding Elements to the Dictionary')


rno=int(input('Enter Rno To be added'))
name=input('Enter Student Name:')
marks=int(input('Enter Marks:'))
att=int(input('Enter Attendence:'))
stu[rno]=name
stu_marks[rno]=marks
stu_att[rno]=att
print("Roll No: Name",stu)
print("Roll No: Marks",stu_marks)
print("Roll No: Attendence%",stu_att)

print('Deleting Elements from the Dictionary')


rno1=int(input('Enter Rno To be deleted'))
del stu[rno1]
del stu_marks[rno1]
del stu_att[rno1]
print("Roll No: Name",stu)
print("Roll No: Marks",stu_marks)
print("Roll No: Attendence%",stu_att)
10) Develop a Python program that takes a numerical input and identifies whether it is divisible by 3

or not utilizing conditional statements.

CODE:-

def check_divisibility_by_3(number):

if number % 3 == 0:

return "The number is divisible by 3"

else:

return "The number is not divisible by 3"

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

result = check_divisibility_by_3(input_number)

print(result)

except ValueError:

print("Invalid input. Please enter a numerical value.")


11) Design a Python program to compute the factorial of a given integer N.

CODE:-

num=int(input('Enter a value to compute its factorial: '))


fact = 1
for i in range(1, num+1):
fact = fact * i
print('The factorial of {0} is {1} '.format(num,fact))
12) Using function, write a Python program to analyze the input number is prime or not.

CODE:-

def is_prime(n):
if n < 2:
return False
i = 2
while i*i <= n:
if n % i == 0:
return False
i += 1
return True

num=int(input('Enter a value to find whether it is prime or not: '))


ans= is_prime(num)
if ans==True:
print('The Entered number {} is prime.'.format(num))
else:
print('The Entered number {} is not prime.'.format(num)
13) Implement a simple Python calculator that takes user input and performs basic arithmetic

operations

CODE:-

def add(x, y):


return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y

def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")


if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print("{0} + {1} = {2}".format(num1,num2,add(num1,num2)))
elif choice == '2':
print("{0} - {1} =
{2}".format(num1,num2,subtract(num1,num2)))
elif choice == '3':
print("{0} * {1} =
{2}".format(num1,num2,multiply(num1,num2)))
elif choice == '4':
print("{0} / {1} =
{2}".format(num1,num2,divide(num1,num2)))
else:
print("Invalid input. Please choose a valid operation.")
calculator()
ch=input("Do you want to perform another operation (y/n)")
while (ch=='y') or (ch=='Y') or (ch=='n') or (ch=='N') :
if ((ch=='y') or (ch=='Y')):
calculator()
else:
exit()
ch=input("Do you want to perform another operation (y/n)")
else:
print("Invalid Response!Exiting...!")
14) Write a Python program that takes two numbers as input and performs division and manage
division by zero error.

CODE:-

def divide_numbers():

try:

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

num2 = float(input("Enter the second number: "))

if num2 == 0:

raise ZeroDivisionError("Cannot divide by zero.")

result = num1 / num2

print("Result:", result)

except ValueError:

print("Invalid input. Please enter valid numbers.")

except ZeroDivisionError as e:

print("Error:", e)

except Exception as e:

print("An unexpected error occurred:", str(e))

divide_numbers()
15) Demonstrate classes and objects using a program(using __init__).

CODE:-
16) Write a Python program to create a 1D NumPy array. Perform basic operations like reshaping and

indexing.

CODE:-
import numpy as np #importing numpy
arr_1d = np.array([1, 2, 3, 4, 5])
print("Original 1D Array:", arr_1d)

arr_1d_reshaped = arr_1d.reshape(1, 5)
print("Reshaped 1D Array to 2D:", arr_1d_reshaped)
17) Write a Python program to create a 2D NumPy array. Perform basic operations like reshaping and

indexing.

CODE:-
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Original 2D Array:")
print(arr_2d)

arr_2d_reshaped = arr_2d.reshape(9,) # Flatten it to a 1D


array with 9 elements
print("Reshaped 2D Array to 1D:", arr_2d_reshaped)

print("Element at row 1, column 2:", arr_2d[1, 2])


18) Write a Python program to create a 3D NumPy array. Perform basic operations like reshaping and

indexing.

CODE:-
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7,
8]]]) print("Original 3D Array:") print(arr_3d)

print("Element at index [1, 0, 1]:", arr_3d[1, 0, 1])

arr_3d_reshaped = arr_3d.reshape(2, 4)
print("Reshaped 3D Array to 2D:")
print(arr_3d_reshaped)
19) Develop a Python script to create two arrays of the same shape and perform element-wise

addition.

CODE:-
Array1 = np.array([1,2,3]
[6,5,4])
Array2 = np.array([4,5,6]
[3,2,1])
Print(“Array1:”)
Print(“n\Array2:”)
print("\nElement-wise Addition (Array1 + Array2):")
20) Write a Python program to calculate mean, median and standard deviation for a 1D array.

CODE:-
# Given array (1D array)
array1 = np.array([10, 20, 30, 40, 50])
#
Mean
mean = np.mean(array1)
print(f"Mean: {mean}")

# Median
median = np.median(array1)
print(f"Median: {median}")

# Standard Deviation std_dev =


np.std(array1) print(f"Standard
Deviation: {std_dev}")

You might also like