2

I have created a simple function on python and make some tests with the debugger to see how it works.

I wanted to print the value of a variable (raiz):

(dbg) p raiz

But it says that it's not defined. Why is this? Here is my code:

import math
def funcion(sen):
    raiz = math.sqrt(sen)
    return "the sqrt of " + repr(sen) + 'is ' + repr(raiz)

print (funcion(38))

import pudb;
pudb.set_trace()
AJF
  • 11,767
  • 2
  • 37
  • 64
JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

2 Answers2

1

Your variable is declared inside the function, not outside, so the code can't see it.

If you need to set value for outside variable, mark it with global keyword (which is a bad practice):

import math

raiz = None

def funcion(sen):
    nonlocal raiz
    raiz = math.sqrt(sen)
    return "the sqrt of " + repr(sen) + 'is ' + repr(raiz)

funcion(38)
print (raiz)

Also you can use nonlocal keyword, but for this case it would fail with:

SyntaxError: no binding for nonlocal 'raiz' found

You can find a tutorial about local, nonlocal and global keywords here.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125
0

This is to do with Scope.

The place that variables are defined is important, and defining them in certain places will cause them to disappear elsewhere. Here is an example:

# PLEASE NOTE: This code will fail.
a = "Hello"

def my_func():
   b = "Hello" # Declare a variable 'b', but only in this scope, in other words this function.

my_func()

print(a) # Works, since a is in the same scope.
print(b) # Fails, since b was defined inside a different scope, and discarded later.

Since, in your example, raiz was declared inside the function funcion, Python discarded it after funcion was called. If you put the line:

raiz = 0

before your function definition, the function would simply update the variable, so there would be no issue, since the scope would be the same as where the print statement occurs.

tl;dr: The variable raiz was declared only in funcion, so it was discarded afterwards.

Community
  • 1
  • 1
AJF
  • 11,767
  • 2
  • 37
  • 64