首页 > 解决方案 > 使用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()

但它不能正常运行任何人的帮助

标签: pythonif-statementinputwhile-loop

解决方案


这能回答问题吗?

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())

推荐阅读