[英]How do I get an if elif else statement to restart
I am a newbie, and am having trouble getting the following code to process. 我是新手,无法处理以下代码。
choice 选择
if: (statement is false) 如果:(陈述为假)
moves to elif statement
elif: (statement is false) elif :(陈述为假)
moves to else statement
else: (I would like for the loop to go back up to choice to retry the if and elif statements else :(我希望循环返回到选择项,以重试if和elif语句
I tried some different indentations and such, but I'm sure I'm missing something else to retrigger the loop. 我尝试了一些不同的缩进等等,但是我确定我缺少其他东西来重新触发循环。
if
is not a loop, it is a conditional. if
不是循环,则是有条件的。 Therefore, there is no loop for you to restart. 因此,没有循环供您重新启动。
while
is a loop. while
是一个循环。 (There are others that do slightly different things.) It can't branch like if
, it just loops. (有些其他程序的功能略有不同。)它不能像if
一样分支,它只是循环。
If you need to make a decision in a loop, put if
inside of while
. 如果需要循环决策,请将if
放在while
。 No single statement is designed to do everything. 没有一个单一的语句可以做所有事情。
while True: # repeats forever
feedback = get_user_feedback()
if feedback_is_this_way(feedback):
go_this_way()
elif feedback_is_that_way(feedback):
go_that_way()
elif feedback_says_user_is_sick_and_tired(feedback):
apologise_to_user()
break # exits the loop
else:
tell_the_user_not_to_mess_around()
I believe you're looking for a while
loop. 我相信您正在寻找一个while
循环。 For this example, the code will continue at the top until the user enters exit
. 对于此示例,代码将在顶部继续,直到用户输入exit
为止。
while True:
item = input('Enter text: ')
if item == 'banana':
print('You entered: {}'.format(item))
elif item == 'apple':
print('You entered: {}'.format(item))
elif item == 'cherry':
print('You entered: {}'.format(item))
elif item == 'exit':
break
else:
print('You did not enter a fruit, try again!')
Some example output 一些示例输出
Enter text: banana
You entered: banana
Enter text: apple
You entered: apple
Enter text: cherry
You entered: cherry
Enter text: exit
while True:
if condition_one:
pass
elif condition_two:
pass
else:
continue
break
You could try putting the conditional block in a function and then call the function again for the else condition: 您可以尝试将条件块放入函数中,然后针对else条件再次调用该函数:
def conditionCheck():
if (...):
#do stuff
elif (...):
#do stuff
else:
conditionCheck()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.