首页 > 解决方案 > 如何退出 if 语句并回到开头

问题描述

我有几个 if 语句,但如果第一个输入为假,它仍然会继续下一个 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,则应始终返回开始并询问体重。**如果没有满足任何条件,我需要它回到开始并再次要求重量。** 程序应重新启动并再次询问重量。

标签: python-3.xwhile-loopcontrol-flow

解决方案


用一个 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

推荐阅读