【发布时间】:2020-11-05 06:13:10
【问题描述】:
这是场景:
我有一个要求用户输入的功能 - 从 n 个项目的列表中选择 m 个项目(给定 m n)。仅供参考,如果他愿意,他可能会输入错误的值,在这种情况下,他会被问到是否要重新开始,但如果他输入了正确的值,那就没问题了。我被前一部分卡住了。
这是我的代码,我知道它是错误的,所以不需要惩罚我!
column_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx"] #The list to choose the items from
def newfunc():
print (f"Here is the list of columns to choose from: {column_names}\n"
args = input ("Enter column names separated by comma (Hit enter to select all columns).\n").split(',')
userinputs_notfound = [] #This will hold the wrong entries entered by the user.
for arg in args:
if arg.replace(" ", "") not in column_names:
userinputs_notfound.append(arg.replace(" ", ""))
if len(userinputs_notfound) == 0:
pass
else:
while input("Do you want to continue? [Y/n]: ").lower() == 'y':
newfunc() #Recursively calling the function
newfunc() #Calling the function.
我无法正确处理 while 部分。简而言之,这就是我想做的事情:
- 用户可以选择从给定列表中选择字符串(称为column_names)
- 他故意输入错误的值
- 脚本显示“未找到这些条目。您要再试一次吗?[Y/n]”
- 当用户点击 Y 时,它会返回并再次执行整个操作。
- 如果他选择否,则退出循环
为了我的一生,我无法做到这一点。
非常感谢任何帮助。
【问题讨论】:
标签: python python-3.x while-loop user-input