0

I am trying to understand how global variables impact. Consider the below code as example

person = "Dave"
def display(person):
    global i 
    i = "Jack"
    print("here is ",person) 
display(person) 
display(i)

This results to:
here is Dave
here is Jack

I need to understand how "here is Jack" is printed

The below code results in error that i is not defined.

person = "Dave"
def display(person):
    global i 
    i = "Jack"
    print("here is ",person) 
display(i)

I don't understand this as well.

Please favour.

2 Answers 2

1

@Gayathri, the first thing is that global keyword is used to refer the global variables declared in the program or to declare any variable as global which is going to appear inside function block (as in your case).

Let you please understand the difference between following 2 code samples.

» Using global keyword:

i = 10;

def func():
    global i;
    i = 20; # Modifying global i
    print(i); # 20

print(i); # 10
func();
print(i); # 20

» Without using global keyword:

i = 10;
def func():
    i = 20; # It won't modify global i, here i is local to func()
    print(i); # 20

print(i); # 10
func(); 
print(i); # 10

Now, let's focus on the main problem.

✓ In first case, the value of local person in def display(person): is "Dave" and it is printing here is Dave & after that it is creating global i and setting its value to 'Jack'. In second call i.e. display(i) is passing the set value Jack of i which is assigned to local person variable available in def display(person): and therefore it is printing here is Jack and no error.

enter image description here

✓ In second case, no explicit assignment or function call for setting value of i before function call display(i) therefore there's an error.

Sign up to request clarification or add additional context in comments.

4 Comments

I wonder how value of variable ' i ' can be set as value of variable ' person '.
@Gayathri, please check answer again. I have updated it with a picture and let me know if you still have any issues. Thanks for commenting back. I appreciate your interest.
Thanks for the clarity , Rishikesh!
No problem @Gayathri. Enjoy Python. Good luck.
1

On the second example, when you call display, i is not defined yet, but in the first example, as you had called display before, i is defined and have a value. If you change the order in the first example, it won't work also.

i is only defined after a display has been called.

2 Comments

Thanks for your reasoning but still I wonder how value of variable ' i ' can be set as value of variable ' person '
Got it. Thanks Bruno!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.