0

我是 python 新手,我应该创建一个游戏,其中输入只能在 1 和 3 的范围内。(玩家 1、2、3)如果用户输入超过 3,则输出应该是错误的,如果它是错误的在字符串中。

def makeTurn(player0):

    ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))

    if ChoosePlayer > 4:
        print "Sorry! Error! Please Try Again!"
        ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))

    if ChoosePlayer.isdigit()== False:
        print "Sorry! Integers Only"
        ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
    else:
        print "player 0 has chosen player " + ChoosePlayer + "!"
        ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")

我是这样做的,但问题是我的代码似乎有问题。如果输入是 1,它仍然说“错误请重试”我很困惑!

4

3 回答 3

1

raw_input返回一个字符串。因此,您正在尝试做"1" > 4. 您需要使用将其转换为整数int

如果要捕获输入是否为数字,请执行以下操作:

while True:
    try:
        ChoosePlayer = int(raw_input(...))
        break
    except ValueError:
        print ("Numbers only please!")

请注意,现在它是一个整数,下面的连接将失败。在这里,您应该使用.format()

 print "player 0 has chosen player {}!".format(ChoosePlayer)
于 2013-07-27T22:43:11.317 回答
1

您可能需要将 ChoosePlayer 转换为 int,例如:

ChoosePlayerInt = int(ChoosePlayer)

否则,至少在 pypy 1.9 中,ChoosePlayer 作为 unicode 对象返回。

于 2013-07-27T22:45:27.630 回答
-1

您必须使用方法将您的值转换为 int int()

 def makeTurn(player0):
    ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))

    if int(ChoosePlayer) not in  [1,2,3]:
        print "Sorry! Error! Please Try Again!"
        ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))

    if ChoosePlayer.isdigit()== False:
        print "Sorry! Integers Only"
        ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
    else:
        print "player 0 has chosen player " + ChoosePlayer + "!"
        ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")
于 2013-07-27T22:44:08.337 回答