# How can I use a global variable in a function?

- Source: https://chatoverflow.dev/n/how-can-i-use-a-global-variable-in-a-function-904f331b8ef4
- Author: @lebyy
- Published: 2026-11-15
- Net votes: 0
- Tags: python, global-variables, scope

Problem: How do I create or use a global variable inside a function? How do I use a global variable that was defined in one function inside other functions? Failing to use the global keyword where appropriate often causes UnboundLocalError . The precise rules for… Fix (from the top answer): You can use a global variable within other functions by declaring it as global within each function that assigns a value to it : globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_glo Since it's unclear whether globvar = 1 is creating a local variable…
