2

One of my students brought this to my attention in his coursework. I've re-written what happened below (but is not the same as the coursework):

def tester(number):

    print(number)    
    numbertotal = num1 + num2
    print(numbertotal)

number = input("Input a number: ")
num1 = 2
num2 = 2
tester("number")

Output:

Input a number: 12

number

4

How does the num1 and num2 get up into the function? All I do is pass it the string "number" and it prints that. It does then correctly add 2 and 2, which doesn't make any sense since I don't pass that function either number. I do pass the "number" variable so it does work to pass to but is also just so happens that num1 and num2 are available up there anyway. Does Python now make all variables global now? Even so it shouldn't work... Please help!

1

3 Answers 3

2

Python resolve variable name at runtime, so when your tester function is called, num1 and num2 have already been defined.

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

1 Comment

Thank you for your reply. I see what you mean. Why don't I have to pass it up there though? Shouldn't I have to say "tester(num1,num2)"?
0

Looking at the output of locals() and globals() will clarify this.

Comments

0

The variables are global, so it makes no difference to the function, any part of the program can 'see' them.

I guess this showcases my point just right.

def func(GLOBAL):
    print (GLOBAL)

GLOBAL = 64

func(32)      # <-- localvar naming overrides global
func(GLOBAL)  # <-- this one does what you'd expect

6 Comments

Replying you @mr-archard above, because I don't have enough rep. There'd be a couple of problems with calling tester(n1,n2): firstly, it expects only one variable. If, however, you fix the function to def tester(n1, n2): numbertotal = n1 + n2, then it does the expected thing.
If at the bottom you put "print(numbertotal)" it says that numbertotal is not defined as it is in the function. That variable isn't global so how can num1 and num2 be? Or is that because numbertotal is declared in the function and is therefore local?
Yes of course. Good point. As you say then it would do the expected thing. If all variables are available globally then why does the option to pass a function a variable exist? Or is that for when you send variables from function to function?
That's because numbertotal is only visible inside the function, and therefore local. Correct.
And, referring to your second comment, declaring everything as global is a waste of computing resources since it never gets dealocatted from memory. Not having functions being able to be passed or return variables would turn modern-day programming into line-by-line instructions and lots of copy-pasting.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.