# Good namesdef calculate_total(): passdef send_email(): passdef validate_password(): pass# Bad namesdef func1(): # Not descriptive passdef Calculate(): # Should be lowercase pass
To change a global variable inside a function, use the global keyword:
Copy
counter = 0 # Global variabledef increment(): global counter # Declare we want to modify the global variable counter += 1increment()increment()print(counter) # 2
Avoid using global when possible. It makes code harder to understand and debug. Instead, pass values as parameters and return results.
# Bad - using global variabletotal = 0def add_to_total(amount): global total total += amount# Good - using parameters and returndef add_amounts(current_total, amount): return current_total + amounttotal = 0total = add_amounts(total, 10)total = add_amounts(total, 20)print(total) # 30
When a local and global variable have the same name, the local variable “shadows” the global one inside the function. Python always uses the local version first.