栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python如何接受用户输入,并验证?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python如何接受用户输入,并验证?

完成此操作的最简单方法是将

input
方法置于
while
循环中。
continue
当输入错误时使用,
break
当你感到满意时使用。

当你的输入可能引发异常时

使用

try
except
检测用户何时输入了无法解析的数据。

while True:    try:        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input        age = int(input("Please enter your age: "))    except ValueError:        print("Sorry, I didn't understand that.")        #better try again... Return to the start of the loop        continue    else:        #age was successfully parsed!        #we're ready to exit the loop.        breakif age >= 18:    print("You are able to vote in the United States!")else:    print("You are not able to vote in the United States.")

实施你自己的验证规则

如果要拒绝Python可以成功解析的值,则可以添加自己的验证逻辑。

while True:    data = input("Please enter a loud message (must be all caps): ")    if not data.isupper():        print("Sorry, your response was not loud enough.")        continue    else:        #we're happy with the value given.        #we're ready to exit the loop.        breakwhile True:    data = input("Pick an answer from A to D:")    if data.lower() not in ('a', 'b', 'c', 'd'):        print("Not an appropriate choice.")    else:        break

结合异常处理和自定义验证

以上两种技术都可以组合成一个循环。

while True:    try:        age = int(input("Please enter your age: "))    except ValueError:        print("Sorry, I didn't understand that.")        continue    if age < 0:        print("Sorry, your response must not be negative.")        continue    else:        #age was successfully parsed, and we're happy with its value.        #we're ready to exit the loop.        breakif age >= 18:    print("You are able to vote in the United States!")else:    print("You are not able to vote in the United States.")

将其全部封装在一个函数中

如果你需要询问用户许多不同的值,则将此代码放在函数中可能很有用,因此你不必每次都重新键入。

def get_non_negative_int(prompt):    while True:        try: value = int(input(prompt))        except ValueError: print("Sorry, I didn't understand that.") continue        if value < 0: print("Sorry, your response must not be negative.") continue        else: break    return valueage = get_non_negative_int("Please enter your age: ")kids = get_non_negative_int("Please enter the number of children you have: ")salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

放在一起

你可以扩展此思想,以创建非常通用的输入函数:

def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):    if min_ is not None and max_ is not None and max_ < min_:        raise ValueError("min_ must be less than or equal to max_.")    while True:        ui = input(prompt)        if type_ is not None: try:     ui = type_(ui) except ValueError:     print("Input type must be {0}.".format(type_.__name__))     continue        if max_ is not None and ui > max_: print("Input must be less than or equal to {0}.".format(max_))        elif min_ is not None and ui < min_: print("Input must be greater than or equal to {0}.".format(min_))        elif range_ is not None and ui not in range_: if isinstance(range_, range):     template = "Input must be between {0.start} and {0.stop}."     print(template.format(range_)) else:     template = "Input must be {0}."     if len(range_) == 1:         print(template.format(*range_))     else:         print(template.format(" or ".join((", ".join(map(str,   range_[:-1])),str(range_[-1])))))        else: return ui

用法如下:

age = sanitised_input("Enter your age: ", int, 1, 101)answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/365330.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号