S
S
Semyon Petrenko2016-01-09 18:25:18
Python
Semyon Petrenko, 2016-01-09 18:25:18

What is the error (why is the function exiting 5 and not 7)?

f71412ff417746a
x=5
def funA(x,y):
x=7
return x
funA(x,4)
print x

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abs0lut, 2016-01-09
@Pogremix

Read about references, objects, variable scope, and how to pass parameters to a function.
What we see in the code: we
created an object with the value "5" and assigned a reference to it to the variable "x"

def funA(x,y):
        x=7
        return x

created a function with two parameters
in the body of the function introduced a local variable "x"
as a result returned a local variable
called the function with parameters 5 and 4
printed a non-local variable "x"
And now the answer to your question:
At the exit from the function just 7
>>> x=5

>>> def funA(x,y):
      x = 7
      return x

>>> funA(x,4)
7

And what you took for the "exit" of the function is just the variable "x", which has no idea about your function, what is happening inside it and what is returned

D
Dimonchik, 2016-01-09
@dimonchik2013

or
or

def funA(y):
    global x
    x = 7
    return y

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question