如何在 Python 中将用户输入限制为仅整数 [英] How can I limit the user input to only integers in Python

查看:216
本文介绍了如何在 Python 中将用户输入限制为仅整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行多项选择调查,允许用户从选项 1-x 中进行选择.我怎样才能做到,如果用户输入数字以外的任何字符,则返回类似这是一个无效答案"的内容

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, return something like "That's an invalid answer"

def Survey():
    print('1) Blue')
    print('2) Red')
    print('3) Yellow')
    question = int(input('Out of these options\(1,2,3), which is your favourite?'))
    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

推荐答案

你的代码会变成:

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

它的工作方式是创建一个循环,无限循环直到只输入数字.所以说我输入'1',它会破坏循环.但是如果我输入Fooey!"except 语句会捕获 WOULD 已引发的错误,并且它会循环,因为它没有被破坏.

The way this works is it makes a loop that will loop infinitely until only numbers are put in. So say I put '1', it would break the loop. But if I put 'Fooey!' the error that WOULD have been raised gets caught by the except statement, and it loops as it hasn't been broken.

这篇关于如何在 Python 中将用户输入限制为仅整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