我试图打印不同的选项,这些选项是我的函数的参数,但是,如果特定的参数是空字符串,我希望我的代码不打印任何东西。我到现在为止的密码是:
def ask_question(question, option1, option2, option3, option4):
#print the question onto the screen as well as numbered options
print(question)
print("1 ", option1)
print("2 ", option2)
print("3 ", option3)
print("4 ", option4)
#store answer under user_response
user_response = input("Your answer: ")
return user_response这个指纹
你好吗
当参数是:(“你好”、“好”、“坏”、"“、"")
但我想把它打印出来:
你好吗
而不包括任何带有空字符串的选项。
我该做什么有什么帮助吗?
发布于 2022-02-07 00:08:51
最好按以下方式传递一份可能的响应列表:
def ask_question(question, options):
print(question)
number = 0
for option in options:
number += 1
print(f" {number:2}. {option}")
while True:
try:
answer = int(input("Your answer: "))
if 1 <= answer <= number:
return answer
print(f"Input out of range, try again.")
except Exception as exc:
print(f"Input error, try again: {exc}.")
response = ask_question("How are you?", ["Good", "Bad"])这样,您可以满足任意数量的可能性,包括检查输入的有效性,如所示。
发布于 2022-02-07 00:10:26
与其单独使用选项参数,不如只使用一个包含列表的选项param。然后你就可以这样做:
def ask_question(question, options:list):
#print the question onto the screen as well as numbered options
print(question)
for e, option in enumerate(options,1):
print(f'{e}) {option}')
#store answer under user_response
user_response = input("Your answer: ")
return user_response发布于 2022-02-07 00:24:41
我刚才在每个人面前都使用了一个if语句,结果很好: ex: if(option1 != "")打印(“1”,option1) --这很有效,并通过了测试
https://stackoverflow.com/questions/71012174
复制相似问题