-4

How does the code below give the output as None?

def funct(x):
    x=7

x=11
x=test(x)
print(x)

Here is another code snippet:-

def func():
    print (x)
    x = 90

x = 1
func()

The output for this should be 90! The scope is searched as Local ,Enclosed , Global ,Build-in .Either x should here be searched as local or global Please explain.

Community
  • 1
  • 1
YoDO
  • 93
  • 1
  • 7
  • 1
    Something went wrong with your code formatting. Consult [Markdown help - Code and Preformatted Text](http://stackoverflow.com/editing-help#code) and [edit] your post. – Kevin Apr 05 '17 at 17:51

2 Answers2

1

x here is not a global variable in the scope of the functions, as functions naturally create their own namespaces, which do not include any outer variables not passed in as a parameter.

There are many issues with your code, including the order of function calling, and the order of the operations inside the functions; but to answer your question in the broadest way possible, in order for you to access the x variable defined outside of your functions, in a greater scope that is, you need to reference its namespace, by prepending global x inside the body of each of your functions.

Read up on Python variables and scope, and recheck the other errors in your code I have stated above.

Ziyad Edher
  • 2,150
  • 18
  • 31
0

The first code snippet returns None for the simple fact that you didn't return any value from the function. You defined x as a local parameter, not a global variable. Since you didn't return any value, your call test(x) (which does not match the function name of funct), will become a value of None. This is clearly defined in the Python documentation. To get the local value back to your main program, try this:

test(x):
    x = 7
    return x

x = 11
x = test(x)
print(x)

Also, please note that your initial value of 11 is entirely ignored in the main program, and that your function ignores the value it's given. You should shorten this example to

func():
    return 7

print(func())

Your second example will print the external value of 1 because you have not defined a local variable x at that point, and a function is allowed to reference global variables.

However, when you assign a value in the next, you create a local variable -- you have not declared x to be global, so you can't assign to the x in the main program.

Again, you do not return any value. Therefore, back in the main program, func() evaluates to None.

Does that clear up what happened?

Prune
  • 76,765
  • 14
  • 60
  • 81