python-3.x - 是否可以接受输入并通过字符串运行它并以我的方式打印它?
问题描述
为什么当我告诉它“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.
解决方案
这是解决方案
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
推荐阅读
- python - 如何使用python将字符串转换为列表?
- excel - Excel 库存跟踪(清除旧输入但保留该值)
- laravel - Laravel 5.8 - 为 foreach() 提供的参数无效?
- sas - 将 SAS 自定义用户格式转换为宏程序
- sql - 从 T-SQL 创建一个新的 Excel 工作表
- javascript - 将标签数组放入chartjs?
- c# - LINQ,检查此字符是否包含在我的数据库中的某些表中
- jquery - 只有第一个 if 在 JSRender 中被评估
- istio - 如何让 Istio 路由匹配工作?
- reactjs - 我需要帮助才能使用地图功能(React JS)显示此 JSON 数据