gpt4 book ai didi

python - 如何通过在输入中输入内容来显示程序的结果?

转载 作者:太空狗 更新时间:2023-10-30 01:33:49 24 4
gpt4 key购买 nike

所以,我有一个程序,我正在完成它,但显然遇到了问题。在程序中,我必须在输入中输入 0 时,程序将停止并打印结果。在我继续说其他任何事情之前,这是程序:

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))

我想出了一种方法如何在 "Enter a name: " 部分输入 0 后让程序停止并发布结果。这是打印出来的:

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

我需要对 "Enter a grade: " 部分做同样的事情,但是如果我试着让程序像现在这样,这就是它打印出来的内容:

Enter a name: Stacy
Enter a grade: 0
A zero has been entered(0)
Enter a name:

如何让程序像在名称输入中输入 0 时那样显示结果?

最佳答案

在您的输入之一中,检查输入是否为 0。如果是,则调用 sys.exit。这可以在任何地方完成,甚至在检查成绩时也是如此。只需确保包含这两个选项(字符串 0 和 int 0)。此外,为什么它仍然说 A zero has been entered(0) 的原因是因为你只是退出一个循环,然后基本上从头继续。

# Be sure to import sys!

random_place = input("Whatever is here ")
if random_place == '0' or random_pace == 0:
sys.exit(0)

然后您的程序将退出。

关于python - 如何通过在输入中输入内容来显示程序的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com