用户正在编写一个 Python 测验程序,但他遇到了一个问题。在玩家回答每个问题后,程序会询问他们是否要继续玩。如果玩家回答 “ja”(是),则程序会显示一个新的随机问题。如果玩家回答 “nej”(否),则程序应显示玩家的当前分数(按百分比)并终止。然而,用户在实现退出循环并显示分数时遇到了困难。

- 解决方案
以下是一些可能的解决方案:
- 使用
break语句退出循环。break语句用于退出当前循环,无论循环的条件是否为真。在该问题中,可以在玩家回答 “nej” 时使用break语句退出循环。 - 使用
sys.exit()函数退出程序。sys.exit()函数用于退出程序。在该问题中,可以在玩家回答 “nej” 时使用sys.exit()函数退出程序。 - 继续询问玩家是否要继续,直到玩家回答 “nej”。 玩家回答 “ja” 时,程序会继续进行。玩家回答 “nej” 时,程序会显示玩家的当前分数并终止。
以下代码演示了如何使用 break 语句退出循环:
while aqpool[0]:
shuffle (aqpool)
numRight = 0
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
for question, rightAnswer in aqpool:
answer = input(question + " ")
if answer == rightAnswer:
print ("RÄTT SVAR!")
numRight = numRight + 1
else:
print("FEL SVAR! Rätta svaret är: " + rightAnswer + "\n")
playAgain = input("Vill du fortsätta spela? (ja eller nej) ")
if playAgain == "nej" or playAgain == "n":
total = numRight / len(aqpool) * 100
print ("Du hade ", total, "% rätt!")
break # 退出循环
以上代码演示了如何使用 sys.exit() 函数退出程序:
while aqpool[0]:
shuffle (aqpool)
numRight = 0
for question, rightAnswer in aqpool:
answer = input(question + " ")
if answer == rightAnswer:
print ("RÄTT SVAR!")
numRight = numRight + 1
else:
print("FEL SVAR! Rätta svaret är: " + rightAnswer + "\n")
playAgain = input("Vill du fortsätta spela? (ja eller nej) ")
if playAgain == "nej" or playAgain == "n":
total = numRight / len(aqpool) * 100
print ("Du hade ", total, "% rätt!")
sys.exit() # 退出程序
以上代码演示了如何继续询问玩家是否要继续,直到玩家回答 “nej”:
while aqpool[0]:
shuffle (aqpool)
numRight = 0
for question, rightAnswer in aqpool:
answer = input(question + " ")
if answer == rightAnswer:
print ("RÄTT SVAR!")
numRight = numRight + 1
else:
print("FEL SVAR! Rätta svaret är: " + rightAnswer + "\n")
playAgain = input("Vill du fortsätta spela? (ja eller nej) ")
while playAgain != "nej" and playAgain != "n":
playAgain = input("Vill du fortsätta spela? (ja eller nej) ")
if playAgain == "nej" or playAgain == "n":
total = numRight / len(aqpool) * 100
print ("Du hade ", total, "% rätt!")
希望这些解决方案对您有用。
文章讲述了在Python编程中,如何处理用户输入来控制测验程序的循环,包括使用break语句退出当玩家选择退出,以及使用sys.exit()函数结束程序。同时,还介绍了如何在玩家连续回答“nej”时显示当前分数。

402

被折叠的 条评论
为什么被折叠?



