So, I have a program, which I am finishing but I apparently ran into a problem. In the program I have to make that whenever I enter a 0 in the input, the program will stop and print the results. Here's the program before I continue saying anything else:
import collections
students = collections.defaultdict(list)
while True:
student = input("Enter a name: ").replace(" ","")
if student == "0":
print ("A zero has been entered(0)")
break
if not student.isalpha():
print ("You've entered an invalid name. Try again.")
continue
while True:
grade = input("Enter a grade: ").replace(" ","")
if grade == "0":
print ("A zero has been entered(0)")
break
if not grade.isdigit():
print ("You've entered an invalid name. Try again.")
continue
grade = int(grade)
if 1 <= grade <= 10:
students[student].append(grade)
break
for i, j in students.items():
print ("NAME: ", i)
print ("LIST OF GRADES: ", j)
print ("AVERAGE: ", round(sum(j)/len(j),1))
I figured out a way how to make the program stop and post results after a 0 is entered in the "Enter a name: "
part. This is what is printed out:
Enter a name: Stacy
Enter a grade: 8
Enter a name: 0
A zero has been entered(0)
NAME: Stacy
LIST OF GRADES: [8]
AVERAGE: 8.0
I need to do the same with the "Enter a grade: "
part but if I try to make the program like it is now, this is what it prints out:
Enter a name: Stacy
Enter a grade: 0
A zero has been entered(0)
Enter a name:
How do I make the program show results like it does when a 0 is entered in the name input?
In one of your inputs, check to see if the input is 0. If it is, make a call to sys.exit
. This can be done anywhere, even when checking for the grade. Just make sure that you include both options then (a string 0 and an int 0). Also, the reason for why it was still saying A zero has been entered(0)
is because you are only quitting out of one loop, and then continuing from the beginning basically.
# Be sure to import sys!
random_place = input("Whatever is here ")
if random_place == '0' or random_pace == 0:
sys.exit(0)
Your program will exit then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With