[英]how to exit an if statement and go back to the beginning
我有幾個 if 語句,但如果第一個輸入為假,它仍然會 go 進入下一個 if 語句,而不是回到該 if 語句的開頭並重新開始。
下面的代碼
# check the weight of a single parcel
while True:
pweight = float(input('How much does your parcel weigh in kg? '))
if pweight > 10:
print('Sorry the parcel is to heavy')
elif pweight < 1:
print('Sorry the parcel is to light')
else:
break
print('----------------------------------------------')
while True:
height1 = float(input('Enter the parcel height in cm: '))
if height1 > 80:
print('Sorry, Your height is too large')
else:
break
print('----------------------------------------------')
while True:
width1 = float(input('Enter the parcel width in cm: '))
if width1 > 80:
print('Sorry, Your width is too large')
else:
break
print('----------------------------------------------')
while True:
length1 = float(input('Enter the parcel length in cm: '))
if length1 > 80:
print('Sorry, Your length is too large')
else:
break
print('----------------------------------------------')
while True:
if (height1 + width1 + length1) > 200:
print('Sorry, the sum of your dimensions are too large')
else:
print('Your parcels dimensions are', height1, 'x', width1, 'x', length1)
print('Your parcel has been accepted for delivery, many thanks for using our service :)')
break
例如,如果輸入的重量為 11 或身高大於 80,則應始終 go 回到開頭並詢問重量。 **如果不滿足任何條件,我需要將它 go 回到開頭並再次詢問重量。 ** 程序應重新啟動並再次詢問重量。
用一個 while True 循環代替所有問題。 除了中斷之外,您還必須在要從頭開始重新開始問題的條件下使用continue 。
# check the weight of a single parcel
while True:
pweight = float(input('How much does your parcel weigh in kg? '))
if pweight > 10:
print('Sorry the parcel is to heavy')
continue
elif pweight < 1:
print('Sorry the parcel is to light')
continue
print('----------------------------------------------')
height1 = float(input('Enter the parcel height in cm: '))
if height1 > 80:
print('Sorry, Your height is too large')
continue
print('----------------------------------------------')
width1 = float(input('Enter the parcel width in cm: '))
if width1 > 80:
print('Sorry, Your width is too large')
continue
print('----------------------------------------------')
length1 = float(input('Enter the parcel length in cm: '))
if length1 > 80:
print('Sorry, Your length is too large')
continue
print('----------------------------------------------')
if (height1 + width1 + length1) > 200:
print('Sorry, the sum of your dimensions are too large')
continue
else:
print('Your parcels dimensions are', height1, 'x', width1, 'x', length1)
print('Your parcel has been accepted for delivery, many thanks for using our service :)')
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.