Skip to content
Advertisement

How do I successfully close the While loop in this code? It seems to not recognize my break condition?

The prompt for the problem goes as follows:

Create an interactive student records system.
Prompt the user for a student name.
Then prompt the user for a numeric grade
Repeat this until the user enters ‘done’ in place of a name.
Then print each student and the average of their grades

I have come up with the following code (I’m a beginner guys, sorry if this is obvious)

# I am creating a dictionary so I can store multiple values that are associated with one name
lst = []
dict = {}

while True:
  try:
    name = str(input("Please enter student's name."))
    grade = int(input("Please enter grade student recieved."))
    
    if (name not in list(dict.keys()) and name != "done"):
      lsst = []
      lsst.append(grade)
      dict[name] = lsst
      print(lsst)
      continue

      
    
    elif name in list(dict.keys()):
      lsst.append(grade)
      print(lsst)
      continue
    
    elif name == "done":
      break
  
  except ValueError:
    print("Try Again")
    pass

for i in range(list(dict.keys())):
  print(f"{name}: {grade}")

I am trying to print the averages after I type ‘done’ for the name input, but it just moves on to the next input inquiry. Why is this, and how do I fix it?

Advertisement

Answer

There are many mistakes in the code but I will break them down in my corrected version.

names_and_grades = {} # I renamed this variable because there is a built in type called dict in Python.

while True: # Using while True is usually discouraged but in this case, it's hard to avoid that.
    try:
        name = input("Please enter student's name.") # No need to convert to string as it takes the input as a string by default.

        if name == "done": # After you prompted for a name immediately check whether the user entered done. This way, you can break right after that.
            break

        grade = int(input("Please enter grade student recieved."))

        if name not in names_and_grades.keys():
            names_and_grades[name] = [grade] # We don't actually need a separate list as the entry in the dictionary will be the list itself (that's why it's put between brackets).
        elif name in names_and_grades.keys():
            names_and_grades[name].append(grade) # Once the list was declared, you can simply append it.

        print(names_and_grades[name]) # No need to repeat this twice in the if-else statements, you can just write it after them. And a very important thing, there is no need to use continue, since you are using if-elfe. When you are using if-else, only one of the blocks will be used, the first block where the condition evaluates as true.

    except ValueError:
        print("Try Again")

for k in names_and_grades.keys():
    print(f"{k}: {names_and_grades[k]}") # This is the simplest way to iterate through a dictionary (if you want to format the entries), by iterating through the keys of the dictionary and with the help of the keys, calling the appropriate values.

I hope this helps, let me know if something is unclear.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement