我应该做些什么让我的代码更像python吗?

2024-03-28 18:23:38 发布

您现在位置: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()

Tags: ofyounewinputiscurrentfloatamount
1条回答
网友
1楼 · 发布于 2024-03-28 18:23:38

扩展赋值运算符

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

相关问题 更多 >