如何用if-else实现输入验证?质数求和程序循环验证故障求助
问题分析与解决
你的核心问题是循环逻辑判断错误:当前代码只要输入不是"y"就直接执行quit()退出程序,完全没处理用户输入无效内容(比如非y/n的字符)的情况,自然达不到输入验证的效果。
修改后的代码
import random # 假设prime_list是你已生成的10000-20000之间的质数列表 prime_list = [10007, 10009, 10037, ...] # 替换为你的实际质数列表 val_1 = random.choice(prime_list) val_2 = random.choice(prime_list) print("This program will find 2 prime numbers in the specified range and sum them") print(val_1, "is the first number and", val_2, "is the second number") print(val_1, "+", val_2, "=", val_1 + val_2) # PLAY AGAIN while True: reset = input("Would you like to generate 2 new numbers? Y/N ").strip().lower() if reset == "y": val_1 = random.choice(prime_list) val_2 = random.choice(prime_list) print(val_1, "is the first number and", val_2, "is the second number") print(val_1, "+", val_2, "=", val_1 + val_2) elif reset == "n": print("Goodbye") break # 用break退出循环比quit()更优雅,避免直接终止整个程序 else: print("Invalid input! Please enter Y or N.")
关键改动说明
- 新增
elif reset == "n"分支:只有输入明确是"n"时才退出程序 - 新增
else分支:输入既不是"y"也不是"n"时,提示用户输入有效内容,循环自动回到开头重新提问 - 给
input()加上.strip():去除输入前后的空格,避免误输入空格导致判断失效 - 用
break替代quit():更安全地退出循环,后续若有其他代码可正常执行
内容的提问来源于stack exchange,提问作者DM0909
相关产品推荐
相关产品推荐

