【发布时间】:2018-07-24 15:54:39
【问题描述】:
下面代码的快速sn-p。我试着弄乱another answer posted on here,但它似乎根本不起作用。我不确定我做错了什么。在 Xubuntu 18.04 LTS 上使用 Python 3。代码如下:
while True:
try:
print("Your room is DARK, yet a light flashes red. What do you do?")
print("")
print("1. Look around.")
print("2. There's a lamp somewhere...")
print("3. Go back to bed.")
print("")
ans = int(input(">>> "))
if ans == 1:
print("")
print("Too dark to see... better find a light...")
time.sleep(2)
if ans == 2:
print("")
print("Fumbling, you turn on your nightstand lamp...")
break
if ans == 3:
print("")
print("You sleep away the troubles... but you can't stay asleep...")
time.sleep(1)
print("")
print("Back to the world of the living...")
if ans == str('q'):
sys.exit(0)
except ValueError:
print("")
所以,当用户输入“q”时,我希望程序关闭。我似乎根本做不到。
【问题讨论】:
-
ans = int(input(">>> "))- 这是试图将其转换为整数。因此你永远不会得到ans == str('q')(另请注意str('q') == 'q'...) -
为什么要转换成整数?将其保留为字符串并与“1”、“2”、“3”和“q”进行比较。
-
我不得不承认我觉得自己像个彻头彻尾的白痴。我不知道为什么要将所有内容都转换为整数。将其作为字符串要简单得多。
标签: python string python-3.x ubuntu integer