2

Here's a part of the the code I'm trying to run:

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!")

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

idjaw
  • 25,487
  • 7
  • 64
  • 83
  • 5
    `guess` is a local name in the `func1` function, which means it d oesn't exist *outside* of that function. The `if` statement is never reached because you have a programming error. – Martijn Pieters Sep 10 '16 at 16:26
  • You may want to [re-read the Python tutorial on functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions). If you want to share the `guess` value with the rest of your program, you need to `return` that value. – Martijn Pieters Sep 10 '16 at 16:27
  • Thank you sir, Much appreciated. – うちわ 密か Sep 10 '16 at 16:33

1 Answers1

1

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

Like so:

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!") 
idjaw
  • 25,487
  • 7
  • 64
  • 83
Christian Dean
  • 22,138
  • 7
  • 54
  • 87