Home > Blockchain >  PYTHON: Using users answers to repeat a question x amount of times
PYTHON: Using users answers to repeat a question x amount of times

Time:09-30

I'm trying to develop a program that will formulate interest rate according to user input over x amount of years.

interestRateYear = int(input("Please enter the year that you want to calculate the personal interest rate for : "))
expenditureCategories = int(input("Please enter the number of expenditure categories: "))

According to the user input for expenditureCategories, the following questions will be asked x amount of times.

previousYearExpenses= int(input("Please enter expenses for previous year: "))
expensesOfInterest= int(input("Please enter expenses for year of interest: "))

I tried creating a loop statement

while expenditureCategories>=0: 
    previousYearExpenses= int(input("Please enter expenses for previous year: "))

    expensesOfInterest= int(input("Please enter expenses for year of interest: "))

    previousYearExpenses = previousYearExpenses   1

    expensesOfInterest = expensesOfInterest   1 

I'm new to coding and I'm not sure what I'm doing wrong.

CodePudding user response:

This should do the work:

interestRateYear = int(input("Please enter the year that you want to calculate the personal interest rate for : "))
expenditureCategories = int(input("Please enter the number of expenditure categories: "))
for i in range(expenditureCategories): #This will repeat expenditureCategories number of times 
    previousYearExpenses= int(input("Please enter expenses for previous year: "))
    expensesOfInterest= int(input("Please enter expenses for year of interest: "))
    previousYearExpenses = previousYearExpenses   1
    expensesOfInterest = expensesOfInterest   1 

CodePudding user response:

You forgot to substract numbers from the expeditureCategories counter. Now, if on the while loop, you want to ask the question the amount of times that is in the counter, it should be while > 0, because if you leave it as >=0 it will do it one more time than the amount of times you want. Now, i know youre starting and probably wont care for now, but if you want to keep learning, just know that if you know the amount of loops youre going to do, a for loop is more efficient than a while loop.

If you want to keep your original code,

while expenditureCategories > 0: 
    previousYearExpenses= int(input("Please enter expenses for previous year: "))
    
    expensesOfInterest= int(input("Please enter expenses for year of interest: "))

    previousYearExpenses = previousYearExpenses   1

    expensesOfInterest = expensesOfInterest   1 

    expenditureCategories = expenditureCategories - 1

This should work.

  • Related