The incomprehension of the scope of python and js variables

I have just learned python and encountered some problems about the scope of variables, as follows:

the following is not very clear

var a = 3
const f = () => {
    a += 4
    console.log(a)
}
a() // 7
f() // 7

in js , you can not only access global variables, but even modify global variables, so what"s the difference between scope mechanism and python in js ?

in addition, I have learned that js and python are static scopes, and the principle should be the same, but the results shown above are very different. Please give me a clear answer. I"m sorry for my lack of knowledge.


Let me explain it to you.
for the variables defined by var in python and js in the example, their scope rules are similar

  1. variable scope is within the function that defines it (the entire python or js file can be regarded as one large function)
  2. according to point 1: a variable with the same name as defined in the global appears within the function, and within the function, it overrides the global.

different points

    To define a variable in the
  1. js function, explicitly write var in front of the variable name (let's not discuss let and const), first, otherwise we will directly call the global
  2. .
  3. python defines a variable to write the variable name directly
  4. In the
  5. pyhton function, if you want to assign a global variable, you need to write the global variable name before the assignment.

based on the above premise knowledge, please see the explanation in the notes

Code of Python


python <br>a += 4 a = a + 4

a, a

js a

js var python

python a

a = 3
def f():
    global a // 
    a += 4
    print(a)
f()
The conversion from

python code to js code actually goes like this:

var a = 3;
const f = () => {
    var a;
    a += 4;
    console.log(a) // NaN js
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e45e03-59bba.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e45e03-59bba.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?