首页 > 解决方案 > 是否可以接受输入并通过字符串运行它并以我的方式打印它?

问题描述

为什么当我告诉它“makeChange(change)”时它不能输出答案?我希望程序接受用户输入并接受它并遍历字符串并将其分解为变化。你可以让它打印功能吗?

def makeChange(amount):
      
      coins = [.05, .1, .25, .5, 1, 2, 5, 10, 20, 50, 100]
    
      coins.sort(reverse=True) 
    
      change = float(input("What do ya want to break down?")) #This is where I want the user to input a number.
      change = []
      for coin in coins:
        totalCoin = int(float(amount) // coin)
        amount = amount % coin
        amount = round(amount, 2)
        for i in range(totalCoin):
          change.append(coin)
        if amount == 0:
          return change
      return 'Not changeable'
                                                        #             \/
    print('Here is your change!: ', makeChange(change)) #makeChange(change) this is where I want the user input to go through the string come out with the answer of what the user inputted into change.

标签: python-3.x

解决方案


这是解决方案

def makeChange(amount):

    coins = [.05, .1, .25, .5, 1, 2, 5, 10, 20, 50, 100]

    coins.sort(reverse=True)

    change = []
    for coin in coins:
        totalCoin = int(float(amount) // coin)
        amount = amount % coin
        amount = round(amount, 2)
        for i in range(totalCoin):
            change.append(coin)
        if amount == 0:
            return change
    return 'Not changeable'


change = float(input("What do ya want to break down?"))
print('Here is your change!: ', makeChange(change))

一个函数在被调用之前不会运行。然后,您使用未定义的更改变量调用该函数。

我建议阅读有关范围的更多信息以更好地理解这一点。 https://www.w3schools.com/python/python_scope.asp


推荐阅读