Week 3: Quiz: Question 1

The code snippet in question 1 is given below:

def temp():
    return b*b

b = 2
a=temp()
print(a)

Here b is declared after its use in the function that is defined above. Can you please explain how does this work in terms of the variables declaration and use in a sequence.
Also if you could throw some light on the scope of the variables?

Hi @Ashwin,
This behavior is due to the fact that temp() after a value is given to b.
Had it been like :

def temp():
    return b*b

a=temp()
b = 2
print(a)

The scenario would be different.

1 Like

Ok, so it does not matter if the function declaration is before the use of the variable. If the call of the function is before then it will be different.

Is it a fair statement?

What will happen in the above case?

Fair enough.
For the above case, b is used before definition… so there will be an error.

1 Like