python-3.x - 如何退出 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,则应始终返回开始并询问体重。**如果没有满足任何条件,我需要它回到开始并再次要求重量。** 程序应重新启动并再次询问重量。
解决方案
用一个 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
推荐阅读
- c++ - 如何仅使用标准库将 C++ 对象写入文件
- javascript - 如何处理嵌套表单的条件验证?
- css - 如何将特定于浏览器的 CSS 组合在一起?
- asp.net - 无法使用 NLog 从托管在 Windows Elastic Beanstalk 机器上的 ASP.Net 应用程序将日志写入 AWS cloudwatch
- google-compute-engine - 在 GCP 中克隆 windows 虚拟机的最佳方法
- python - 熊猫 groupby 中的 NaN 项目是否后跟聚合,包括类别列的预期行为?
- python - 不打印多处理中的功能输出
- sql-server - 用引号显示多列输出值的 STUFF 函数 SQL Server
- python-3.x - 如何从 odoo 中删除已付款或已过帐的发票?
- apache-spark-sql - 在 PySpark/Delta 数据帧上高效执行