我想知道是否可以将两个变量放入一个if语句中,每个级别都包含一个块,包括current_text变量和answers变量。我想让代码更短,它有太多“如果”。比如说:
if level in easy:
current_text = easy_level
answers = easy_answers
这是代码:
if level in easy:
current_text = easy_level
if level in medium:
current_text = medium_level
if level in hard:
current_text = hard_level
if level in easy:
answers = easy_answers
if level in medium:
answers = medium_answers
if level in hard:
answers = hard_answers
ask_questions(current_text, answers)
由于
答案 0 :(得分:2)
是的,你可以做类似下面的代码。
print "Please enter a number between 1 and 20"
enter_num = int(raw_input("> "))
if enter_num >= 1 and enter_num <= 20:
print "You have entered a valid number"
if enter_num % 2 == 0: #test for even/odd
print "Your number is even"
print enter_num * enter_num
elif enter_num % 2 == 1: #test for even/odd
print "Your number is odd"
print enter_num * 3
else:
print "You've entered an invalid number"
详细说明可在此处找到。
https://blog.udemy.com/python-if-else/
你的最终if条件可能如下所示。
if level in easy:
current_text = easy_level
answers = easy_answers
if level in medium:
current_text = medium_level
answers = medium_answers
if level in hard:
current_text = hard_level
answers = hard_answers
ask_questions(current_text, answers)
答案 1 :(得分:1)
简短的回答,是的。
if level in easy:
current_text = easy_level
answers = easy_answers
elif level in medium:
current_text = medium_level
answers = medium_answers
elif level in hard:
current_text = hard_level
answers = hard_answers
ask_questions(current_text, answers)
答案 2 :(得分:0)
这看起来像您可能更喜欢使用字典调度的情况:
Close
...其中current_text = text[level]
current_answers = answers[level]
设置为level
...或其他任何内容。