当一个选择被输入时,什么都不会发生

2024-06-16 09:31:03 发布

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

我不知道该如何用语言来表达我的问题。你知道吗

这个代码是我做的骰子游戏的一部分。当游戏开始时,用户有一个多选选项,即:

Please enter 'n' if you are a new user, 'e' if you are an existing user, or 's' to display scores, or 'f' if you forgot your password:

例如,如果用户输入字母n,它会让他们为游戏创建一个新帐户,然后我会调用函数ens1,让他们选择做某事。你知道吗

我遇到的问题是,如果用户在创建帐户后输入n来创建一个新帐户,我调用函数ens1,让他们选择做其他事情,并说他们想通过输入e来启动游戏,什么都不会因为某种原因发生,我也不知道为什么会发生这种情况。你知道吗

def ens1():
    global ens
    print("\n")
    ens = input("Please enter 'n' if you are a new user, 'e' if you are an existing user, or 's' to display scores, or 'f' if you forgot your password: ")
    while ens not in ('e', 'n', 's', 'f'):
        ens = input("Please enter 'n' if you are a new user, 'e' if you are an existing user, or 's' to display scores, or 'f' if you forgot your password: ")


if ens == "f": # f stands for forgotton password
    #code here
    ens1()


if ens == "e": # e stands for existing user
    #code here
    ens1()


if ens == "n": # n stands for new account
    #code here
    ens1()


if ens == "s": # s stands for scores
    #code here
    ens1()

Tags: oryou游戏newforifcodepassword
2条回答

您遇到的问题是,在调用ens1()之后,执行不会从头开始,即,如果用户按's',则

if ens == "s": # s stands for scores
    #code here
    ens1()   # <=== after this call...
    # <============ code continues here (not at the top)

使用全局变量作为状态(即当前用户选择)被认为是不好的。这也是不必要的-只需让函数返回用户选择:

def ens1():
    ens = " "   # don't use global variable (cannot be an empty string ;-)
    prompt = """
      Please enter 

         'n' if you are a new user, 
         'e' if you are an existing user, 
         's' to display scores, 
         'f' if you forgot your password

      or 'q' to quit: """
    while ens not in 'ensfq':
        ens = input(prompt)
    return ens

然后在while循环中使用函数的结果:

while True:
   ens = ens1()
   if ens == 'q':
       break  # exit if the user presses 'q'
   elif ens == "f": # f stands for forgotton password
       print('f chosen')
   elif ens == "e": # e stands for existing user
       print('e chosen')
   elif ens == "n": # n stands for new account
       print('n chosen')
   elif ens == "s": # s stands for scores
       print('s chosen')
   else:
       print('unknown option chosen:', ens)

更新:ens = ""(空字符串)不起作用,因为

"" in 'ensfq'

一切都是真的。将其更改为ens = " "(即单个空格)使其工作。你知道吗

问题是,一旦用户第一次通过en1循环,执行的下一行代码就是新用户的“n”。然后en1将执行以获得用户输入,例如“e”。但是,请记住函数en1是在if(en=="n")范围内调用的。所以程序会因为条件满足而终止。你知道吗

你需要的是一个连续的循环。你知道吗

比约恩的回答是正确的。一旦用户输入“q”,循环将终止

相关问题 更多 >