我希望在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,并返回返回。
发布于 2019-07-01 23:04:14
如果您不在一个函数的末尾创建一个返回语句,该语句等于唯一的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发布于 2019-07-01 23:04:21
您可以尝试使用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)希望这能帮到你。:)
发布于 2019-07-02 01:46:50
使用异常流。
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()]既不是'T'也不是'F',那么response.upper()将引发response.upper(),所以您可以在下面捕获它,并使用该流将您从循环中移出。
另一种选择是编写一个验证器,强制用户正确地回答。
def ask_question(prompt):
while True:
response = input(prompt)
if response.upper() in ['T', 'F']:
break
return True if response.upper() == 'T' else Falsehttps://stackoverflow.com/questions/56843414
复制相似问题