Python 中"Do you want to continue?"类型案例的问题



以下是场景:

我有一个功能,要求用户输入-从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部分。简而言之,以下是我希望它做的事情:

  1. 用户可以选择从给定列表中选择字符串(称为column_names(
  2. 他故意输入错误的价值观
  3. 剧本上写着">找不到这些条目。你想再试一次吗?[Y/n]">
  4. 当用户点击Y时,它会返回并再次执行整个操作
  5. 如果他选择,则退出循环

就我的一生而言,我无法做到这一点。

非常感谢您的帮助。

输入正确后,整个主体应该处于while循环中。不要像这样以无限制的方式使用递归。

column_names = set(["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx")
def newfunc():
while True:
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(',')
if all(arg.replace(" ", "") in column_names for arg in args):
break

missing = set(args) - column_names
if missing:
print(f"Missing: {missing}")
response = input("Do you want to try again?")
if response.lower() == "n":
break
column_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx"]
def newfunc():
print (f"Here is the list of columns to choose from: {column_names}n") //correction
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:
if input("Do you want to continue? [Y/n]: ").lower() == 'y': //correction no need of while
newfunc()
newfunc() #Calling the function.

对代码进行了一些重构:

(也解决了"输入以选择所有列"的问题。(

# The list to choose the items from
column_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt",
"fuDmY", "WoTau", "qrFaZ", "ZGSkx"]
def get_input():
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").strip().split(',')
return args

while True:
args = get_input()
if len(args) == 1 and args[0] == '':  # pressed enter
print('OK. Selected all columns')
break
# This will hold the wrong entries entered by the user.
userinputs_notfound = []
for arg in args:
if arg.replace(" ", "") not in column_names:
userinputs_notfound.append(arg.replace(" ", ""))
if not userinputs_notfound:
print('OK')
break
should_quit = input("Do you want to continue? [Y/n]: ").lower() == 'n'
if should_quit is True:
break

输出:

Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']
Enter column names separated by comma (Hit enter to select all columns).
DWUXZ, bKDoH
OK
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']
Enter column names separated by comma (Hit enter to select all columns).
fda, fdax
Do you want to continue? [Y/n]: n
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']
Enter column names separated by comma (Hit enter to select all columns).
fda, dax
Do you want to continue? [Y/n]: y
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']
Enter column names separated by comma (Hit enter to select all columns).
Here is the list of columns to choose from: ['DWUXZ', 'bKDoH', 'erLlI', 'QJAfR', 'dAfNn', 'kpwGt', 'fuDmY', 'WoTau', 'qrFaZ', 'ZGSkx']
Enter column names separated by comma (Hit enter to select all columns).
OK. Selected all columns

将整个函数体放入for循环中,并将递归调用省略为:

def foo():
while x:
do_stuff
change_x

或者省略while循环,并使用条件if语句保持递归为:

def foo():
do_stuff
if condition:
foo()

否则,您将继续调用该函数,因此您需要转义在程序运行期间创建的每个while input() == 'y'循环,无论循环有多少。

至于"点击回车保持选择所有列":

if arg == ['']:
arg = column_names

检查[''],因为您对用户输入进行了拆分。

这是针对python 3.8+的

# The list to choose from
col_names = ["DWUXZ", "bKDoH", "erLlI", "QJAfR", "dAfNn", "kpwGt", "fuDmY", "WoTau", "qrFaZ", "ZGSkx"]
def newFunc():
# Print all the available column names.
print("List of columns to choose from:n", *col_names, sep = 'n')
# Filter out the missing names (if any) and ask for the prompt.
# The anonymous function inside lambda match against the empty
# string when the user chooses to select all.
while missing := list(filter(lambda name: name and name not in col_names,
input("nEnter column names separated by comma (Hit enter to select all): ").split(','))):

print("Missing:", *missing, sep = 'n')
# Break the loop for any of the negetive response.
if input("nDo you want to continue? ").lower() in ['n', "no", "nope", "nah"]:
break
# Implement here your logic when no missing is found.

# Call the function.
newFunc()

在赋值运算符:=的帮助下,我们在几行代码中就完成了这项工作。

最新更新