我是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,它仍然显示“错误,请再试一次”我很困惑!
答案 0 :(得分: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)
答案 1 :(得分:1)
您可能需要将ChoosePlayer转换为int,例如:
ChoosePlayerInt = int(ChoosePlayer)
否则,至少在pypy 1.9中,ChoosePlayer会以unicode对象的形式返回。
答案 2 :(得分:-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 +"?")