Python函数挣扎



我是Python的初学者,我正在练习一些函数。现在我有以下代码:

def BTWcalculator():
    price = input("What is the products price?")
    btw = input("Please enter a valid BTW-class: 1 = 6%, 2 = 19%")
    if btw == 1:
        return price * 1.06
    elif btw == 2:
        return price * 1.19
    else:
        BTWcalculator()

BTWcalculator()

但是,它不起作用。我确定我错过了一些愚蠢的东西,但我就是找不到我的错误。如果有人能帮助我,那就太好了。

我正在使用Python 3.3.3

提前感谢!

你必须将输入转换为你想要的相应类型(使用 Python 3.3),因为input返回一个字符串。在 else 子句中,您必须返回 BTWcalculator() 的值,否则它不会被存储或打印。

法典:

def BTWcalculator():
    price = float(input("What is the products price?: "))
    btw = input("Please enter a valid BTW-class: 1 = 6%, 2 = 19%: ")
    if btw == "1":
        return price * 1.06
    elif btw == "2":
        return price * 1.19
    else:
        return BTWcalculator()

并对其进行测试:

print BTWcalculator()

输出:

What is the products price?: 10
Please enter a valid BTW-class: 1 = 6%, 2 = 19%: 3
What is the products price?: 10
Please enter a valid BTW-class: 1 = 6%, 2 = 19%: 1
10.6

最新更新