有人可以解释为什么我不能把我的int放在我的输入中吗?

时间:2017-06-12 10:38:37

标签: python

我想让某人解释为什么输入中的int为字符串' cont'不会工作。这是完整的程序:

import random
ans1=("Go for it!")
ans2=("No way, Jose!")
ans3=("I’m not sure. Ask me again.")
ans4=("Fear of the unknown is what imprisons us.")
ans5=("It would be madness to do that!")
ans6=("Only you can save mankind!")
ans7=("Makes no difference to me, do or don’t - whatever.")
ans8=("Yes, I think on balance that is the right choice.")
print("Welcome to MyMagic8Ball.")
question = input("Ask me for advice then press ENTER to shake me.\n")
print("shaking ...\n" * 4)
cont=input(int("Continue? Yes = 1, No = 0.\n"))
choice=random.randint(1, 8)
while cont != 0:
    if choice==1:
        answer=ans1
    elif choice==2:
        answer=ans2
    elif choice==3:
        answer=ans3
    elif choice==4:
        answer=ans4
    elif choice==5:
        answer=ans5
    elif choice==6:
        answer=ans6
    elif choice==7:
        answer=ans7
    else:
        answer=ans8
print(answer)

3 个答案:

答案 0 :(得分:4)

因为你不能将包含非数字字符的字符串强制转换为int,就这么简单。您目前正在做的是将非整数字符串转换为整数。

input(int("Continue? Yes = 1, No = 0.\n"))

应该是

int(input("Continue? Yes = 1, No = 0.\n"))

请注意,只要一个只包含整数字符的字符串作为输入传递,这就行了,所以要为一些异常处理做好准备。

答案 1 :(得分:3)

@ A.Chandu已经给了你答案,我知道这不是codereview.se,但是我无法帮助自己添加这个:

此代码:

ans1=("Go for it!")
ans2=("No way, Jose!")
ans3=("I’m not sure. Ask me again.")
ans4=("Fear of the unknown is what imprisons us.")
ans5=("It would be madness to do that!")
ans6=("Only you can save mankind!")
ans7=("Makes no difference to me, do or don’t - whatever.")
ans8=("Yes, I think on balance that is the right choice.")

可以写成:

answers = [
    "Go for it!",
    "No way, Jose!",
    "I’m not sure. Ask me again.",
    "Fear of the unknown is what imprisons us.",
    "It would be madness to do that!",
    "Only you can save mankind!",
    "Makes no difference to me, do or don’t - whatever.",
    "Yes, I think on balance that is the right choice.",
]

这样:

if choice==1:
    answer=ans1
elif choice==2:
    answer=ans2
elif choice==3:
    answer=ans3
elif choice==4:
    answer=ans4
elif choice==5:
    answer=ans5
elif choice==6:
    answer=ans6
elif choice==7:
    answer=ans7
else:
    answer=ans8

可以成为:

answer = answers[choice-1]

choice小于1或大于8时,您仍需要以某种方式支持该案例。

另请查看random.choice

答案 2 :(得分:2)

很简单,您正在尝试将字符串更改为Integer。你在输入中调用了一个无效的函数。因为您无法更改包含非数字字符的字符串,因此其无效。

更改

cont=input(int("Continue? Yes = 1, No = 0.\n"))

cont=int(input("Continue? Yes = 1, No = 0.\n"))