简体   繁体   English

在范围循环中跳过

[英]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?出于某种原因for i in range(0,noYears)不起作用? 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.它只是在完成一次后移动到下一行代码 - 即使我将 noYears 的答案设为 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.代码不起作用,因为 while 循环永远不会执行。 You could solve this two ways.你可以通过两种方式解决这个问题。

  1. Use a break statement instead of setting loop to 1:使用 break 语句而不是将循环设置为 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 循环内将变量循环重置为 0:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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