Python Assignment 1,2,3,4,5,6,7,8
Python Assignment 1,2,3,4,5,6,7,8
Lab Assignment
Bachelor of Computer Application
Submitted By
Submitted to
Dr. Hemant Petwal
ASSIGNMENT-1
Downloading and Installing Python:
Submitted to
Dr. Hemant Petwal
ASSIGNMENT-2
Q1. Write Python programs to print strings in the given manner:
a) Hello Everyone!!!
b) Hello world
c) Hello world
d) Sujal’s date of birth is
07\02\2005CODE:
print("Hello
Everyone!!!")print("Hello
World") print("hello
world")
print("Sujal's date of birth is 12\\08\
\2005”)INPUT:
OUTPUT:
OUTPUT:
Q3.Take different data types and print values using print function
CODE:
a=int(input("Integer:")
)
b=float(input("Float:")
)c=a+b
print(C)
INPUT:
OUTPUT:
Q4.Take two variable a and b. Assign your r] and la] name. Print your
name a er adding your r] and la] name together.
CODE:
a=input("First
name:") b=input("Last
name:")print(a+" “+b)
INPUT:
OUTPUT:
OUTPUT:
INPUT:
OUTPUT:
PYTHON PROGRAMMING
Lab Assignment
Bachelor of Computer Application
Submitted By
Submitted to
Dr. Hemant Petwal
ASSIGNMENT-3
Use of input statements, operators
Q1. Declare these variables (x, y and z) as integers. Assign a value of 9 to x. Assign a
value of 7 to y, perform addition, multiplication, division, and subtraction onthese two
variables and print out the result.
CODE:
x=9 y=7
z=x+y
print(z)
z=x*y
print(z)
z=x/y
print(z)
INPUT: OUTPU
T:
Q2. Write a Program where the radius is taken as input to compute the area of a
circle.
CODE:
r=int(input("ENTER THE RADIUS: "))
area = print(3.14*r*r)
INPUT: OUTPU
T:
CODE:
x1=int(input("x1: "))
x2=int(input("x2: "))
y1=int(input("y1: "))
y2=int(input("y2: "))
z1=x1+y1 z2=x2+y2
A=z1*z2
print (A)
INPUT: OUTPU
T:
Q4. Test data: x = 4, y = 3. Write a Program to perform any operation to get
expected output: 49.
CODE:
x1=int(4)
x2=int(4)
y1=int(3)
y2=int(3)
z1=x1+y1
z2=x2+y2
A=z1*z2
print(A)
INPUT: OUTPU
T:
INPUT: OUTPU
T:
Q6. Write a program to find area of triangle when length of sides are given.
CODE:
b=int(input("Base: "))
h=int(input("Height: "))
area=print((b*h)/2)
INPUT: OUTPU
T:
INPUT: OUTPU
T:
Q8. Write a program to swap two numbers without taking additional variable.
CODE:
a=int(input("A: "))
b=int(input("B: "))
a,b=b,a
print(f"A={a}")
print(f”B={b}")
INPUT: OUTPU
T:
INPUT: OUTPU
T:
Q10. Write a program to check whether a number is perfect square or not?
CODE:
number = int(input("Enter a number: "))
is_perfect_square = number**0.5 == int(number**0.5)if
is_perfect_square:
print(f"{number} is a perfect square.")
else:
print(f"{number} is not a perfect square.”)
INPUT: OUTPU
T:
CODE:
INPUT: OUTPU
T:
CODE:
Q13. Write a program to compute the length of the hypotenuse (c) of a right triangle
using Pythagoras theorem.
CODE:
a = float(input("Enter the length of side a: ")) b
= float(input("Enter the length of side b: "))c =
(a**2 + b**2)**0.5
print(f"The length of the hypotenuse is: {c}")
INPUT: OUTPU
T:
Q14. Write a program to print sum of even and odd numbers among n natural numbers
CODE:
INPUT: OUTPU
T:
PYTHON PROGRAMMING
Lab Assignment
Bachelor of Computer Application
Submitted By
Submitted to
Dr. Hemant Petwal
ASSIGNMENT-4
Q1: Read an integer from keyboard using input and display it using print.
Input: 10 Output: 10
INPUT:
OUTPUT:
Q2: Read a float type number from a keyboard using input and display it using print.
Truncate the number to two decimal places.
Input: 10.5 Output: 10.50
INPUT:
OUTPUT:
Q3: Any variable in Python has to have a name to identify its presence in
theprogram. The
name assigned to that variable will become a "identifier". The identifier's name can
start
with the alphabets A to Z or a to z or an underscore (_). Also, numerals (0 to 9) can
be
present in the variable name. And, the special symbols such as: !, #,@,%,$ cannot
beused
in the identifiers. Write a program to assign different combinations of identifiers
tothe
variables and display the output of the values stored in identifiers and their type.
Sample Input :
integer = 10
decimal = 10.11
num_ber = -5
INPUT:
OUTPUT:
Q4: Take input of a string “UPES University” and print 1st, fourth and last
characterof the string
Sample Input: Output: U S
YUPES University
INPUT:
OUTPUT:
Q5: Write a program to accept your personal details such as name and age and print
iton the screen
using the formatter and the
placeholder.Sample Input:
Rahu
l18
INPUT:
OUTPUT:
Q6: Write a program to accept string as input and print it on the screen
usingformatter and
placeholder
.INPUT:
OUTPUT:
Q7: Mohit is a very cunning child, when his brother was away from his laptop,
hechanged his
original program to the following:
x =
input()y =
input() if
x>y:
output("x is greater than
y")else:
print("y is greater than x")
This program does not throw an error when it is run, rather it throws an error during
runtime. These
kinds of errors are known as runtime errors.
If we give x=1, y=2, the program runs fine, but when we give x=2 and y=1,
theprogram will throw an
error.
Correct this code so that it is error
free.INPUT :2,1
OUTPUT : x is greater than y
INPUT:
OUTPUT:
Q8. Below is Smart meter Prototype, write a program to implement this meter
through python
programming.
Ex:
Input:
Login: Alok
Meter No: 1234
Alok, kindly find your receipt
below.Output:
Dear Mr. Alok, Kindly proceed to generate your meter receipt.
Input:
Current Bill =User Input (Say 500)
Electricity bill you paid (a/b)= User
INPUT:
OUTPUT:
PYTHON PROGRAMMING
Lab Assignment
Bachelor of Computer Application
Submitted By
Submitted to
Dr. Hemant Petwal
ASSIGNMENT-5
1. Write a program to find left shift and right shift values of a given number.
code: output:
code: output:
3. Using membership operator find whether a given character is in a string.
code: output:
code: output:
code: output:
6. Find the greatest among two numbers. If numbers are equal than print “numbers are
equal”.
code: output:
7. Find the greatest among three numbers assuming no two values are same.
code: output:
8. Check whether the quadratic equation has real roots or imaginary roots. Display the
roots.
code: output:
code: output:
10. Print the grade sheet of a student for the given range of cgpa. Scan marks of five subjects
and calculate the percentage.
CGPA=percentage/10
CGPA range:
0 to 3.4 -> F
3.5 to 5.0->C+
5.1 to 6->B
6.1 to 7-> B+
7.1 to 8-> A
8.1 to 9->A+
9.1 to 10-> O (Outstanding)
Sample Grade sheet
Name: Rohit Kumar
Roll Number: R17234512
SAPID: 50005673
Sem: 1
Course: B.Tech. CSE AI & ML
Subject name: Marks
PDS: 70
Python: 80
Chemistry: 90
English: 60
Physics: 50Percentage: 70%
CGPA:7.0
Grade: A
code: output:
PYTHON PROGRAMMING
Lab Assignment
Bachelor of Computer Application
Submitted By
Submitted to
Dr. Hemant Petwal
1. Write a Python program that takes two strings as input and concatenates them
INPUT: OUTPUT:
2. Write a Python program that takes a string as input and prints its reverse.
INPUT: OUTPUT:
3. Write a Python program that takes a string as input and counts the number of
vowels in it.
INPUT: OUTPUT:
4. Write a Python program that checks if a given string is a palindrome (reads the
same backward as forward).
INPUT: OUTPUT:
5. Write a Python program that takes a sentence as input and counts the number of
words in it.
INPUT: OUTPUT:
6. Write a Python program that takes a string as input and prints it in uppercase.
INPUT: OUTPUT:
7. Write a Python program that checks if two given strings are anagrams (contain the
same characters with the same frequency).
INPUT: OUTPUT:
8. Write a Python program to perform basic string compression using the counts of
repeated characters. For example, the string "aabcccccaaa" would become
“a2b1c5a3".
INPUT: OUTPUT:
9. Write a Python program that takes a sentence as input and capitalizes the rst
letter of each word.
INPUT: OUTPUT:
10. Write a Python function that takes a string as input and determines if it has all
fi
unique characters.
INPUT: OUTPUT:
11. Write a Python program that takes a sentence as input and prints the frequency of each
word.
INPUT: OUTPUT:
12. Write a Python function that takes two strings as input and determines if the rst
string is a substring of the second string.
INPUT: OUTPUT:
13. Write a Python program that takes a list of numbers as input and prints their sum.
INPUT: OUTPUT:
14. Write a Python program that takes a list as input and prints its reversed order.
fi
INPUT: OUTPUT:
15. Write a Python function that takes a list as input and returns a new list containing
only the unique elements in the original list.
INPUT: OUTPUT:
16. Write a Python program that takes two lists as input and prints their intersection
(common elements).
INPUT: OUTPUT:
17. Write a Python program that takes a list of numbers as input and prints the
elements from the third to the sixth (inclusive).
INPUT: OUTPUT:
18. Write a Python program that takes two lists as input and uses the extend method
to combine them into a single list.
INPUT: OUTPUT:
19. Write a Python program that takes a list of strings as input and prints the strings at
even indices in reverse order.
INPUT: OUTPUT:
20. Write a Python program that takes a list and a number n as input and repeats the
elements of the list n times.
INPUT: OUTPUT:
21. Write a Python program that takes a list of strings as input and sorts them in
alphabetical order.
INPUT: OUTPUT:
22. Write a Python program that takes a list and an element as input and removes all
occurrences of that element from the list.
INPUT: OUTPUT:
23. Write a Python program that takes a list of numbers as input and uses list
comprehension to create a new list containing the squares of even numbers.
INPUT: OUTPUT:
24. Write a Python function that takes a list of strings as input and uses list
comprehension to count the total number of vowels in all the strings combined.
INPUT: OUTPUT:
25. Write a Python program that takes two sorted lists as input and merges them into
a single sorted list. Avoid using built-in functions or libraries for sorting.
INPUT: OUTPUT:
PYTHON PROGRAMMING
Lab Assignment
Bachelor of Computer Application
Submitted By
Submitted to
Dr. Hemant Petwal
INPUT: OUTPUT:
Question 2: Tuple Manipulation
Write a Python program that does the following:
1. Create a tuple original_tuple with elements (10, 20, 30, 40, 50).
2. Print the length of original_tuple.
3. Print the element at index 3.
4. Print the last element of the tuple.
5. Convert original_tuple to a list new_list.
6. Add a new element 60 to new_list.
7. Convert new_list back to a tuple new_tuple.
8. Print new_tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
Question 5: Tuple Concatenation
1. Create two tuples, tuple1 with elements (1, 2, 3) and tuple2 with elements (4, 5, 6).
2. Concatenate tuple1 and tuple2 into a new tuple result_tuple.
3. Print result_tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
Question 8: Tuple Comprehension
Write a Python program that creates a tuple of squares of numbers:
1. Use tuple comprehension to create a tuple squares_tuple that contains squares of
numbers from 1 to 10.
2. Print squares_tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
Question 12: Reverse a Tuple
1. Create a tuple numbers with elements (1, 2, 3, 4, 5).
2. Write a program to reverse the elements of numbers.
3. Print the reversed tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
fi
Question 15: Check Tuple Membership
1. Create a tuple test_tuple with elements (1, 2, 3, 4, 5).
2. Prompt the user to enter a number.
3. Check if the entered number exists in test_tuple and print an appropriate message.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
ch
Question 18: Tuple Comprehension
1. Use tuple comprehension to create a tuple squares_tuple that contains squares of numbers
from 1 to 10.
2. Print squares_tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
Question 22: Tuple Concatenation and Sorting
1. Create two tuples tuple1 with elements (5, 8, 2) and tuple2 with elements (3, 6, 1).
2. Concatenate tuple1 and tuple2 into a new tuple result_tuple.
3. Sort result_tuple in descending order.
4. Print the sorted result_tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
INPUT: OUTPUT:
fi
Question 25: Tuple Flattening
1. Create a tuple nested_tuple with nested tuples ((1, 2), (3, 4), (5, 6)).2. Write a program to atten
nested_tuple into a single-level tuple.
3. Print the attened tuple.
INPUT: OUTPUT:
INPUT: OUTPUT:
fl
fl
Python Lab Experiment -8
CODE: OUTPUT:
class Cab:
def __init__(self):
self.cars = []
self.details()
def details(self):
count = int(input("How many car details do you
want to enter: "))
for i in range(count):
print("Input the details of car", i + 1)
kms = int(input("Enter the speed of car: "))
carName = input("Enter the car Name: ")
rate = int(input("Enter the Rate of car: "))
self.cars.append({'kms': kms, 'carName':
carName, 'rate': rate})
self.display()
def display(self):
for i, car in enumerate(self.cars):
print(i + 1, "th cab driver is:", car['carName'])
print(i + 1, "th cab payment is:", car['kms'] *
car['rate'])
fi
fi
fi
Q2. Given two user inputs x and n, calculate the value of xn.
For this expression evaluation design a class and an object to call the method
to
implement this.
Sample Input 1
(X, n)= 5, 2
Sample Output 1
25
Sample Input 2
(X, n)= 2, -2
Sample Output 2
0.25
INPUT: OUTPUT:
class Sqare:
def __init__(self,num,powe):
self.number=num
self.power=powe
self.sqare()
def sqare(self):
print(self.number**self.power
)
Q3. De ne a class cars that uses init method to initialize the name, model and speed
of a car.
1. Cars has two methods accelerate() and brakes(), that takes the value speed from
init
method.
2. accelerate() returns the Cars.speed +70 whereas brakes() returns Cars.speed-20.
Sample Input_1
Name: Tata
Model: Punch
Speed: 100
Sample Output_1
When the car accelerates, speed is 170
Car brakes applied; speed is 80
CODE: OUTPUT:
class Car:
def __init__(self):
self.name = 'none'
self.model = 'none'
self.speed = 0
self.initialize()
def initialize(self):
self.name = input("Enter the name: ")
self.model = input("Enter the model: ")
self.speed = int(input("Enter the speed:
"))
def acce
lerate(self):
return self.speed + 70
def brakes(self):
return self.speed – 20
fi
Q4. WAP to create a class UPES with three attributes, namely School name, number
of students
and number of faculties. Add a method in the class to show these attributes. Create
three objects
of this class UPES and show their details.
Database:
School Students Faculty SoCS 1000 150
Media 500 50 Law 450 25
INPUT: OUTPUT:
class Upes:
def __init__(self):
self.SchoolName=[]
self.NoOfStudent=[]
self.NoofFaculti=[]
self.installize()
def installize(self):
count=int(input("how MANY DETAILS YOU
Want to enter"))
for i in range(count):
Name=input("Enter input the name of
school :")
self.SchoolName.append(Name)
Student=int(input("ENter the number of
studentes"))
self.NoOfStudent.append(Student)
Faculti=input("Enter the name of faculty")
self.NoofFaculti.append(Faculti)
self.display()
def display(self):
lis=["school","student","faculty"]
print(lis)
print(self.SchoolName)
print(self.NoOfStudent)
Code:
class UPES:
def __init__(self, school_name, num_students,
num_faculty):
self.school_name = school_name
self.num_students = num_students
self.num_faculty = num_faculty
def display_details(self):
print("School:", self.school_name)
print("Number of Students:",
self.num_students)
print("Number of Faculty:", self.num_faculty)
print()
Q5. We have two circles with given coordinates of their centers C1(x1, y1) and
C2(x2, y2) and
radius R1 and R2. Create a class with a method to check if the given circles
a) Inside the other
b) touch each other
c) Intersect each other
d) Do not overlap
INPUT: OUTPUT:
class Circle:
def __init__(self, x_coord, y_coord, radius):
self.x_coord = x_coord
self.y_coord = y_coord
self.radius = radius
def distance(self, other):
return ((self.x_coord - other.x_coord) ** 2 +
(self.y_coord - other.y_coord) ** 2) ** 0.5
def check_relation(self, other):
dist = self.distance(other)
if dist < abs(self.radius - other.radius):
return "Circle B is inside A"
elif dist == abs(self.radius - other.radius):
return "Circle touch to each other"
elif dist == self.radius + other.radius:
return "Circle touch to each other"
elif dist > self.radius + other.radius:
return "Circle not touch to each other"
else:
return "Circle intersect each other"
Q6. Write a Python code to check a given number is odd or even using class. For this,
design a
class namely “even_odd” and a method “check” and create an object to check the number
using this function.
INPUT: OUTPUT:
class even_odd:
def check(self, num):
if num % 2 == 0:
print("Number is even")
else:
print("Number is odd")
Q7. A person has a list of words, where the words are written in small case letters. He
wants to
convert each word of that list into uppercase letters. Write a python program (a function)
that
converts small case word list to uppercase words list. For Example ['delhi', 'panjab'] will be
input and output will be ['DELHI', ‘PANJAB'].
INPUT: OUTPUT:
class WordConverter:
def __init__(self, word_list):
self.word_list = word_list
self.convert_to_uppercase()
def convert_to_uppercase(self):
uppercase_list = [word.upper() for word
in self.word_list]
print(self.word_list)
print(uppercase_list)
Q8. Counting Upper and Lower case and Space symbols: Design a python module that will
count both upper, lower case symbols, and spaces in a given paragraph or sentences.
Create a
module named case_counting.py which has the funtion string_test for performing the
count.
Create an other program le main.py which import the case_counting module.
Hint: Use Dictionary to store count.
Test Case 1
Input:
Enter any sentence:
Pollution is very high in Delhi-NCR
Output:
Original String: Pollution is very high in Delhi-NCR
No. of Upper case characters: 5
No. of Lower case Characters: 24
No. of spaces: 5
INPUT: OUTPUT:
class CaseCounter:
def __init__(self, sentence):
self.sentence = sentence
self.upper_count = 0
self.lower_count = 0
self.space_count = 0
self.count_characters()
def count_characters(self):
for char in self.sentence:
if char.isupper():
self.upper_count += 1
elif char.islower():
self.lower_count += 1
elif char.isspace():
self.space_count += 1
self.display_counts()
def display_counts(self):
print("Original String:", self.sentence)
print("No. of Upper case characters:", self.upper_count)
print("No. of Lower case Characters:", self.lower_count)
print("No. of spaces:", self.space_count)
fi
Q9. Perfect number
Design and code a function viz., “perfect()” that determines if parameter number is a perfect
number. Use this function in a program that determines and prints all the perfect numbers
between 1 and N in a list.
[An integer number is said to be “perfect number” if its factors, including 1(but not the
number
itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
INPUT: OUTPUT:
def Perfect(n):
if n <= 1:
return False
total_sum = 1
i=2
while i * i <= n:
if n % i == 0:
total_sum += i
if i != n // i:
total_sum += n // i
i += 1
return total_sum == n
print("Below are all perfect numbers")
limit = int(input("Enter the range:"))
for num in range(2, limit + 1):
if Perfect(num):
print(num, "is a perfect number")
Q10. Practice Question: Student Database Management:
Develop a Python program to manage a student database. Implement functionalities to add
new students, display all students' information, search for a student by their ID, and save
the
database to a le named "students.txt".
class Student:
def __init__(self, id, name, age):
self.id = id
self.name = name
self.age = age
def __str__(self):
return f"ID: {self.id}, Name: {self.name}, Age: {self.age}"
def save_students_to_ le(students, lename):
with open( lename, 'w') as le:
for student in students:
le.write(f"{student.id},{student.name},{student.age}\n")
def load_students_from_ le( lename):
students = []
with open( lename, 'r') as le:
for line in le:
data = line.strip().split(',')
student = Student(data[0], data[1], data[2])
students.append(student)
return students
# Usage example:
students = [Student("101", "Alice", 20), Student("102", "Bob", 21)]
save_students_to_ le(students, "students.txt")
loaded_students = load_students_from_ le("students.txt")
for student in loaded_students:
print(student)
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Q11. Practice Question: Employee Directory:
Implement a Python program to maintain an employee directory. Allow users to add new
employees, update employee information, delete employees, display all employees' details,
and save the directory to a le named "employees.txt".
class Employee:
def __init__(self, id, name, position):
self.id = id
self.name = name
self.position = position
def __str__(self):
return f"ID: {self.id}, Name: {self.name}, Position: {self.position}"
def save_employees_to_ le(employees, lename):
with open( lename, 'w') as le:
for emp in employees:
le.write(f"{emp.id},{emp.name},{emp.position}\n")
def load_employees_from_ le( lename):
employees = []
with open( lename, 'r') as le:
for line in le:
data = line.strip().split(',')
emp = Employee(data[0], data[1], data[2])
employees.append(emp)
return employees
# Usage example:
employees = [Employee("001", "Alice", "Manager"), Employee("002", "Bob", "Developer")]
save_employees_to_ le(employees, "employees.txt")
loaded_employees = load_employees_from_ le("employees.txt")
for emp in loaded_employees:
print(emp)
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Q12. Exception Handling:
1) Write a Python program that takes two numbers from the user and divides the rst
number by the second number. Handle the ZeroDivisionError exception if the second
number is zero.
INPUT: OUTPUT:
try:
n1 = oat(input("Enter the rst number: "))
n2 = oat(input("Enter the second number: "))
result = n1 / n2
print("The result is:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
2) Develop a Python program that reads the contents of a le speci ed by the user. Handle
the FileNotFoundError exception if the le does not exist.
INPUT: OUTPUT:
try:
fname = input("Enter the le name: ")
with open(fname, "r") as le:
content = le.read()
print("File content:\n", content)
except FileNotFoundError:
print("Error: The speci ed le does not
exist.")
3) Create a Python program that prompts the user to enter an integer. Handle the ValueError
exception if the input is not an integer.
INPUT: OUTPUT:
try:
user_input = int(input("Enter an integer:
"))
print("You entered:", user_input)
except ValueError:
print("Error: The input is not an integer.")
fl
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
4) Write a Python program that prompts the user to enter the index of a list and then prints
the element at that index. Handle the IndexError exception if the index is out of range.
INPUT: OUTPUT:
my_list = [10, 20, 30, 40, 50]
try:
idx = int(input("Enter the index: "))
print("The element at index", idx, "is:",
my_list[idx])
except IndexError:
print("Error: The index is out of range for the
list.")
5) Develop a Python program that de nes a dictionary and prompts the user to enter a key
to retrieve the corresponding value. Handle the KeyError exception if the key does not exist
in the dictionary.
INPUT: OUTPUT:
my_dict = {"apple": 1, "banana": 2,
"cherry": 3}
try:
key = input("Enter the key: ")
print("The value for the key", key, "is:",
my_dict[key])
except KeyError:
print("Error: The key does not exist in
the
dictionary.")
6) Design a Python program that writes user input to a le named "output.txt". Handle the
IOError exception if there is an error while writing to the le.
INPUT: OUTPUT:
try:
user_input = input("Enter the content to write to
the le: ")
with open("output.txt", "w") as le:
le.write(user_input)
print("The content has been written to the le.")
except IOError:
print("Error: There was a problem writing to the
le.")
fi
fi
fi
fi
fi
fi
fi
fi
7) Create a Python program that prompts the user to enter two numbers and then
concatenates them as strings. Recognize TypeError exception if the inputs are not
convertible to strings.
INPUT: OUTPUT:
try:
n1 = input("Enter the first number: ")
n2 = input("Enter the second number: ")
result = n1 + n2
print("The concatenated result is:",
result)
except TypeError:
print("Error: The input could not be
converted to
strings.")
8) Write a Python program that prompts the user to enter a number between 1 and 10.
Handle the ValueError exception if the input is not within the speci ed range.
INPUT: OUTPUT:
try:
user_input = int(input("Enter a number
between
1 and 10: "))
if 1 <= user_input <= 10:
print("You entered:", user_input)
else:
raise ValueError
except ValueError:
print("Error: The input is not within the
specified
range (1 to 10).")
fi
9) Develop a Python program that performs arithmetic operations based on user input.
Recognize the ArithmeticError exception for invalid operations.
INPUT: OUTPUT:
try:
n1 = float(input("Enter the first number:
"))
n2 = float(input("Enter the second
number: "))
op = input("Enter the operator (+, -, *, /):
")
if op == "+":
result = n1 + n2
elif op == "-":
result = n1 - n2
elif op == "*":
result = n1 * n2
elif op == "/":
result = n1 / n2
else:
raise ArithmeticError
print("The result is:", result)
except ArithmeticError:
print("Error: Invalid operator. Please try
again.")