我是一个新手,正在尝试使以下代码正常运行。
选择
如果:(语句为假)
moves to elif statement
elif:(语句为假)
moves to else statement
否则:(我希望循环返回到选择以重试if和elif语句。
我尝试了不同的缩进等方法,但我确定我错过了其他重新触发循环的东西。
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()
def conditionCheck():
if (...):
#do stuff
elif (...):
#do stuff
else:
conditionCheck()
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
while True:
if condition_one:
pass
elif condition_two:
pass
else:
continue
break
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?')
tell_the_user_not_to_mess_around
加 1 :D - Ayxan Haqverdili