简体   繁体   中英

in range loop skipping through

    salary=0
salaryArray=[]
loop=0
noYears=int(input("How many years do you want to do salaries for? "))
for i in range(0,noYears):
    while loop==0:
        print()
        print("You can add multiple sources of income, one at a time")
        salaryType=input("Do you want to put in your salary hourly or yearly? (h/y) ")
        if salaryType=="y":
            salarySection=float(input("What is your salary? "))
            salary=salarySection+salary
        else:
            salaryHourly=float(input("What are you payed per hour? "))
            salaryWeekly=float(input("How many hours per week will you work? "))
            salaryYearly=float(input("How many weeks per year will you work? "))
            print()
            salarySection=salaryHourly*salaryWeekly*salaryYearly
            salary=salary+salarySection
        
        repeat=input("Do you wish to add another source of income? (y/n) ")
        if repeat=="n":
            print("This year's anual salary is", salary)
            salaryArray.append(salary)
            loop=1

For some reason the for i in range(0,noYears) isn't working? It just moves on to the next line of code after doing it through once - even though I put the answer to noYears as 3.

Anyone know why this might be as I cannot see what is wrong? :)

The code isn't working because the while loop never executes. You could solve this two ways.

  1. Use a break statement instead of setting loop to 1:

     #previous code repeat=input("Do you wish to add another source of income? (y/n) ") if repeat=="n": print("This year's anual salary is", salary) salaryArray.append(salary) break
  2. Reset the variable loop to 0 inside of the for loop:

     for i in range(0,noYears): loop = 0 while loop==0: # remaining code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM