困惑为什么此代码无法打印任何内容

时间:2018-07-04 17:34:53

标签: python python-3.x

我在python上制作了一个简单的宠物小精灵游戏,很有趣,这段代码不会显示任何内容

a = int(input("1. Leave for an adventure 2. Ask the professor more questions Type 1 or 2 to answer"))

if a == "1":
 print ("You encounter a pidgey it should be an easy battle but be ready")
if a == "2":
 print ("What are you doing come on go adventure!")

4 个答案:

答案 0 :(得分:2)

由于评论时间太长,我只想说其他答案很好,并着重说明了问题,但我不明白为什么没人建议只删除您的int铸件。

a = input("1. Leave for an adventure 2. Ask the professor more questions Type 1 or 2 to answer")

if a == "1":
    print ("You encounter a pidgey it should be an easy battle but be ready")
if a == "2":
    print ("What are you doing come on go adventure!")
else:
    print ("Value is not 1 or 2")

由于您显然将输入用作开关,因此只需将其作为字符串而不是将其操纵为int并必须处理潜在的ValueError

答案 1 :(得分:1)

Python是强类型的。您无法将int的值与str的值进行比较,并期望它们相等。改为这样做:

a = int(input("1. Leave for an adventure 2. Ask the professor more questions Type 1 or 2 to answer"))

if a == 1:
 print ("You encounter a pidgey it should be an easy battle but be ready")
if a == 2:
 print ("What are you doing come on go adventure!")

答案 2 :(得分:1)

请勿将int与字符串进行比较。并且不要错过使用elif的完美时机:

a = int(input("1. Leave for an adventure 2. Ask the professor more questions Type 1 or 2 to answer"))

if a == 1:
  print("You encounter a pidgey it should be an easy battle but be ready")
elif a == 2:
  print("What are you doing come on go adventure!")

答案 3 :(得分:0)

这是错误的,为什么要使用整数。整数是数字,而不是字符串。您只需要去a = input('...')就可以了!