0% found this document useful (0 votes)
62 views21 pages

Python Programs for Basic Calculations

Uploaded by

Manushree Nayak
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)
62 views21 pages

Python Programs for Basic Calculations

Uploaded by

Manushree Nayak
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

1.

WAP to accept two numbers and operator from the user and create a menu to provide

four functions of a calculator (+, -, *, /).

Code:
while True:

print("Menu:")

print("1. Addition (+)")

print("2. Subtraction (-)")

print("3. Multiplication (*)")

print("4. Division (/)")

print("5. Exit")

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

if choice == '5':

break

if choice not in ('1', '2', '3', '4'):

print("Invalid choice. Please enter a valid option.")

continue

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

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

if choice == '1':

result = num1 + num2

operator = '+'

elif choice == '2':

result = num1 - num2

operator = '-'

elif choice == '3':

result = num1 * num2

operator = '*'

elif choice == '4':

if num2 == 0:

print("Cannot divide by zero")

continue

result = num1 / num2

operator = '/'

print(f"{num1} {operator} {num2} = {result}")


Output:

Menu:

1. Addition (+)

2. Subtraction (-)

3. Multiplication (*)

4. Division (/)

5. Exit

Enter your choice (1/2/3/4/5): 1

Enter the first number: 10

Enter the second number: 5

10.0 + 5.0 = 15.0

2. WAP to find and display the sum of first N even and odd numbers.

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

sum_even = sum(range(2, 2 * n + 1, 2))

sum_odd = sum(range(1, 2 * n, 2))

print(f"Sum of first {n} even numbers: {sum_even}")

print(f"Sum of first {n} odd numbers: {sum_odd}")

Output:

Enter a number (N): 5

Sum of first 5 even numbers: 30

Sum of first 5 odd numbers: 25

3. WAP to accept percentage of a student and display its grade accordingly based on the

table given below:

Percentage Grade

>=90 A

Between 80 and 89 B

Between 70 and 79 C

Between 60 and 69 D

Between 50 and 59 E

Less than 50 F
Code:
Enter marks for Student, Subject 1: 85

Enter marks for Student, Subject 2: 78

Enter marks for Student, Subject 3: 92

Student 1:

Max Marks: 92.0

Min Marks: 78.0

Total Marks: 255.0

Average Marks: 85.0

Output:

Enter the percentage: 85

Grade: B

4. WAP to print all the numbers in the given range divisible by a given number Num.

Code:
start = int(input("Enter the starting number: "))

end = int(input("Enter the ending number: "))

num = int(input("Enter the number for divisibility: "))

for i in range(start, end + 1):

if i % num == 0:

print(i)

Output:
Enter the starting number: 10

Enter the ending number: 30

Enter the number for divisibility: 5

10

15

20

25

30
5. Write a program to find the length of string using for loop.

Code:
text = input("Enter a string: ")

length = 0

for char in text:

length += 1

print("The length of the string is {length}.")

Output:
Enter a string: Hello, World!

The length of the string is 13.

6. Write a program to accept a string from the user and check whether the string is palindrome or
not.

Code:
text = input("Enter a string: ")

if text == text[::-1]:

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

Output:
Enter a string: radar

The string is a palindrome.

7. Write a Menu Driven program to perform the following operations on a list.

Menu.

a) Create a list with any five values

b) Insert an element into a list at a particular position

c) Remove an element from the list based on the user's choice.

d) Print the largest element and smallest element in the list

e) Reverse the elements of a list

Code:
my_list = [] # Initialize an empty list

while True:

print("Menu:")

print("a) Create a list with any five values")

print("b) Insert an element into the list at a particular position")


print("c) Remove an element from the list based on the user's choice")

print("d) Print the largest element and smallest element in the list")

print("e) Reverse the elements of the list")

print("f) Exit")

choice = input("Enter your choice (a/b/c/d/e/f): ")

if choice == 'f':

break

