2014-01-05 99 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