[Python] Why are variables not available to a sub-function on run? [duplicate]

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    This script defines a variable inside main(), but the variable isn't available to func(), which runs inside main(). Why is that?

    #!/usr/bin/env python3
    # vars_in_func.py
    # Test script for variables within a function.

    def func():
    print(greeting)

    def main():
    greeting = "Hello world"
    func()

    main()


    Error:

    Traceback (most recent call last):
    File "./vars_in_func.py", line 11, in <module>
    main()
    File "./vars_in_func.py", line 9, in main
    func()
    File "./vars_in_func.py", line 5, in func
    print(greeting)
    NameError: name 'greeting' is not defined


    If I convert the script to Python2, the error is the same, except it says global name instead of name.

    I assume I'm just missing a key concept. I just started learning Python after learning Bash.

    Edit: After reading the answers, I realized my mistake: I'm still thinking in terms of Bash, where functions either run in the same shell as the caller (with the same variables), or a subshell of the caller (inherited variables).

    Continue reading...

Compartilhe esta Página