如何在问题中使用Y \ N(是或否)函数创建输入和输出?
我的例子;如果我的问题是Would you like some food? (Y \ N):
,我该怎么做,让答案显示Yes, please.
或No, thank you.
,然后选择具有相同功能的下一个问题?
我考虑过使用以下方法:valid=("Y": True, "y": True, "N": False, "n": False)
,但对我而言它仅显示为True
或False
,或者有办法将True \ False
更改为{{ 1}}?或这个:
Yes \ No
但是我真的不确定如何继续进行此操作,或者是否还有其他更简单的解决方案。
答案 0 :(得分:0)
我认为您要查找的是条件打印语句,而不是函数上的true / false return语句。
例如:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
print ("Yes, please" if user_input == 'Y' else "No, thank you")
或者,更具可读性:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
if (user_input == 'Y'):
print("Yes, please")
elif (user_input == 'N'):
print("No, thank you")
答案 1 :(得分:0)
我希望我能正确理解您的问题,基本上您每次输入一个值时都会检查第一个字母(以防用户输入“是/否”),并尝试验证是否为“是/否”,否则就中断循环问同样的问题。
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
if user_input[0].lower() == 'y':
print("Yes, please.")
break
elif user_input[0].lower() == 'n':
please("No, thank you.")
break
else:
print("Invalid, try again...")
答案 2 :(得分:0)
不确定这是否是最好的方法,但是我有相同的基于类的实现
""" Class Questions """
class Questions:
_input = True
# Can add Multiple Questions
_questions = [
'Question 1', 'Question 2'
]
def ask_question(self):
counter = 0
no_of_question = len(self._questions)
while self._input:
if counter >= no_of_question:
return "You have answred all questions"
user_input = input(self._questions[counter])
self._input = True if user_input.lower() == 'y' else False
counter += 1
return "You have opted to leave"
if __name__ == '__main__':
ques = Questions()
print(ques.ask_question())