在python中使用while循环时如何排除空行和小于零的数字

2024-10-04 09:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的程序,它在条件为if-else时执行。我的程序接收用户输入的物体重量,单位为kg,浮点数,并打印出装运价格。通过使用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()

但它不能正常运行 有人帮忙吗


Tags: the用户程序inputiffloatpriceenter
1条回答
网友
1楼 · 发布于 2024-10-04 09:32:10

这能回答问题吗

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

相关问题 更多 >