Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Q on functions
#1
Hi,

Can someone please explain how the sample variable is passed onto the function?

I understand if it would be sample_func(sample) but sample_func() with no data? Think

TIA

def sample_func(): # or def sample_func(*args):
    print(sample * sample)


for sample in range(1, 5):
    sample_func()
Reply
#2
It isn't passed to the function; it's basically a global. Perhaps you should read about scope and the LEGB rule, e.g. here.

Note: this question seems to have nothing to do with *args.
Reply
#3
If a variable is only read in a function (not written to), then the function will search for a variable in an enclosing scope, or in global scope.

sample is assigned in the for loop, so it's a global variable, and sample_func() will use that value when reading from that variable.
Reply
#4
Ok so, if I've over 5.000 lines of codes with several variables, sample_func() can pickup any of them?
Reply
#5
No, some of those lines are probably other functions. If the variable is local to that other function, it can't be accessed.

def other_func():
    l = 20    # l is local to other_func

def func():
    print(g)  # g is global.  Can print
    print(l)  # l is not global or local to this function.  Error

g=10
func()
Reply
#6
Understood, thank you.
Reply
#7
(Sep-18-2020, 08:34 AM)ebolisa Wrote: Hi,

Can someone please explain how the sample variable is passed onto the function?

I understand if it would be sample_func(sample) but sample_func() with no data? Think

TIA

def sample_func(): # or def sample_func(*args):
    print(sample * sample)


for sample in range(1, 5):
    sample_func()
Though this code works it is a horrible way to write code. You have already identified the problem. In "sample_func()" where is "sample" coming from? To find out I have to search through the code for "sample" and see where it is set relative to a call to "sample_func()". Not only does this make the code difficult to maintain, it also severely limits the usefulness of "sample_func()". This is the problem with functions referencing variables outside the function's scope, there is too much dependency on the caller. This makes the function hard to use and really hard to re-use.
Reply
#8
I'm not using it. I put it together to help me to get an answer to my question. Thanks.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020