python - 使用while循环时如何在python中排除空行和小于零的数字
问题描述
我正在编写一个执行 if-else 条件的简单程序。我的程序从用户那里接收以公斤为单位的物体重量作为输入。,一个浮点数,并打印出装运价格。通过使用 while 我想扩展程序来运行并计算多个包的总价格。程序应该加载数据包权重,直到用户输入一个空行或一个小于等于 0 的数字。然后程序将打印所有包裹的总价
代码如下所示:
def packagePrice():
weightInKg = float(input(" Enter the value of weight:"))
totalPrise = 0
while weightInKg != "" or weight <= 0:
if weightInKg <= 10:
price = 149
elif 10 < weightInKg <= 100:
price = 500
elif weightInKg > 100:
print ("Not allowed")
totalPrise+= price
print(totalPrise)
weightInKg = float(input(" Enter the value of weight:"))
packagePrice()
但它不能正常运行任何人的帮助
解决方案
这能回答问题吗?
def packagePrice():
totalPrise = 0
while True:
weightInKg = input(" Enter the value of weight:")
if weightInKg == '':
break
try:
weightInKg = float(weightInKg)
except ValueError:
print("Text not allowed")
continue
if weightInKg <= 0:
break
if weightInKg <= 10:
totalPrise += 149
elif weightInKg <= 100:
totalPrise += 500
else:
print("Not allowed")
return totalPrise
print(packagePrice())
推荐阅读
- threadpool - gRPC context.interceptCall() 和 SimpleForwardingServerCallListener
- azure - Terraform:如何修复 azurerm_cosmosdb_account 创建超时
- c# - WPF TextBox 绑定到 StringBuilder 以模拟控制台性能
- java - 如何从 servlet 获取 JSP 中的属性?
- javascript - 清除现有对话框
- reactjs - 应用程序在 heroku 上运行良好,除了一个问题
- amazon-web-services - 获取 AWS 机器类型(ubuntu/nixos/centos 等)
- browser - 屏幕阅读器在按下按钮或链接时使用什么浏览器事件?
- java - JPanel paintComponent() 不会在 JFrame 中绘制
- apache-flink - 理解 Flink 中使用的 Status.JVM.Memory.Direct.Memory