Ads

AI lab assignment

Q1)

You are tasked with creating a program to manage student grades. 

 Write a Python program to: 

1. Create a dictionary named student grades with student names as keys and their corresponding grades (out of 100) as values.

 2. Calculate and print the average grade of all students. 

3. Identify and print the student with the highest grade. 

4. Allow the user to input a student's name and retrieve their grade. Handle cases where the student's name is not found in the dictionary.

Answer:

# 1. Create a dictionary named student_grades with student names as keys and their corresponding grades as values

student_grades = {

    'John': 85,

    'Emma': 92,

    'Sophia': 78,

    'Michael': 88,

    'Daniel': 95

}


# 2. Calculate and print the average grade of all students

total_grades = 0

for grade in student_grades.values():

    total_grades += grade

average_grade = total_grades / len(student_grades)

print("Average grade of all students:", average_grade)


# 3. Identify and print the student with the highest grade

highest_grade_student = ''

highest_grade = 0

for student, grade in student_grades.items():

    if grade > highest_grade:

        highest_grade = grade

        highest_grade_student = student

print(f"The student with the highest grade is {highest_grade_student} with a grade of {highest_grade}.")


# 4. Allow the user to input a student's name and retrieve their grade

student_name = input("Enter a student's name to retrieve their grade: ")


# Handle cases where the student's name is not found in the dictionary

if student_name in student_grades:

    print(f"{student_name}'s grade: {student_grades[student_name]}")

else:

    print(f"Student {student_name} not found in the dictionary.")


Q2)

1. Define a student database as a list of dictionaries. Each dictionary should represent a student and contain keys such as "name", "age", "grade", and "subjects". Initialize the database with at least three students. Implement the following functionalities: 

1.1. Add a new student to the database. 

1.2. Remove a student from the database. 

1.3. Update a student's information. 

1.4. Display all students' information.

 1.5. Search for a student by name. 

2. Use loops (for/while), conditional statements (if/elif/else), and nested structures as necessary to implement the functionalities.

 3. Ensure user-friendly interactions. Display appropriate messages for each action. 

4. Test your program with various scenarios to ensure it handles different cases correctly.

# Initial student database (list of dictionaries)
student_database = [
    {"name": "John", "age": 20, "grade": "A", "subjects": ["Math", "Science"]},
    {"name": "Jane", "age": 22, "grade": "B", "subjects": ["English", "History"]},
    {"name": "Sam", "age": 19, "grade": "C", "subjects": ["Biology", "Chemistry"]}
]

while True:
    print("\nStudent Database Menu:")
    print("1. Display all students")
    print("2. Add a new student")
    print("3. Remove a student")
    print("4. Update a student's information")
    print("5. Search for a student by name")
    print("6. Exit")

    choice = input("Enter your choice (1-6): ")

    if choice == "1":
        if len(student_database) == 0:
            print("No students found.")
        else:
            for s in student_database:
                print("Name:", s["name"], "Age:", s["age"], "Grade:", s["grade"], "Subjects:", ", ".join(s["subjects"]))

    elif choice == "2":
        name = input("Enter student's name: ")
        age = int(input("Enter student's age: "))
        grade = input("Enter student's grade: ")
        subjects = input("Enter subjects separated by commas: ").split(",")
        student_database.append({
            "name": name,
            "age": age,
            "grade": grade,
            "subjects": [sub.strip() for sub in subjects]
        })
        print("Student added successfully.")

    elif choice == "3":
        name = input("Enter the name of the student to remove: ")
        found = False
        for student in student_database:
            if student["name"].lower() == name.lower():
                student_database.remove(student)
                print("Student removed.")
                found = True
                break
        if not found:
            print("Student not found.")

    elif choice == "4":
        name = input("Enter the name of the student to update: ")
        for student in student_database:
            if student["name"].lower() == name.lower():
                print("1. Update age")
                print("2. Update grade")
                print("3. Update subjects")
                update_choice = input("Enter option number: ")
                if update_choice == "1":
                    student["age"] = int(input("Enter new age: "))
                elif update_choice == "2":
                    student["grade"] = input("Enter new grade: ")
                elif update_choice == "3":
                    new_subjects = input("Enter new subjects (comma separated): ").split(",")
                    student["subjects"] = [s.strip() for s in new_subjects]
                else:
                    print("Invalid choice.")
                print("Student info updated.")
                break
        else:
            print("Student not found.")

    elif choice == "5":
        name = input("Enter the name of the student to search: ")
        found = False
        for student in student_database:
            if student["name"].lower() == name.lower():
                print("Student found:")
                print("Name:", student["name"])
                print("Age:", student["age"])
                print("Grade:", student["grade"])
                print("Subjects:", ", ".join(student["subjects"]))
                found = True
                break
        if not found:
            print("Student not found.")

    elif choice == "6":
        print("Exiting the program. Goodbye!")
        break

    else:
        print("Invalid choice. Please try again.")


Q3)You are building a shopping list application. Write a Python program to:

     a.         Create a list named shopping list containing items to buy at the grocery store.

     b.         Add three more items to the shopping list using the append () method.

     c.         Remove an item from the shopping list using the remove () method.

     d.         Print the final shopping list.


shopping_list = ["flour", "sugar", "oil", "salt", "tea"]


shopping_list.append("coffee")

shopping_list.append("biscuits")

shopping_list.append("jam")

shopping_list.remove("oil") 

print("Final Shopping List:")

for item in shopping_list:

    print("-", item)


Post a Comment

0 Comments