简体   繁体   中英

Allowing only a maximum integer input and no alphabets in python

I am new in python and I am supposed to create a game where the input can only be in range of 1 and 3. (player 1, 2 , 3) and the output should be error if user input more than 3 or error if it is in string.

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 +"?")

I was doing it like this but the problem is that it seems like there is a problem with my code. if the input is 1, it still says "error please try again" im so confused!

raw_input returns a string. Thus, you're trying to do "1" > 4 . You need to convert it to an integer by using int

If you want to catch whether the input is a number, do:

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

Just note that now it's an integer, your concatenation below will fail. Here, you should use .format()

 print "player 0 has chosen player {}!".format(ChoosePlayer)

You probably need to convert ChoosePlayer to an int, like:

ChoosePlayerInt = int(ChoosePlayer)

Otherwise, at least with pypy 1.9, ChoosePlayer comes back as a unicode object.

You have to cast your value to int using method 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 +"?")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM