<p>您遇到的问题是,在调用<code>ens1()</code>之后,执行不会从头开始,即,如果用户按<code>'s'</code>,则</p>
<pre><code>if ens == "s": # s stands for scores
#code here
ens1() # <=== after this call...
# <============ code continues here (not at the top)
</code></pre>
<p>使用全局变量作为状态(即当前用户选择)被认为是不好的。这也是不必要的-只需让函数返回用户选择:</p>
<pre><code>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
</code></pre>
<p>然后在while循环中使用函数的结果:</p>
<pre><code>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)
</code></pre>
<p><em>更新:</em><code>ens = ""</code>(空字符串)不起作用,因为</p>
<pre><code>"" in 'ensfq'
</code></pre>
<p>一切都是真的。将其更改为<code>ens = " "</code>(即单个空格)使其工作。你知道吗</p>