<p>因此,评论也这么说,但以下是完整的解释:</p>
<ol>
<li><p>要求用户输入年龄。无论您输入什么年龄,它都符合三个条件之一,因此输入的任何年龄都不会触发“else”条件</p></li>
<li><p>触发else的唯一方法是输入非整数,如单词或字母,但行<code>message = int(input (prompt))</code>尝试将输入转换为整数,因此输入任何其他内容都将引发异常</p></li>
<li><p>您可以使用异常处理程序或通过实现执行退出响应的特定整数(如零)来解决此问题</p></li>
</ol>
<p>下面是一个带有异常处理程序的示例:</p>
<pre><code>prompt = "\nI will price your ticket. What is your age?"
active = True
#Per Matthes, using the flag Active, a program "should run while
#the flag is set to True and stop running when any of several events sets the
#value of the flag to False."
while active:
message = input (prompt)
try:
message = int(message)
if message < int(3):
print("Your ticket is free!")
elif int(3) <= message <= int(12):
print("Your ticket is $10!")
elif message > int(12):
print("Your ticket is $15!")
except:
active = False
print("\nGoodbye!")
</code></pre>
<p>这里有一个输入零将触发退出:</p>
<pre><code>prompt = "\nI will price your ticket. What is your age?"
active = True
#Per Matthes, using the flag Active, a program "should run while
#the flag is set to True and stop running when any of several events sets the
#value of the flag to False."
while active:
message = int(input (prompt))
if int(1) <= message < int(3):
print("Your ticket is free!")
elif int(3) <= message <= int(12):
print("Your ticket is $10!")
elif message > int(12):
print("Your ticket is $15!")
else:
active = False
print("\nGoodbye!")
</code></pre>