Reputation: 53
I made an object and a variable outside a function but I am able to use it inside a function I was just messing around the code and I noticed this ps I was trying to make a linked list
this is the rest of the code I cant add another image here
ll=Linkedlist()
first=Node(1)
Second=Node(2)
Third=Node(3)
ll.head=first
first.next=Second
Second.next=Third
ll.tail=Third
x=4
def display():
ll.trav()
print(x)
display()
my question now is how am I able to use ll
and x=4
in the function display
when both are defined outside the function
Upvotes: 1
Views: 127
Reputation: 16906
Official docs here
Sample (comments inline)
x = 123
def fun_1():
# gloabl x, can read it but cannot overwrite it
print ("fun_1\t", id(x), x)
def fun_2():
# local x, can read/write
x = 0
print ("fun_2\t", id(x), x)
def fun_3():
# Global x, can read/write into it
global x
x = 0
print ("fun_3\t", id(x), x)
print ("main\t", id(x), x)
fun_1()
print ("main\t", id(x), x)
fun_2()
print ("main\t", id(x), x)
fun_3()
print ("main\t", id(x), x)
Output:
main 94861900917056 123
fun_1 94861900917056 123
main 94861900917056 123
fun_2 94861900913120 0
main 94861900917056 123
fun_3 94861900913120 0
main 94861900913120 0
Not that method calls on object are not overwriting the object but rather changing the some internal state. i.e obj.do_something(...)
only changes the internal state of obj
but the object pointed bu obj
is still same which, so it is not an overwrite operation.
Upvotes: 1
Reputation: 748
The other answer tells you how to do it in another way (the way you have done it is also not wrong, as is proved by its working). However it doesn't answer the question
how am I able to use ll and x=4 in the function display when both are defined outside the function
The answer to this is from another post: link
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
Upvotes: 2
Reputation: 21
If you just want to use ll and x in display(), you just pass them as parameters :
def display(xParam, llParam):
llParam.trav()
print(xParam)
display(x, ll)
Upvotes: 0