Python如何实现姓名输入仅接受纯字符串格式的校验
问题根源
input() 本身返回值就是字符串类型,nname = str(input()) 只是对本就为字符串的输入做冗余类型转换,完全没有校验内容是否包含数字,因此即使用户输入纯数字,也会被当做合法值传入后续流程。
实现方案
要拦截带数字的姓名输入,必须在输入环节增加循环校验:不满足规则就提示重输,直到输入符合要求才向下执行。
核心校验规则:
- 拦截空输入(用户直接按回车的无效输入)
- 检测输入内容,只要包含任意数字字符就判定为无效
- 可按需扩展规则,比如拦截特殊符号、限制输入长度等
核心校验代码片段:
# 替换原代码中直接写 nname = input().lower() 的部分 while True: input_name = input().strip() if not input_name: print("姓名不能为空,请重新输入:") continue if any(ch.isdigit() for ch in input_name): print("姓名不能包含数字,请重新输入:") continue nname = input_name.lower() break
原代码其他问题修复
你提供的原始代码还有几处会直接导致运行报错的问题,一并修复后的完整可运行代码如下:
print("Good Day Welcome To our Shop.") mnu = ["Milktea","Foods", "Drinks", "Dessert"] # 拆分菜单项的数字序号和内容,避免影响后续商品匹配 lsa = ["Matcha", "Taro", "Winter Melon", "Okinawa", "Chocolate", "Cheese Cake"] fds = {'Chicken'} shot = ["tubig"] mtms = ["ice cream"] laht = [] print("Hi what would you like to be called, So we can inform you if your order is ready") def cstmrinfo(name): print("Okay " + name, "So what would you like to get " ) print(*mnu,sep = "\n") def kuha_order(): while True: order = input().lower() # 统一转小写,省略重复的大小写判断 if order == "milktea": print(lsa) laht.append(order) break elif order == "foods": print(fds) laht.append(order) break elif order == "drinks": print(shot) laht.append(order) break elif order == "dessert": print(mtms) laht.append(order) break else: print("Sorry you input a thing that is not available on our menu, Please Try again:") continue # 增加姓名入参,解决原代码未定义变量的报错 def pnglhtn(customer_name): while True: print("I Would like to get a: ") qwe = input() if qwe in lsa or qwe in fds or qwe in shot or qwe in mtms: print(qwe) else: print("There is no such thing like that ") continue dmi = int(input("How Many Servings Would you Like: ")) laht.append(qwe) laht.append(dmi) print("So " + customer_name, "you Like a " + str(laht[:2])) print(dmi, "Serves of: " + str(qwe)) break # 带校验的姓名输入逻辑 while True: input_name = input().strip() if not input_name: print("姓名不能为空,请重新输入:") continue if any(ch.isdigit() for ch in input_name): print("姓名不能包含数字,请重新输入:") continue nname = input_name.lower() break cstmrinfo(nname) kuha_order() pnglhtn(nname)
扩展:更严格的校验
如果需要更精准的人名校验(比如只允许中文、英文字母和空格,禁止所有特殊符号和数字),可以用正则实现,只需要先导入re模块,把校验条件替换成正则匹配即可:
import re # 校验逻辑替换为: if not re.match(r'^[a-zA-Z\u4e00-\u9fa5\s]+$', input_name): print("姓名只能包含中文、英文字母和空格,请重新输入:") continue
内容的提问来源于stack exchange,提问作者brrtbrrt
相关产品推荐
相关产品推荐

