2017-09-26 183 views
0

我正在嘗試創建一個更改返回程序,該程序需要一個項目的成本和給定的資金,並返回筆記,宿舍,硬幣等方面的適當更改。等在Python中將用戶提供的數字轉換爲整數和浮點數

我是相當新的編程,我堅持試圖分裂它。我查看了StackOverflow,發現方法math.modf(x)是相關的。但是,我很難實施它。

能否請你讓我知道爲什麼changeyis not defined

感謝

import math 

def changereturn(): 

    quarter = 0.25 
    dime = 0.1 
    nickel = 0.05 
    penny = 0.01 

    cost = float(raw_input('Please enter the cost of the item in USD: ')) 
    money = float(raw_input('Please enter the amount of money given in USD: ')) 

    change = money - cost 


    y = math.modf(change) 

    return change 
    return y 

回答

1

函數(def)只能return一次,但是Python可以讓你返回元組的結果。

此實現可能是你所需要的:

import math 

def changereturn(): 
    quarter = 0.25 
    dime = 0.1 
    nickel = 0.05 
    penny = 0.01 

    cost = float(input('Please enter the cost of the item in USD: ')) 
    money = float(input('Please enter the amount of money given in USD: ')) 

    change = money - cost 

    y = math.modf(change) 

    return change, y 

print(changereturn()) 
+0

謝謝。我如何將整數部分賦值給一個變量,將浮點部分賦值給另一個變量?謝謝 – paulnsn

+1

用我的'change,y = changereturn()'替換他的'print(changereturn())' –

1

第一個問題是你從來沒有運行changereturn()函數。第二個問題是changereturn()函數中的兩條return行。發送y的第二個函數永遠不會運行。你可以返回(其他城市,y)和作爲運行您的程序:

change, y = changereturn() 

print change 
print y 

你需要把這個在最底層沒有縮進。就個人而言,我不喜歡從函數返回多個東西。通常我會建議捕捉它作爲一個元組,然後打印每個部分。你的問題有點像一個Comp Sci一年級學生的任務,所以我不想1)爲你解決它,2)使它過於複雜。