Why am I getting NameError?
<p>Here's a part of the the code I'm trying to run:</p>

<pre><code>def func1():
    a = True
    while a == True:
        try:
            guess = int(input("guess it: "))
            a = False
        except ValueError:
            print("Not a valid number.")

import random
number = random.randint(0, 50)
print("Im thinking of a number between 0 and 50,")

func1()

if guess == number:
    print("Perfect, you got it from the first try!")
</code></pre>

<p>I don't know why I get this: NameError: name 'guess' is not defined, even though I defined it in "func1"  </p>

<p>You're getting the error because <code>guess</code> only exists in the scope of <code>func1()</code>. You need to return the value <code>guess</code> from <code>func1()</code> to use it. </p>

<p>Like so:</p>

<pre><code>def func1():
    a = True
    while a == True:
        try:
            guess = int(input("guess it: "))
            a = False
        except ValueError:
            print("Not a valid number.")
    return guess # i'm returning the variable guess

import random
number = random.randint(0, 50)
print("Im thinking of a number between 0 and 50,")

guess = func1() # I'm assigning the value of guess to the global variable guess

if guess == number:
    print("Perfect, you got it from the first try!") 
</code></pre>

python python-3.5