我正在尝试执行之前已经多次询问过的事情(特别是Asking the user for input until they give a valid response),但我要么尝试做一些过于复杂的事情,要么不考虑我的循环方式正确。
在下面的代码中,我尝试做一些事情:
loan_ids
)在第二个功能中,我试图合并第一个功能,然后让用户在切断之前确认loan_ids
:
y
,则结束循环n
,请返回第一个功能并再次询问我试图不违反不要重复自己的原则,但对于我的生活,我无法弄清楚循环的位置。我对python和编程结构也比较陌生,所以对设计的惯用评论也是开放的
def get_unique_loans_from_user():
"""Get list of loan_ids from user
This function is mean to capture raw loan_ids a user wishes to look up.
Returns tuple of unique loan_ids
"""
loan_ids = []
while True:
loan_id = raw_input('> Loan Id: ')
# If nothing entered, exit
if len(loan_id)==0:
break
# Make sure an integer was entered
else:
try:
int(loan_id)
except ValueError:
print loan_id + " is not a real integer, so likely not a valid loan id"
continue
# if an integer was entered, append to running list as an integer and continue
# We only need to return the unique list of loan ids
else:
loan_ids.append(int(loan_id))
# Convert unique list of loans to tuple to use in SQL
loans = tuple(np.unique(loan_ids))
# Return the tuple of loans
return loans
第二部分 - 它当前编写的方式会在用户输入y
以外的任何内容时强制执行相同的结果 - 我尝试根据使用是否无效而导致不同的行为输入与实际确认loan_ids
不正确。我最后还使用了一个额外的中断声明,我相当肯定这不是最佳实践
def confirm_loan_ids():
""" Confirm the list of loan ids is what the user wanted"""
while True:
# Get loan ids from user through raw input
ids = get_unique_loans_from_user()
# Print out the ids to the user
print "Printing loan ids. There are {0} ids".format(len(ids))
print ids
# Confirm with user these are the correct ids
answer = raw_input('> Are these the loan ids you expected? [y/n] ')
# If user confirms correct, and continue
if answer == 'y':
print "\nExcellent - moving on\n"
print "Here are your loan ids:"
print ids
break
# If the answer is n, repeat the question
elif answer == 'n':
print "\n-------------> Let\'s try again\n"
continue
# If answer is not no or yes, ask again
elif (len(answer) == 0) or (answer not in ('y','n')):
print "Please enter only y or n"
continue
else:
print "This is only a test"
# The If loop only breaks when the answer is 'y'
break
return ids
答案 0 :(得分:0)
试试这个。它减少了使用continue
的一些要求,而是让循环自然地再次迭代。这减少了代码中的视觉噪音。
对于第二个函数,您可以再次简化逻辑以消除使用continue的需要,而只是在输入良好时断开。
代码需要再次循环以获得yes / no确认,因此为了避免必须打破嵌套循环的问题,yes / no循环在另一个函数中。在收到有效输入之前,此功能不会返回。
希望这能为您提供一些更清晰的逻辑吗?
如果你想要而不是numpy.unique
,你可以恢复你的set
功能,但我一般不会使用numpy
而只是为了这个目的导入它似乎有点过分我使用{ {1}}而是。我不知道您的具体要求,因此不知道set
或set
是否更合适。
numpy.unique