Python while循环可能需要一个break语句?

时间:2017-02-17 03:27:18

标签: python

我需要这段代码停止计算第20年后工资的增加。我尝试添加另一个while循环,但这会导致无限循环发生。任何帮助将不胜感激!!

RATE = 2.0
INITIAL_SALARY = 37238.00
salary = INITIAL_SALARY
year = 1

print("Murdock County")
print("Teacher Salary Schedule")
print()
print("Year          Salary")
print("----          ------")



while year < 31 :
    print("%4d  %15.2f"  % (year, salary))
    increase = salary * RATE / 100
    salary = salary + increase
    year = year + 1

2 个答案:

答案 0 :(得分:1)

while year < 31 :
    print("%4d  %15.2f"  % (year, salary))
    if year < 21:
       increase = salary * RATE / 100
       salary = salary + increase
    year = year + 1

答案 1 :(得分:1)

您可能输入的是31而不是21,所以

while year < 21 :
    # your code

或者你可能意味着在21岁之后工资不再增加,所以:

while year < 31 :
    print("%4d  %15.2f"  % (year, salary))
    if year < 21:
       increase = salary * RATE / 100
       salary += increase
    year += 1

您可以选择使用for循环,因为您知道循环执行的次数,并且可能会删除变量INITIAL_SALARY,使用括在tripe双引号或单引号中的字符串来避免使用太多打印声明:

RATE = 2.0
salary = 37238.00

print("""Murdock County
Teacher Salary Schedule

Year          Salary
----          ------""")


for year in range(1, 31):
    print("%4d  %15.2f" % (year, salary))
    if year < 21:
        increase = salary * RATE / 100
        salary += increase
    year += 1