我希望在Python程序中使用函数使其更整洁,更高效。根据用户的选择,我可以在函数内返回true或false。尽管在输入错误/无效回复的情况下,我还是希望以不问更多问题的方式返回返回。
编辑:
更具描述性;我想重新创建一个:
def askquestion(question):
response = input(question, "Enter T or F")
if response == "T":
return True
elif response == "F":
return False
else:
return None
def askmultiple():
questionOne = askquestion("Do you fruits?")
if questionOne == None:
return # Exit the function, not asking more questions
questionTwo = askquestion("Do you Apples?")
if questionTwo == None:
return # Exit the function, not asking more questions
我想事后检查是否为None
,然后返回return。
答案 0 :(得分:0)
如果在函数的末尾没有创建返回语句,该语句等于唯一的return
,而这两个函数等于return None
调用。
因此,您可以像下面这样组织代码:
if returned_value is None:
# do something a
elif returned_value is False:
# do something else
else: # value is True
# do something b
答案 1 :(得分:0)
您可以尝试使用while循环来确保用户输入正确的输入。 例如:
while not response.isdigit():
response = input("That was not a number try again")
在这种情况下,当用户输入“ response”不是一个数字时,python控制台将继续请求响应。对于基本模板,
while not (what you want):
(ask for input again)
希望这对您有所帮助。 :)
答案 2 :(得分:0)
使用异常流。
def ask_question(prompt):
"""Asks a question, translating 'T' to True and 'F' to False"""
response = input(prompt)
table = {'T': True, 'F': False}
return table[response.upper()] # this allows `t` and `f` as valid answers, too.
def ask_multiple():
questions = [
"Do you fruits?",
"Do you apples?",
# and etc....
]
try:
for prompt in questions:
result = ask_question(prompt)
except KeyError as e:
pass # this is what happens when the user enters an incorrect response
如果table[response.upper()]
既不是KeyError
也不是response.upper()
,则'T'
会引发'F'
,因此您可以在下面找到它,并使用该流程移动您跳出循环。
另一种选择是编写一个验证器,以强制用户正确回答。
def ask_question(prompt):
while True:
response = input(prompt)
if response.upper() in ['T', 'F']:
break
return True if response.upper() == 'T' else False