2014-01-05 101 views
1

我是一名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

在此先感谢!

+0

代码是否按原样,或者它实际上有缺口?在'价格...'缩进?另外,特别是你有什么错误? –

+4

你正在使用Python3.x,它的'input'返回一个字符串 - 你需要首先将它转换为一个整数才能与'if'语句中的整数进行比较....'btw = int(...) '...你可能想要一个浮动价格...例如:'价格=浮动(...)'等... –

+0

为什么你的意思是“它不工作”。你是否遇到错误? – Christian

回答

1

因为input返回一个字符串,所以您必须将输入转换为您想要的相应类型(使用Python 3.3)。在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 
+1

谢谢!终于搞定了! :) – Sytze