Lesson-8: Python Global and local variables, RETURN Command

Python Global and local variables, RETURN Command

RETURN Command

In Python, some of the functions perform only one function, and the task ends there. But some functions return a value. Returns the value
functions include the expression” return”. Just because a function prints text on the screen does not mean that it returns a value. If the output of a function can be assigned to an appropriate variable, this function is a function that returns a value.

def func(sayı1,sayı2):
    x=sayı1*sayı2
    return x

a=func(4,5)
a=a*20+8
print(a)

In the example above, a function called func is created. In the main body of the program, this function is called by assigning it to a variable.

a=func(4,5)

the func function is called with two parameters, and the function works. In the employee function, the variable x was created and the value x was sent to the main body with the return x command just below it. In this way, the variable a in the main body has the value of multiplying number1 and number2.

Global and local variables:

The value of each variable is valid in its own function. A variable created within the function can also not be used in the main body of the mast. In the following example:

a=1
def fonksiyon():
    print ("Value of a =",a)
    b=2

fonksiyon()
print (b)

IT GIVES AN ERROR!!!

In the example above, I will talk about 2 important rules. First, variable a is created in the main body of the program (global variable), and a value of 1 is assigned to it. We can easily use this variable a in the function.

But the second rule is that variable b (local variable) created in the function cannot be used in the main body of the program below. The above command lines return the error code when it runs. This is because Variable b is a local variable and is valid within its own function.

So let’s repeat these 2 rules.
1-the main body can also be used in the created variable function.
2-if it is a variable created within the focus, the main body cannot be used.

There is actually a command to use. A variable that is local can be converted to a GLOBAL variable using the GLOBAL command. See the example below:

a=1
def fonksiyon():
    global b
    print ("Value of a =",a)
    b=2

fonksiyon()
print (b)

the global b command returns a variable created in the function to GLOBAL. So we could easily use the main body.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *