如何在代码结束后循环此代码,以及如何使代码的Y/N部分正常工作?

2024-04-26 05:31:51 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我需要的是让我的代码在玩家获胜并被问到是否想继续后从顶部再次运行。 我还需要关于如何做到这一点的帮助。我想让代码在选择“是”时重新开始,如果选择“否”则停止

from random import *

a = randint(0,20)
user_input = ""
user_input2 = ""
while True:
   if a != user_input:
       user_input = int(input("Pick a number or die: \n"))
   print(user_input, a)
   if user_input < a:
       print("Aim higher")
   elif user_input > a:
       print("Bit lower mate")
   else:
       break

while True:
   if a == user_input:
       user_input2 = raw_input("Up for another try:(Y/N)?")
   if user_input2.lower() == 'N' or 'n':
       break
       print("Lets see if you re so lucky again.")
   if user_input2.lower() == 'Y' or 'y':
       pass
       print("No shame in being a coward")
   else:
       print("That is wrong")
       break





1条回答
网友
1楼 · 发布于 2024-04-26 05:31:51

正如您现在的代码一样,它循环通过第一部分(游戏),然后分别循环通过第二部分(提示)。所以当你答应再玩一次时,它只会不断地问你是否想再玩一次

您需要将第一个循环放在主循环中,并在第二个循环中去掉else语句。希望这些评论有意义

在中断之前,您应该有任何print语句,否则代码将永远无法到达该点。(例如,在这个if语句之后user_input2.lower() == 'N' or 'n':

我认为您也混淆了是和否提示。再玩一次是的,他们会再玩一次

from random import *

a = randint(0,20)
user_input = ""
user_input2 = ""
while True:     #Loop for prompt and game
    user_input = ""     #Gets reset each time
    while True:     #Loop for just game
        if a != user_input:
            user_input = int(input("Pick a number or die: \n"))
        print(user_input, a)
        if user_input < a:
            print("Aim higher")
        elif user_input > a:
            print("Bit lower mate")
        else:
            break

    if a == user_input:
        user_input2 = raw_input("Up for another try:(Y/N)?")
    if user_input2.lower() == 'N' or 'n':
        print("No shame in being a coward")     #Quit game
        break
    if user_input2.lower() == 'Y' or 'y':
        print("Lets see if you re so lucky again.")     #Play again
        pass
    else:
        print("That is wrong")      #Bad or no input
        break

相关问题 更多 >