Write a program that asks the user to enter the amount that he or she has // budgeted for a month. Call a function that uses a loop that prompts the user // to enter each of his or her expenses for the month and keep a running total. // The loop finishes when the user enters an expense of 0 at which time the function // returns the total for the monthly expenses. The program should display the amount // that the user is over or under budget.

Respuesta :

Answer:

The program is written in Python as it possesses a simple and clean syntax.

  1. def getExpenses():
  2.    total_amount = 0
  3.    amount = float(input("Amount: $"))
  4.    total_amount += amount
  5.    while(amount !=0):
  6.        amount = float(input("Amount: $"))
  7.        total_amount += amount
  8.    return total_amount
  9. budget = float(input("Enter your monthly budget: $"))
  10. expenses = getExpenses()
  11. if(budget > expenses):
  12.    print("Under budget.")
  13. else:
  14.    print("Over budget.")

Explanation:

Line 1 - 11: (A function to prompt user for each of his/her expenses)

  • Create a variable total_amount to track the running total. Assign an initial value zero to the variable. (Line 2)
  • Use Python built-in function input() to prompt user for expenses amount and assign the input to variable amount. (Line 4)
  • Add the expenses amount to variable total_amount. (Line 5)
  • Create a while loop to keep prompting user for expenses amount and add the expenses amount to variable total_amount until user input zero (Line 7-9)
  • Return total_amount as output

Line 13: Get user input for monthly budget

Line 14: Call the function getExpenses() to obtain the total expenses from user

Line 16 - 19: Determine if user is over budget or under budget

  • Set an if condition - if budget is bigger than expenses, display "Under budget" (Line 17)
  • else, display "Over budget" (Line 19)

Otras preguntas