def print_sum():
a = 100
b = 200
result = a + b
Inside print('print_sum() : ', a, ' and', b, 'the sum of ', result, '. ' )
a = 10
b = 20
print_sum()
result = a + b
Print ('print_sum() External: ', a, 'and', b, 'sum of' , result, '. ' )
Here
new a, b with variables in def referencing 100, 200 and 100, 200 Create Variables
and the variable outside def is
Generate a and b variables referring to 10 and 20
That's what he said.
In my opinion, the variable was created first in print_sum(), and then the a and b values of 10,20 were assigned outside, right? Doesn't the value of print_sum() change if a=10 and b=20 are assigned? Once defined, the defined variable value does not change, but does it need to change the variable value in def to change it? I'd appreciate it if you let me know! Have a great day!
python global-variable
The explanation is confusing. If you want to exchange information, please clarify the subject + verb (+ object) in all sentences.
If it's hard to write a sentence, you can use the number with me.
I don't have any education on Python. The reason I'm saying this is to let you know that I don't know exactly what terms like global variables, definitions, regional variables mean, and that's why it's impossible to explain it clearly.
It's based on my understanding that it's impossible for me to give a clear explanation of the term, and I looked at the example code and thought, "This is what this is."
# Script Example
a = 10
b = 20
c = a + b
#Example of regional variables
a = 10
b = 20
def print_sum():
a = 100
b = 200
c = a + b # 300
a = 10
b = 20
def ex():
a = 100
c = a + b # 120
For a function (print_sum), you can view it as follows:
a = 10
b = 20
def print_sum():
c = 100
d = 200
print(c, d)
del c
del d
You can take something declared outside of a function, but you've never seen something declared inside a function affect a variable outside of the function.
a = 20
def aa():
print(a)
aa()
print(a)
>> 20
20
def aa():
print(a)
a = 20
aa()
print(a)
>> 20
Traceback (most recent call last):
print(a)
NameError: name 'a' is not defined
a = 30
def aa():
a = 20
print(a)
aa()
print(a)
>> 20
30
Is the use of a and b different inside and outside the definition function? If you look at the answer you posted above, the variables in the definition can only affect (you don't even know if you declared a variable on the outside), and if you look at the code of my original question, it feels like a,b in the definition function is the same as the name, so it feels like a different variable. If you look at image 1, the last line refers to a separate object, not an object referenced by the regional variable, but isn't the global variable correct? We're not referring to objects outside of the definition function, we're writing objects that the local variable inside refers to
If there's anything wrong, can I ask you to correct it? Thanks to you, I'm getting a lot of help Thank you so much!
© 2024 OneMinuteCode. All rights reserved.