在Python中将用户提供的数字转换为整数和浮点数

时间:2017-09-26 00:24:05

标签: python user-input

我正在尝试创建一个更改退货计划,该计划会收取物品的成本和给定的金额,并在票据,季度,角钱等方面返回正确的更改。

我对编程很新,而且我一直试图将其拆分。我查看了StackOverflow,发现方法math.modf(x)是相关的。但是,我很难实现它。

您能否告诉我为什么changey is 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

2 个答案:

答案 0 :(得分: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())

答案 1 :(得分:1)

第一个问题是你从不运行你的changereturn()函数。第二个问题是changereturn()函数中的两个return行。发送y的第二个函数永远不会运行。您可以返回(更改,y)并将程序运行为:

change, y = changereturn()

print change
print y

你需要把它放在最底部而不缩进。就个人而言,我不喜欢从函数中返回多个东西。通常情况下,我建议将其作为元组捕获,然后打印每个部分。你的问题有点像Comp Sci一年级学生的作业,所以我不想1)为你解决它,2)使它过于复杂。