if choice == 'a':

my_list = [int(input("Enter value 1: "), int(input("Enter value 2: "), int(input("Enter value 3: "),

int(input("Enter value 4: "), int(input("Enter value 5: "))]


print(“The list contains:”, mylist)

elif choice == 'b':

value = int(input("Enter the value to insert: ")

position = int(input("Enter the position to insert: ")

my_list.insert(position, value)

elif choice == 'c':

value = int(input("Enter the value to remove: ")

if value in my_list:

my_list.remove(value)

else:

print("Value not found in the list.")

elif choice == 'd':

if len(my_list) > 0:

print(f"Largest element: {max(my_list)}")

print(f"Smallest element: {min(my_list)}")

else:

print("List is empty.")

elif choice == 'e':

my_list.reverse()

print("List reversed.")

else:

print("Invalid choice. Please enter a valid option.")

print("List operations complete.")


Output:

Menu:

a) Create a list with any five values

b) Insert an element into the list at a particular position

c) Remove an element from the list based on the user's choice

d) Print the largest element and smallest element in the list

e) Reverse the elements of the list

f) Exit

Enter your choice (a/b/c/d/e/f): a

Enter value 1: 10

Enter value 2: 20

Enter value 3: 30

Enter value 4: 40

Enter value 5: 50

The list contains: [10, 20, 30, 40, 50]

8. Write a program to input two lists and create a third list that contains the elements from

both the lists and sort it.

Code:
list1 = [3, 1, 2]

list2 = [6, 5, 4]

# Combine and sort the two lists

combined_list = list1 + list2

sorted_list = sorted(combined_list)

print("Combined and sorted list:", sorted_list)

Output:
Combined and sorted list: [1, 2, 3, 4, 5, 6]
9. Accept marks of five students in three subjects into a tuple. For each find the and

display the following

a) Maximum marks out of three subjects

b) Minimum marks out of three subjects

c) Sum and average of the marks in three subjects.


code:
# Accept marks of five students in three subjects into a tuple

marks = []

for i in range(5):

subject1 = float(input(f"Enter marks for Student {i+1}, Subject 1: "))

subject2 = float(input(f"Enter marks for Student {i+1}, Subject 2: "))

subject3 = float(input(f"Enter marks for Student {i+1}, Subject 3: "))

marks.append((subject1, subject2, subject3))

# Find and display maximum, minimum, sum, and average

for i, student_marks in enumerate(marks, 1):

max_marks = max(student_marks)

min_marks = min(student_marks)

total_marks = sum(student_marks)

average_marks = total_marks / 3

print(f"Student {i}:")

print(f"Max Marks: {max_marks}")

print(f"Min Marks: {min_marks}")

print(f"Total Marks: {total_marks}")

print(f"Average Marks: {average_marks}")

Output:
Enter marks for Student 1, Subject 1: 85

Enter marks for Student 1, Subject 2: 78

Enter marks for Student 1, Subject 3: 92

Enter marks for Student 2, Subject 1: 91

Enter marks for Student 2, Subject 2: 88

Enter marks for Student 2, Subject 3: 94

Enter marks for Student 3, Subject 1: 75

Enter marks for Student 3, Subject 2: 82

Enter marks for Student 3, Subject 3: 89


Enter marks for Student 4, Subject 1: 79

Enter marks for Student 4, Subject 2: 68

Enter marks for Student 4, Subject 3: 74

Enter marks for Student 5, Subject 1: 93

Enter marks for Student 5, Subject 2: 85

Enter marks for Student 5, Subject 3: 77

Student 1:

Max Marks: 92.0

Min Marks: 78.0

Total Marks: 255.0

Average Marks: 85.0

Student 2:

Max Marks: 94.0

Min Marks: 88.0

Total Marks: 273.0

Average Marks: 91.0

Student 3:

Max Marks: 89.0

Min Marks: 75.0

Total Marks: 246.0

