2
def Interface():
     Number = input("Enter number: ")

Interface()
print(Number)

This is a small simplified snippet of my code which produces:

Traceback (most recent call last):
  File "C:/Users/Jack/Documents/Python/NumberToText.py", line 78, in 
    print(Number)
NameError: name 'Number' is not defined

I underdstand this is because the variable is defined in a function.

What can I do to fix this?

  • Well, actually I've seen some question like this about three times. And most of them got lot's of downvotes. But this one got three upvotes and none of downvotes now. Could someone tell me why? – Remi Guan Oct 01 '15 at 08:46
  • 1
    Perharps becuase of the way I asked it. @KevinGuan – Oliver Murfett Oct 01 '15 at 10:32

2 Answers2

5

It depends on what you want to do.

Probably making the Interface function return Number would be the easiest solution

def interface():
     number = input("Enter number: ")
     return number

print(interface())

Please see this SO QA on the topic of scope rules in python

Note: as you can see, I have converted the names of the function and the variable to lowercase, following the PEP-8 guideline

Community
  • 1
  • 1
Pynchia
  • 10,996
  • 5
  • 34
  • 43
1

Because variable Number only belongs function Interface(). You can use return like this:

def Interface():
     number = int(input("Enter number: "))
     # remember use int() function if you wish user enter a number

     return(number)

print(Interface())

or use global just like this:

def Interface():
     global number
     number = input("Enter number: ")
     # remember use int() function if you wish user enter a number

Interface()
print(number)

And only use global when you need the variable can use at everywhere or you need the function return other things. Because modifying globals will breaks modularity.

Here is the document about what is global variable.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87