0

这是我编写的一段非常简单的代码,但如果有办法让它更 Pythonic,那么我很想知道。谢谢!

def money():
    current_salary = float(input("What is your current salary? "))
    years = int(input("How many years would you like to look ahead? ")) + 1
    amount_of_raise = float(input("What is the average percentage raise you think you will get? "))
    amount_of_raise = amount_of_raise * 0.01

    while years > 1:
        years = years - 1
        new_salary = current_salary + (current_salary * amount_of_raise)
        current_salary = new_salary
        print('Looks like you will be making', new_salary,' in ', years,'years.')

money()
4

1 回答 1

2

Extended assignment operators

amount_of_raise = amount_of_raise * 0.01
years = years - 1

x = x * y can be shortened to x *= y. Same thing for -.

amount_of_raise *= 0.01
years -= 1

Iteration and counting

while years > 1:
    years = years - 1

Counting down causes your printouts to display backwards. I would count up. The Pythonic way to count uses range:

for year in range(1, years + 1):
    print('Looks like you will be making', new_salary,' in ', years,'years.')

Computing new salary

new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary

I'd probably just simplify that to:

current_salary += current_salary * amount_of_raise

Or even better is to give a 5% raise by multiplying by 1.05. In code that is:

current_salary *= 1 + amount_of_raise
于 2013-07-06T21:25:14.367 回答