Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not. We can accomplish these by: (a) writing a user defined function (b) using the built-in function
Question
Write a program to input names of $n$ students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not.
We can accomplish these by:
(a) writing a user defined function
(b) using the built-in function
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Below is a Python program that performs the required tasks. Both approaches (using a user-defined function and using a built-in function) are provided.
Using a User-Defined Function
def check_student_in_tuple(students_tuple, student_name):
"""Function to check if a student is in the tuple."""
return student_name in students_tuple
# Input the number of students
n = int(input("Enter the number of students: "))
students = []
# Input the names of the students
for i in range(n):
name = input("Enter the name of student {}: ".format(i+1))
students.append(name)
# Convert the list to a tuple
students_tuple = tuple(students)
# Input the name to be searched
search_name = input("Enter the name you want to search: ")
# Check if the student is present
if check_student_in_tuple(students_tuple, search_name):
print(f"{search_name} is present in the tuple.")
else:
print(f"{search_name} is not present in the tuple.")
Using Built-in Function
# Input the number of students
n = int(input("Enter the number of students: "))
students = []
# Input the names of the students
for i in range(n):
name = input("Enter the name of student {}: ".format(i+1))
students.append(name)
# Convert the list to a tuple
students_tuple = tuple(students)
# Input the name to be searched
search_name = input("Enter the name you want to search: ")
# Check if the student is present using the 'in' operator
if search_name in students_tuple:
print(f"{search_name} is present in the tuple.")
else:
print(f"{search_name} is not present in the tuple.")
Both methods will:
Ask for the number of students.
Collect the names of the students and store them in a tuple.
Take a name input from the user and check if the name exists in the tuple.
Print whether the name is found in the tuple or not.
In the first method, a user-defined function check_student_in_tuple
is used to check the presence of the student's name. In the second method, the in-built in
operator is directly utilized to perform the check.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month