我已经设法在Python3中创建了一个无限while循环

我已经设法在Python3中创建了一个无限while循环,python,Python,我已经成功地在python上创建了一个无限while循环(它不断重复显示高分),但我在纠正它时遇到了困难,有什么想法吗 我在高分位后添加了一个中断,这停止了无限循环,但程序会要求用户在输入选择后按退出按钮,即使他们没有按0 #high scores #demonstrates list methods scores = [] choice = None while choice != "0": print( """ High Scores 0 - Exit 1 - Sho

我已经成功地在python上创建了一个无限while循环(它不断重复显示高分),但我在纠正它时遇到了困难,有什么想法吗

我在高分位后添加了一个中断,这停止了无限循环,但程序会要求用户在输入选择后按退出按钮,即使他们没有按0

#high scores
#demonstrates list methods

scores = []

choice = None

while choice != "0":
    print(
    """
High Scores

0 - Exit
1 - Show Scores
2 - Add a Score
3 - Delete a Score
4 - Sort Scores
"""
)

choice = input("Choice: ")
print()

#exit
if choice == "0":
    print("Goodbye")

#list high scores table
elif choice == "1":
    print("High Scores")
    for score in scores:
        print(score)

#add a score
elif choice == "2":
    score = int(input("What score did you get?: "))
    scores.append(score)

#remove a score
elif choice == "3":
    score = int(input("Remove which score?: "))
    if score in scores:
        scores.remove(score)
    else:
        print(score, "isn't in the high score list.")

#sort scores
elif choice == "4":
    scores.sort(reverse=True)

#some unknown choice
else:
    print("Sorry, but", choice, "isn't a valid choice.")


input("\nPress the enter key to exit.")

谢谢。

您只缩进了
打印
,因此剩余的行不是while块的一部分

如果这是Python 2.x,请使用
原始输入
输入
给您一个整数,它不等于字符串
“0”
,而且
输入
是有害的,因为它是一个安全问题

还有缩进。

input()函数会自动将其结果转换为整数(因为它正在调用eval),因此您可能希望与0而不是“0”进行比较:

但更明智的选择是使用原始输入:

choice = raw_input("Choice: ")

if choice == "0":
  print("bye")

请参见

,您也可以尝试以下方法:

choice = input(int("Choice: "))
这将使选择成为一个整数类型,并有助于防止不同类型的混合,如果编译器正在查找一个类型但得到另一个类型,则会抛出错误

例如,对于我给出的代码,我可以选择2,它将是整数类型。或者用你的,我可以给2,它可能是字符串类型


我对这个有点生疏,所以我说的话可能根本不重要。只是把它扔出去

纠正你的刻痕!使用以下命令逐步完成代码。它将诊断与此类似的一切。这是针对Python3的,抱歉,我没有说得很清楚标题是Python3,这很好,因为我们不希望在Python2中使用
eval
input
。抱歉,我忽略了这一点。
choice = input(int("Choice: "))