1
def main():
    userInput()
    calculate()

def userInput():
    print("Please put in the weight of your package:")
    a= input()
    weight= float(a)


def calculate():
    if weight <= 2:
        print('Your rate is $1.10')
    elif weight > 2 or weight <= 6:
        print('Your rate is $2.20')
    elif weight > 6 or weight <= 10:
        print('Your rate is $3.70')
    else:
        print('Your rate is $3.80')
main()

所以基本上我想知道如何在“计算”模块中使用“用户输入”模块中的数据。我知道我有一个争论,但是(这一直让我发疯)对于我的生活,我无法找出正确的方法来做到这一点。我理解参数的概念,但我无法在我的代码中实现它。谢谢。

4

2 回答 2

0

您可以将weight周围作为参数传递

def userInput():
    a= input("Please put in the weight of your package:")
    weight = None
    try:
        weight= float(a)
    except:
        userInput()
    return weight

def calculate(weight):
    if weight <= 2:
        print('Your rate is $1.10')
    elif weight > 2 and weight <= 6:
        print('Your rate is $2.20')
    elif weight > 6 and weight <= 10:
        print('Your rate is $3.70')
    else:
        print('Your rate is $3.80')

def main():
    weight = userInput()
    calculate(weight)

main()
于 2013-09-30T19:53:22.347 回答
0

顺便说一句,您可以使用以下方法重写重量检查:

if weight <= 2:
    print('Your rate is $1.10')
elif 2 < weight <= 6:
    print('Your rate is $2.20')
elif 6 < weight <= 10:
    print('Your rate is $3.70')
else:
    print('Your rate is $3.80')

注意“n < x < n+”符号的使用

来自shantanoo的评论后更新:

我正在查看原始问题中的代码:

def calculate():
    if weight <= 2:
        print('Your rate is $1.10')
    elif weight > 2 or weight <= 6:
        print('Your rate is $2.20')
    elif weight > 6 or weight <= 10:
        print('Your rate is $3.70')
    else:
        print('Your rate is $3.80')

我意识到在两条 elif 行上,不需要第一次比较,代码可以重写为:

def calculate():
    if weight <= 2:
        print('Your rate is $1.10')
    elif weight <= 6:
        print('Your rate is $2.20')
    elif weight <= 10:
        print('Your rate is $3.70')
    else:
        print('Your rate is $3.80')
于 2013-09-30T20:08:41.883 回答