python - 使用用户输入在python中循环和求和
问题描述
我试图通过要求用户输入他们想要预算的金额并将其分解为特定金额并在每次迭代中从原始金额中减去该金额并向他们展示最后的结果来计算预算
budget = int(input("Please enter the amount you have budgeted for this month: "))
print(budget)
expensess = ['Rent','Food','Car','Gym','Phone','Travel','Savings']
balance=0
budget = budget
for i in expensess:
added_balance = int(input('How much did you budget for '+str(i)))
new_balance = int(budget - added_balance)
print(new_balance)
balance += new_balance
budget = balance
print("budget is "+str(budget))
if balance is > budget:
print("You underbudgeted ")
else:
print('Good Job you would have extra money to spend'+ )
当我运行这个
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
=== RESTART: C:\Users\boxfo\Desktop\Programming Challenges\Budget Analysis.py ==
Please enter the amount you have bugeted for this month: 6000
6000
How much did you budget for Rent2000
budget is 4000
How much did you budget for Food2000
budget is 6000
How much did you budget for Car3000
budget is 9000
How much did you budget for Gym
解决方案
你应该减少预算变量,你可以计算你想要的所有问题:
budget -= balance
我已经从您的代码中编写了一个带有一些注释的工作版本。
代码:
budget = int(input("Please enter the amount you have budgeted for this month: "))
expensess = ["Rent", "Food", "Car"]
for i in expensess:
added_balance = int(input("How much did you budget for {}: ".format(i)))
budget -= added_balance # decrease the budget variable with the spend money
print("Current budget is {}".format(budget))
if 0 > budget: # If the budget is a minus number then you are underbudgeted.
print("You underbudgeted: {}".format(abs(budget))) # Creating ABS from negative number and print the difference.
else:
print("Good Job you would have extra money to spend: {}".format(budget))
测试:
预算不足:
>>> python3 test.py
Please enter the amount you have budgeted for this month: 6000
How much did you budget for Rent: 2000
Current budget is 4000
How much did you budget for Food: 2000
Current budget is 2000
How much did you budget for Car: 3000
Current budget is -1000
You underbudgeted: 1000
好工作:
>>> python3 test.py
Please enter the amount you have budgeted for this month: 6000
How much did you budget for Rent: 2000
Current budget is 4000
How much did you budget for Food: 1000
Current budget is 3000
How much did you budget for Car: 1000
Current budget is 2000
Good Job you would have extra money to spend: 2000
推荐阅读
- linux - 组装中的扫码
- c# - 如何获取失败的 .NET 测试的完整文件名?
- ios - Swift - UIButton 没有固定在屏幕底部
- sql - 在 2 个表之间进行比较并插入缺失的记录 pl sql
- c - 斐波那契数列 C 问题
- react-native - 更改背景颜色时反应导航选项卡栏图标消失
- angular - 将leafletjs AnimatedMarker 集成到打字稿中
- javascript - 伙计们,我怎样才能为我的功能添加 30 秒的延迟?我是 JavaScript 新手
- java - 是否有支持这种泛型注入的 Kotlin/Java DI 框架?
- python - 长列表创建 sorted() TypeError: 'NoneType' 对象不可下标