Baba.S
Baba.S

Reputation: 354

Do variables created within a function get global scope?

I have a simple function containing a loop that calculates how money grows per year with interest, which got me thinking about scope and variables in Python.

def invest(amount, rate, years):
    for i in range(years):
        amount = amount + amount*rate
        print(f"year {i+1}: ${amount:.2f}")


invest(100, 0.05, 4)

The output:

year 1: $105.00
year 2: $110.25
year 3: $115.76
year 4: $121.55

I know it works, but usually I would create the 'amount' variable above the for loop to ensure that after each iteration, that variable will get updated. Since I didn't do that this time, I assume that this variable gets created globally so that happens automatically.

Are my assumptions correct? Thank you

Upvotes: 1

Views: 54

Answers (2)

Andressa Cabistani
Andressa Cabistani

Reputation: 483

The answer above already satisfy what you asked, but I think the following link might be good for your learning, as it was good for mine. In Python Tutor you can put your code and visualize what happens inside the global scope, functions' scopes, etc. Hope this can help you!

Upvotes: 1

chevybow
chevybow

Reputation: 11888

If it was global then you would be able to access it outside the function. The scope of the variable is limited to that specific function.

You can also create another intermediate variable above the loop but it wouldn't change much about the function- you don't need the original value of amount in your function so for your purposes- using that variable and updating it directly in your loop is fine.

Upvotes: 4

Related Questions