A variable's scope is the part of the program that the variable is visible to.
In Python, a scope can be local to a function or global (visible everywhere).
Furthermore, scope may also be limited within a function - e.g., you can't use a variable before you've assigned something to it
Parameters are local to the function they're defined in.
import csv
def calculate_pay(wage,hours):
if hours <= 40:
pay = wage*hours
else:
overtime_hours = hours-40
pay = (wage*40) + (wage*1.5*overtime_hours)
return pay
def user_pay_calculator():
hourly_wage = float(input("Enter your hourly wage: "))
num_hours = float(input("Enter your number of hours worked: "))
#calculate_pay(hourly_wage,num_hours)
#print(pay) #won't work
print("Your total pay is",calculate_pay(hourly_wage,num_hours))
user_pay_calculator()
wage, hours, overtime_hours, pay are all local to the calculate_pay() function
You can't use pay inside user_pay_calculator()
Similarly, hourly_wage couldn't be used in calculate_pay()
Global variables are weird
num_students = 350 #this variable is global because it is defined outside of a function
def first_grade_classroom():
print(num_students)
def second_grade_classroom():
print(num_students)
first_grade_classroom()
second_grade_classroom()
num_students = 350 #this variable is global because it is defined outside of a function
def first_grade_classroom():
num_students = 30 #this is actually now a local variable with the same name as the global variable!
print(num_students)
def second_grade_classroom():
print(num_students)
first_grade_classroom()
second_grade_classroom()
If you really want to change a global variable inside a function, you have to use the global keyword.
num_students = 350 #this variable is global because it is defined outside of a function
def first_grade_classroom():
global num_students #here, we tell it to really use the global variable
num_students = 30
print(num_students)
def second_grade_classroom():
print(num_students)
first_grade_classroom()
second_grade_classroom()
But, you really shouldn't do this. Changing global variables inside of functions makes programs extremely difficult to debug.
If you need the same variable in multiple functions, it is better to pass it as an argument or return it.
It's best to have all your code be in functions, except
import csv
OVERTIME_THRESHOLD = 40
def calculate_pay(wage,hours):
if hours <= OVERTIME_THRESHOLD:
pay = wage*hours
else:
overtime_hours = hours-OVERTIME_THRESHOLD
pay = (wage*OVERTIME_THRESHOLD) + (wage*1.5*overtime_hours)
return pay
def user_pay_calculator():
hourly_wage = float(input("Enter your hourly wage: "))
num_hours = float(input("Enter your number of hours worked: "))
print("Your total pay is",calculate_pay(hourly_wage,num_hours))
user_pay_calculator()