Change language

Why does Python function not work? Specify the scope in Python

|

Let's imagine a situation. You have written a function, initialised the variables somewhere and are about to test your code.

You have succeeded, the code runs without errors, but the problem is that the function does not do the right thing, or, more precisely, it returns a value you don't want. On top of that, you don't even know how it happens. The variables are in place, the function structure is fine, what is the reason?

You may have used the scope incorrectly. Let's look at an example:

list_sqrt = [2,4,6,8,10]
def Sum():
  list_sqrt = [i*i for i in list_sqrt]
  print(list_sqrt)
if __name__ == '__main__':
  Sum()

Briefly about the code: there is a list with numbers, with the help of the function we need to make the numbers in the same list, be squared. Let's try to understand what the function feels at compile time: "Master, in line 6 where the list inclusion happens, in the loop, the temporary variable doesn't understand who it goes by.

We can conclude that the temporary variable, i, iterates, or rather does not iterate at all, according to an undefined sequence. But from another place in the code, we see that we have the right sequence (line 2). So why doesn't the function do what we need it to do, or, more precisely, doesn't do it at all? It's all about the scope.

The code defined a global sequence and a function that uses a local sequence, i.e. the one that is to be used and distributed within the scope of the function.

Briefly. The code tries to use the local sequence in the function - as a local sequence. That is where the error lies.

How to make it local? Because without it, it cannot be used in the function? In a word - global.

Let's take a look at the following code:

list_sqrt = [2,4,6,8,10]
def Sum():
  global list_sqrt
  list_sqrt = [i*i for i in list_sqrt]
  print(list_sqrt)

if __name__ == '__main__':
  Sum()

There is one new element in line 6, but the sequence is still the same. Now in the code, the list appears as a global list and goes beyond the boundaries of the function, and the output is as follows:

[4, 16, 36, 64, 100]

You may have the following question: but if the sequence was global in the code before, but after adding global it is still global, even though the function needed a local list, what is this gibberish?

It's simple. The list was and is indeed global. But we all know that a function is a separate code block, like a base for the favorites. And since the list globality extends to exactly the same parts of (empty) code and does not intrude into functions and classes, or simply separate blocks, it does not work.

And if in a block (in our case, a function), designate the sequence as global not only for space in the code, but also in the desired block, the boundaries of the function collapse, and the door is opened for the chosen global. And the sequence becomes available inside the given block.

Bottom line

Don't forget about scope, it's often the reason why functions don't return what you want.

Here I didn't go deep into the subject and simply described everything in my own words. In addition, I link to a small documentation on this topic.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically