如何使if elif else语句重新启动

3

我是一个新手,正在尝试使以下代码正常运行。

选择

如果:(语句为假)

  moves to elif statement

elif:(语句为假)

  moves to else statement

否则:(我希望循环返回到选择以重试if和elif语句。
我尝试了不同的缩进等方法,但我确定我错过了其他重新触发循环的东西。
5个回答

3

if 不是循环语句,而是条件语句。因此,你没有循环可以重新启动。

while 是一种循环语句。(还有其他略微不同的循环语句。) 它不能像if那样分支,它只是循环。

如果你需要在循环中做出决策,请将if放在while内部。没有单个语句被设计来完成所有任务。

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()

tell_the_user_not_to_mess_around 加 1 :D - Ayxan Haqverdili

1
您可以尝试将条件块放入函数中,然后再次调用该函数以进行else条件处理:
def conditionCheck():
    if (...):
        #do stuff
    elif (...):
        #do stuff
    else:
        conditionCheck()

1
我相信您正在寻找一个 while 循环。在这个例子中,代码将一直在顶部继续执行,直到用户输入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!')

一些输出示例。
Enter text: banana
You entered: banana
Enter text: apple
You entered: apple
Enter text: cherry
You entered: cherry
Enter text: exit

0
while True:
    if condition_one:
       pass
    elif condition_two:
       pass
    else:
        continue
    break

0
'While True'和'Break'是你需要关注的'if'和'elif'语句中的内容。 下面是一个完整的工作示例:
print('Hello welcome to the Coffee House!')

name=input('\nWhat is your name?\n')

print('\nHello ' +(name) +'!\n')

menu= 'Americano, Cappucino, Latte, Espresso'

print('What would you like today? Here is our menu... \n\n' +menu)

Americanoprice = '£1.00'
Cappuchinoprice = '£1.50'
Latteprice = '£1.50'
Espressoprice = '£1.00' 

while True:
  order =input()

if (order=='Americano'):
  print('\nSounds good ' +name+ '.' + ' That will be '+Americanoprice + ' please')


elif (order=='Cappuchino'):
  print('\nSounds good ' +name+ '.' + ' That will be ' +Cappuchinoprice + ' please')


elif (order == 'Latte'):
  print('\nSounds good ' +name+ '.' + ' That will be ' +Latteprice + ' please.')


elif(order == 'Espresso'):
  print('\nSounds good ' +name+ '.' + ' That will be' +Espressoprice +' please.')
  
  break 

else:
  print('\nSorry but we do not have that. Would you like anything else?')

测试一下代码,看看所有东西是如何工作的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接