Average Marks: 82.0

Student 4:

Max Marks: 79.0

Min Marks: 68.0

Total Marks: 221.0

Average Marks: 73.66666666666667

Student 5:

Max Marks: 93.0

Min Marks: 77.0

Total Marks: 255.0

Average Marks: 85.0


10. WAP to create a dictionary of 4 subjects with marks.

student={“Name”:”Amar”, “Age”:16, “Sci":69, "Phy":65, "Chem":68, "CS":67}

Do the following questions

a. Display all the marks in student

b. Add a new value to the dictionary student.(“grade”:’)

c. Change CS marks to 70 .

d. Display each key value pair in different line using for loop.

Code:
# Creating a dictionary for a student

student = {

"Name": "Amar",

"Age": 16,

"Sci": 69,

"Phy": 65,

"Chem": 68,

"CS": 67

# a. Display all the marks in student

print("Marks in student dictionary:")

for subject, marks in student.items():

if subject not in ["Name", "Age"]:

print(f"{subject}: {marks}")

# b. Add a new value to the dictionary student ("grade": "")

student["Grade"] = ''

# c. Change CS marks to 70

student["CS"] = 70

# d. Display each key-value pair in different lines using a for loop

print("\nKey-Value Pairs in student dictionary:")

for key, value in student.items():

print(f"{key}: {value}")
Output:
Marks in student dictionary:

Sci: 69

Phy: 65

Chem: 68

CS: 67

Key-Value Pairs in student dictionary:

Name: Amar

Age: 16

Sci: 69

Phy: 65

Chem: 68

CS: 70

Grade:

11. WAP to calculate the mean, median, mode, standard deviation and variance in Python

using statistics functions.

Code:
import statistics

data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

mean = statistics.mean(data)

median = statistics.median(data)

mode = statistics.mode(data)

stdev = statistics.stdev(data)

variance = statistics.variance(data)

print(f"Mean: {mean}")

print(f"Median: {median}")

print(f"Mode: {mode}")

print(f"Standard Deviation: {stdev}")

print(f"Variance: {variance}")
Output:
Mean: 55.0

Median: 55.0

Mode: 10

Standard Deviation: 29.154759474226502

Variance: 850.0

12. WAP to create 2-D numpy array with 2 rows and 5 columns. Do the following operations

a) Display 1st row values

b) Display 2nd and 3rd column values

c) Display 1st column, 2nd row value

Code:
import numpy as np

# Create a 2-D numpy array with 2 rows and 5 columns

array = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

# a) Display 1st row values

print("1st Row Values:", array[0])

# b) Display 2nd and 3rd column values

print("2nd and 3rd Column Values:")

print(array[:, 1:3])

# c) Display 1st column, 2nd row value

print("Value at 1st column and 2nd row:", array[1, 0])

Output:
1st Row Values: [1 2 3 4 5]

2nd and 3rd Column Values:

[[ 2 3]

[ 7 8]

[12 13]]

Value at 1st column and 2nd row: 6


13. WAP to create a 2D array called ’data’, having 3 rows and 3 columns and store the

following data:

Do the following numpy operations:

a) Addition- Add 10 with all the numbers

b) Subtraction – Subtract 6 from all the numbers

c) Multiplication – Multiply 3 with all the numbers

d) Division – Divide the all elements of data by 2

Code:
import numpy as np

# Create a 2-D numpy array (3x3)

data = np.array([[10, 20, 30],

[40, 50, 60],

[70, 80, 90]])

# a) Addition - Add 10 with all the numbers

data += 10

# b) Subtraction - Subtract 6 from all the numbers

data -= 6

# c) Multiplication - Multiply 3 with all the numbers

data *= 3

# d) Division - Divide all elements of data by 2

data /= 2

print("Updated 2D array:")

print(data)

Output:
Updated 2D array:

[[ 7.5 17.5 27.5]

[37.5 47.5 57.5]

[67.5 77.5 87.5]]


