我应该做些什么来使我的代码更加pythonic?

时间:2013-07-06 21:19:15

标签: python

这是我编写的一段非常简单的代码,但如果有办法让它更加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()

1 个答案:

答案 0 :(得分:2)

扩展分配操作符

amount_of_raise = amount_of_raise * 0.01
years = years - 1

x = x * y可以缩短为x *= y-也是如此。

amount_of_raise *= 0.01
years -= 1

迭代和计数

while years > 1:
    years = years - 1

倒计时会导致打印输出向后显示。我会数数。 Pythonic计数方法使用range

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

计算新工资

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

我可能只是将其简化为:

current_salary += current_salary * amount_of_raise

或者更好的是通过乘以1.05来提高5%。在代码中:

current_salary *= 1 + amount_of_raise