2017-09-26 184 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)使它过于复杂。