Search code examples
pythondictionaryfor-loopuser-input

How to ask the user which students grade they want to look up. And print that student’s grade from the input listed


The code I wrote is directly below and my question is under it.

student= {}
for i in range(5):
    name = input("Add students name: ")
    grade = input("Add students grade: ")
    student[name] = grade
print(student)

My question would be easier to show you and I would like the output to be what is listed below however I can't seem to get the last two lines.

"Enter a name: Sue

Enter a grade: 90

Enter a name: Bob

Enter a grade: 60

Enter a name: Kim

Enter a grade: 55

Enter a name: Jim

Enter a grade: 100

Enter a name: Sarah

Enter a grade: 95

{'Jim': 100.0, 'Kim ': 55.0, 'Sue': 90.0, 'Sarah': 95.0, 'Bob': 60.0}

Type a name to lookup in the dictionary: Jim

The grade is: 100.0"

If you can help me get what is listed above it would be very helpful. Thanks.


Solution

  • Check the code for this problem below.

    student= {}
    for i in range(3):
        name = input("Add students name: ")
        grade = input("Add students grade: ")
        student[name] = grade
    lookup_name = input("Type a name to lookup in the dictionary: ")
    try:
        lookup_grade = student[lookup_name]
        print(lookup_grade)
    except:
        print('name not in list')
    
    

    Output:

    Add students name: A
    Add students grade: 50
    Add students name: B
    Add students grade: 60
    Add students name: C
    Add students grade: 70
    Type a name to lookup in the dictionary: B
    60
    

    If it helps, please accept the answer.