-1

Okay so this is the code im testing and it simply doesnt work. Python says my x is not defined even though my set_x should set x to a value. What am I missing?

def hi():
    print(x)

def set_x1():
    x = "hello"
    hi()

def set_x2():
    x = "world"
    hi()

set_x1()
set_x2()
Panup Pong
  • 1,871
  • 2
  • 22
  • 44

2 Answers2

1

Closer to your original code, just pass the variable:

def hi(x):
    print(x)

def set_x1():
    x = "hello"
    hi(x)

def set_x2():
    x = "world"
    hi(x)

set_x1()
set_x2()

It's all to do with your hello function not being able to see what's inside the x variable in other functions, which we know as a local variable. Here's a good lecture that tells you what's going on behind the code: https://www.youtube.com/watch?v=_AEJHKGk9ns

Paul Brown
  • 2,235
  • 12
  • 18
0

You shouldn't set x in a local scope. You could return a value instead (and perhaps set x to that value):

def hi(x_arg):
    print(x_arg)

def x1():
    return "hello"

def x2():
    return "world"

x = x1()
hi(x)
x = x2()
hi(x)

In your original code, x is no longer defined when the function ends. Since it is local to the function's scope.

Another way for a function to affect the "outer world" would be to mutate a mutable object, but that's beyond our scope (see what I did there? :-) ... ).

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88