Python输入函数循环校验求助:如何实现合规前重复请求输入
输入验证循环问题的解决方案
原代码的问题点
- 判断逻辑错误:
str()生成的是空字符串,First_Name != str()实际是检查输入是否为空,而非是否为合法字符串;Age1 != int()是拿变量和int类型对象比较,永远为真,完全起不到验证作用。 - 缺少循环控制:输入不符合条件时,没有重复请求当前项,直接执行下一行输入代码。
- 未处理异常:年龄输入用
int(input())时,若输入非数字会直接抛出ValueError,导致程序崩溃。
推荐实现:通用验证函数+循环
编写一个可复用的输入验证函数,减少重复代码,同时实现循环请求直到输入合法的需求:
def get_valid_input(prompt, validator, error_msg): while True: user_input = input(prompt) if validator(user_input): return user_input print(error_msg) # 验证名字/国家:非空且不全为数字(可按需调整规则) def validate_name(s): return s.strip() != "" and not s.isdigit() # 验证年龄:可转换为正整数 def validate_age(s): try: age = int(s) return age > 0 except ValueError: return False # 逐个获取合法输入 first_name = get_valid_input('First_Name: ', validate_name, 'please input a valid first name') last_name = get_valid_input('Last_Name: ', validate_name, 'please input a valid last name') country = get_valid_input('Country1: ', validate_name, 'please input a valid country name') age = int(get_valid_input('Age1: ', validate_age, 'please input a positive number')) print(first_name, last_name, country, age)
代码说明
get_valid_input:核心循环函数,持续请求输入,直到传入的validator函数返回True,才返回合法输入。validate_name:自定义名字/国家的验证规则,这里设置为输入非空且不全是数字,你可以根据需求修改(比如允许包含字母、空格、连字符等特殊字符)。validate_age:尝试将输入转为整数,同时确保年龄为正数,转换失败或年龄无效时返回False。
简化版(无通用函数)
如果暂时不想封装函数,也可以为每个输入单独写循环逻辑:
# 获取合法名字 while True: first_name = input('First_Name: ') if first_name.strip() != "" and not first_name.isdigit(): break print('please input a valid first name') # 获取合法姓氏 while True: last_name = input('Last_Name: ') if last_name.strip() != "" and not last_name.isdigit(): break print('please input a valid last name') # 获取合法国家名 while True: country = input('Country1: ') if country.strip() != "" and not country.isdigit(): break print('please input a valid country name') # 获取合法年龄 while True: try: age = int(input('Age1: ')) if age > 0: break print('please input a positive number') except ValueError: print('please input a number') print(first_name, last_name, country, age)
两种实现都能保证:只有当前输入项符合要求时,才会执行下一行输入代码。
内容的提问来源于stack exchange,提问作者Ayodele Williams
相关产品推荐
相关产品推荐

