How can I limit the user input to only integers in Python

前端 未结 4 748
盖世英雄少女心
盖世英雄少女心 2020-11-29 10:37

I\'m trying to make a multiple choice survey that allows the user to pick from options 1-x. How can I make it so that if the user enters any characters besides numbers, retu

4条回答
  •  醉酒成梦
    2020-11-29 11:31

    I would catch first the ValueError (not integer) exception and check if the answer is acceptable (within 1, 2, 3) or raise another ValueError exception

    def survey():
        print('1) Blue')
        print('2) Red')
        print('3) Yellow')
    
        ans = 0
        while not ans:
            try:
                ans = int(input('Out of these options\(1, 2, 3), which is your favourite?'))
                if ans not in (1, 2, 3):
                    raise ValueError
            except ValueError:
                ans = 0
                print("That's not an option!")
    
        if ans == 1:
            print('Nice!')
        elif ans == 2:
            print('Cool')
        elif ans == 3:
            print('Awesome!')
        return None
    

提交回复
热议问题