How to handle both integer and string from raw_input?

前端 未结 5 402
一向
一向 2021-01-14 12:56

Still trying to understand python. It is so different than php.

I set the choice to integer, the problem is on my menu I need to use letters as well.

How c

5条回答
  •  無奈伤痛
    2021-01-14 13:41

    I'm not entirely clear what you're asking here. raw_input() always returns a str type. If you want to convert user input automatically to an int or other (simple) type you can use the input() function, which does this.

    You have chosen to let the user enter either a letter or a number, you could equally assign the "letter" options to number in the menu. Or, you could take more advantage of the try/except, e.g.:

    try:
        choice = int(user_input)
        if choice == 1:
            # do something
        elif ...
    except ValueError: # type(user_input) != int
        if choice == 'X' or choice == 'x':
            # do something
        elif ...
        else:
            print 'no idea what you want' # or print menu again
    

提交回复
热议问题