如果您问某人是/否的问题,那么答案就是这两个选项之一。在编程中,如果响应是"Y"
或"y"
或"yes"
或其他原因,怎么办?
我必须创建一个复合条件来重复我的声明,而实际上它是相同的。我不是专家,但我可以看到它可以改进。
def note_maker(note):
case_note = open("case_note.txt", "a+")
update = case_note.write("\n" + note)
multiple_inputs = input("Do you want to enter more details? Y/N")
while multiple_inputs == "yes" or multiple_inputs == "YES" or multiple_inputs == "Yes" or multiple_inputs == "Y" or multiple_inputs == "y":
update_again = case_note.write("\n" + input("Enter your additional information"))
multiple_inputs = input("Do you want to enter more details?")
case_note.close()
有没有一种方法可以控制用户对我期望的输入?
答案 0 :(得分:0)
您可以缩短用户输入并使其小写,这应该有所帮助。
例如:user_input = input("Something? y/n: ")[0].lower()
这样,如果他们输入“ Y”,“是”,“是”或“是”,则最终将是“ y”。
答案 1 :(得分:0)
尝试将输入检查重构为新功能:
def is_affirmative(input: str) -> bool:
return input.strip().lower() in ['y', 'yes']
def note_maker(note):
case_note = open("case_note.txt", "a+")
update = case_note.write("\n" + note)
multiple_inputs = input("Do you want to enter more details? Y/N")
while not is_affirmative(multiple_inputs):
update_again = case_note.write("\n" + input("Enter your additional information"))
multiple_inputs = input("Do you want to enter more details?")
case_note.close()
答案 2 :(得分:0)
您可能有set
个有效的是响应和否响应:
yes_responses, no_responses = {'y', 'yes'}, {'n', 'no'}
user_response = None
while user_response not in yes_responses and user_response not in no_responses:
user_response = input("Do you want to enter more details? (Y/N): ").lower()
if user_response in yes_responses:
print("The user responded yes.")
else:
print("The user responded no.")
用法示例:
Do you want to enter more details? (Y/N): zxc
Do you want to enter more details? (Y/N): YesNo
Do you want to enter more details? (Y/N): yEs
The user responded yes.
注意:与set
或list
相比,使用tuple
的优势在于in
操作是{{1 }},而不是O(1)
。