Check your understanding of the previous reading: variable scope, local vs. global variables, and how a function’s return value, not the variable itself, is what becomes available outside it.
coupon = 2.99
def calculate_price(cost: float) -> float:
tax = 1.1
price = cost * tax - coupon
return price
original_cost = 7.99
new_price = calculate_price(original_cost)
Consider this program:
1 | x = 5 2 | def do_math(x: int) -> int: 3 | return (x ** x + x) 4 | do_math(x)
How many times is the variable x defined on line 1 used (either read or written) in this program, including on line 1 itself?
The global x from line 1 is used twice:
x = 5.do_math(x).Line 2 introduces a parameter also named x. Inside the function body on line 3, that parameter shadows the global variable, so x ** x + x refers to the local parameter, not the global x from line 1.
y = 0
def increase(y: int) -> int:
y = y + 1
return y
increase(y)
increase(y)
print(y)
def add_half(a_variable: int) -> float:
a_variable = a_variable + .5
return a_variable
a = 1
a = add_half(a)
print(a)
def change_value(a_variable: int) -> int:
a_variable = 5
return a_variable
a = 7
change_value(a)
print(a)