有麻烦使用函数来打破我的代码



我有一个每月预算代码,显示用户是否超过/低于某个月的预算。我有麻烦将代码分解成def函数。这是我的

print("""
This program uses a for loop to monitor your budget.
The program will prompt you to enter your budget, and amount spent
for a certain month and calculate if your were under or over budget.
You will have the option of choosing how many months you would like to
monitor.n""")

AmountSpent = 0
Budget = 0

numMonths = int(input("Enter the number of months you would like to monitor:"))
while numMonths<0:
print("nNegative value detected!")
numMonths = int(input("Enter the number of months you would like to monitor"))
for month in range(1,numMonths+1):
print("n=====================================")
AmountBudgeted = float(input(f"Enter amount budgeted for month {month}:"))
while AmountBudgeted<0:
print("Negative value detected!")
AmountBudgeted = float(input(f"Enter amount budgeted for month {month}:"))
AmountSpent = float(input(f"Enter amount spent for month {month}:"))
while AmountSpent<0:
print("Negative value detected!")
AmountSpent = float(input(f"Enter amount spent for month {month}:"))
if AmountSpent <= AmountBudgeted:
underB = AmountBudgeted - AmountSpent
print(f"Good Job! You are under budget by {underB}")
else:
overB = AmountSpent - AmountBudgeted
print(f"Oops! You're over budget by {overB}")
if month == "1":
print(f'your budget is {AmountBudgeted}.')

谁能帮我用"def"把这段代码分解成函数?和其他函数,如" descripbeprogram ()"one_answers"GetMonths()";

?

您可以像

这样提取用户交互
def get_nb_months():
value = int(input("Enter the number of months you would like to monitor:"))
while value < 0:
print("Negative value detected!")
value = int(input("Enter the number of months you would like to monitor"))
return value

但是你注意到它们是完全相同的方法,所以你可以概括:

def get_amount(msg, numeric_type):
value = numeric_type(input(msg))
while value < 0:
print("Negative value detected!")
value = numeric_type(input(msg))
return value
def summary(spent, budget):
diff = abs(budget - spent)
if spent <= budget:
print(f"Good Job! You are under budget by {diff}")
else:
print(f"Oops! You're over budget by {diff}")
if __name__ == "__main__":
numMonths = get_amount("Enter the number of months you would like to monitor:", int)
for month in range(1, numMonths + 1):
print("n=====================================")
amount_budgeted = get_amount(f"Enter amount budgeted for month {month}:", float)
amount_spent = get_amount(f"Enter amount spent for month {month}:", float)
summary(amount_spent, amount_budgeted)

相关内容

最新更新