1

I started learning python. I learned that a function cannot use values if they are not defined as parameters, but I was practicing and made a little program calling a function without parameters and it works. I don't understand why does it works, can someone please explain why does the program works?

Here is the code:

def sum():
   return x + y

x = 10
y = 20
print("Total: ", sum())
wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

1

When the names x and y aren't found in the local scope of sum, Python looks in the containing namespace, which is the global scope, where it finds them.

Further reading: Short description of the scoping rules?


By the way, note that child scopes can't modify parent scopes, so this fails:

def foo():
    x += 1

x = 1
foo()
print(x)
Traceback (most recent call last):
  File "tmp.py", line 5, in <module>
    foo()
  File "tmp.py", line 2, in foo
    x += 1
UnboundLocalError: local variable 'x' referenced before assignment

There are ways of getting around this, but it's better if you don't. See for example: Are global variables bad?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Oh my.

I found the answer, because there is no parameter passed to the function. Python considers that x and y are global variables, that is why it can make the operation and print the total.

Sorry for bothering you guys, and thanks.

  • Using global variables to pass arguments to functions is legal, but don't do it unless you really have to. You really want to write `def sum(x, y)` and pass `x` and `y` as arguments. You will eventually want to name your function something else, since Python defines a function named `sum` and you might want to use it. – Frank Yellin Sep 18 '21 at 02:27
  • learning python involves a lot of running code. it's riddled with exceptions that take longer to look up than cause and catch through test runs. – Abel Sep 18 '21 at 02:28
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 18 '21 at 03:05
  • Thanks for your explanations guys. :) – DummyPerson Sep 18 '21 at 22:51