14. WAP create a csv file with the name “Employee.csv”. The Employee.csv file should store

minimum 10 employees with the details Emp name,Emp_job,Emp_age, Emp_Salary.

Do the following :(Using Pandas)

a) Display the first 5 rows of the file Employee

b) Add 5000 with all the employees salary

c) Delete the columns Emp_age and Emp_salary and display the updated file.

Code:
import pandas as pd

# Create a DataFrame with employee details

data = {

'Emp name': ["John", "Alice", "Bob", "Eve", "Mike", "Jenny", "Chris", "Sara", "David", "Emily"],

'Emp_job': ["Manager", "Engineer", "Analyst", "Designer", "Technician", "Manager", "Engineer", "Analyst", "Designer",
"Technician"],

'Emp_age': [35, 28, 32, 24, 29, 34, 27, 31, 26, 30],

'Emp_Salary': [60000, 50000, 55000, 45000, 48000, 62000, 51000, 54000, 47000, 49000]

df = pd.DataFrame(data)

# Save the DataFrame to a CSV file

df.to_csv("Employee.csv", index=False)

# a) Display the first 5 rows of the file Employee

print("First 5 rows of Employee.csv:")

print(df.head())

# b) Add 5000 with all the employees' salary

df['Emp_Salary'] += 5000

# c) Delete the columns Emp_age and Emp_salary and display the updated file

df.drop(['Emp_age', 'Emp_Salary'], axis=1, inplace=True)

print("\nUpdated Employee.csv (after deleting columns Emp_age and Emp_salary):")

print(df)

Output:
First 5 rows of Employee.csv:

Emp name Emp_job Emp_age Emp_Salary

0 John Manager 35 60000

1 Alice Engineer 28 50000

2 Bob Analyst 32 55000


3 Eve Designer 24 45000

4 Mike Technician 29 48000

Updated Employee.csv (after deleting columns Emp_age and Emp_Salary):

Emp name Emp_job

0 John Manager

1 Alice Engineer

2 Bob Analyst

3 Eve Designer

4 Mike Technician

5 Jenny Manager

6 Chris Engineer

7 Sara Analyst

8 David Designer

9 Emily Technician

15. Plot the mean temperature of Jaipur, using a scatter plot.

a) Make sure that the x ticks and y ticks are clearly visible.

b) Give appropriate labels to the x and y axes.

c) Add a title which is bigger than the x and y axis titles.

d) Change the size of the plot.

e) Change the marker shape.

f) Change the marker colour to random colours.

Code:
import matplotlib.pyplot as plt

jaipur_temperatures = [30, 32, 34, 36, 35, 33, 32, 30, 29, 28]

# a) Scatter plot

plt.scatter(range(1, 11), jaipur_temperatures)

# b) Labels for x and y axes

plt.xlabel("Day")

plt.ylabel("Temperature (°C)")

# c) Title

plt.title("Mean Temperature in Jaipur")

# d) Change the size of the plot

plt.figure(figsize=(8, 6))
# e) Change marker shape (for example, use 's' for square markers)

plt.scatter(range(1, 11), jaipur_temperatures, marker='s')

# f) Change marker color (random colors example)

colors = ['red', 'blue', 'green', 'orange', 'purple', 'pink', 'brown', 'gray', 'cyan', 'magenta']

plt.scatter(range(1, 11), jaipur_temperatures, c=colors)

# Show the plot

plt.show()

Output:
16. Create a box plot from the following of data:

b1= [58,68,78,67,58,53,53,90,81,77,63,75,71,42,90].

Code:
import matplotlib.pyplot as plt

b1 = [58, 68, 78, 67, 58, 53, 53, 90, 81, 77, 63, 75, 71, 42, 90]

plt.boxplot(b1)

plt.title("Box Plot of Data")

plt.xlabel("Data")

plt.ylabel("Values")

plt.show()

Output:
17. Marks is a list that stores marks of a student in 10 units tests. Write a program to plot the
students’ performance in these 10-unit tests title and legend [Line graph].

Code:
import matplotlib.pyplot as plt

# Student's marks in 10 unit tests

Marks = [90, 85, 78, 92, 88, 76, 89, 91, 87, 94]

# Create a list of test numbers from 1 to 10 for the x-axis

test_numbers = list(range(1, 11))

# Plot the line graph

plt.plot(test_numbers, Marks, marker='o', label='Student Marks')

plt.title("Student's Performance in 10 Unit Tests")

plt.xlabel("Test Number")

plt.ylabel("Marks")

plt.legend()

plt.grid(True)

# Show the graph

plt.show()

Output:
18. WAP to plot a vertical bar chart from the students data. Give appropriate title, axes

labels, include legend.

Sub=[‘Chemistry’,’Math’,’SST’,’Physics’]

Marks=[66,55,58,59]

Code:
import matplotlib.pyplot as plt

Subjects = ['Chemistry', 'Math', 'SST', 'Physics']

Marks = [66, 55, 58, 59]

# Create a vertical bar chart

plt.bar(Subjects, Marks, color=['blue', 'green', 'red', 'purple'])

plt.title("Student's Marks in Different Subjects")

plt.xlabel("Subjects")

plt.ylabel("Marks")

plt.legend(['Marks'])

plt.show()

Output:
19. Use OpenCV module in the program. Write OpenCV commands for the following:

a) Import a cat image & Viewing it (cat.jpg).

b) Find the minimum and maximum pixel value present in the image.

c) Find the size of an image. Label the image as ‘Cat’.

d) Use the image of cat and extract a square that focuses on the cat’s face

Code:
# Importing a cat image & Viewing it
import cv2

# Load the cat image

image = cv2.imread('cat.jpg')

# Display the image

cv2.imshow('Cat', image)

cv2.waitKey(0)

cv2.destroyAllWindows()
# Find the minimum and maximum pixel value present in the image.
min_pixel_value = image.min()

max_pixel_value = image.max()

print(f"Minimum Pixel Value: {min_pixel_value}")

print(f"Maximum Pixel Value: {max_pixel_value}")

# Find the size of the image and label it as 'Cat':


height, width, channels = image.shape

print(f"Image Size - Height: {height}, Width: {width}")

cv2.imshow('Cat', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

# Extract a square focusing on the cat's face (you'll need to specify the coordinates of the square):

# Define the coordinates of the square (x, y, width, height)


x, y, w, h = 100, 150, 200, 200

cat_face = image[y:y + h, x:x + w]

# Display the extracted cat's face

cv2.imshow('Cat Face', cat_face)

cv2.waitKey(0)

cv2.destroyAllWindows()
Output: (to be done)

20. Use OpenCV module in the program. Write OpenCV commands for the following:

a. Import a flower Image & Viewing it (flower.jpg).

b. Change the image into BGR to RGB.

c. Change the image into grayscale image.

d. Resize the flower image. Set height and width as 150,150.

Code:

# a) Import a flower image and view it:


import cv2

# Load the flower image

image = cv2.imread('flower.jpg')

# Display the image

cv2.imshow('Flower', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

# b) Change the image from BGR to RGB:


image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the RGB image

cv2.imshow('Flower (RGB)', image_rgb)

cv2.waitKey(0)

cv2.destroyAllWindows()

# c) Convert the image to grayscale:


gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Display the grayscale image

cv2.imshow('Flower (Grayscale)', gray_image)

cv2.waitKey(0)

cv2.destroyAllWindows()

#d) Resize the flower image to 150x150:


height, width = 150, 150

resized_image = cv2.resize(image, (width, height))

# Display the resized image

cv2.imshow('Resized Flower', resized_image)

cv2.waitKey(0)

cv2.destroyAllWindows()
Output: (to be done)

You might also like