arij asad
arij asad

Reputation: 1

How do i change the value of a variable but from inside a function?

p = input(":")
def c (p):
    p = "cat"
    return p 

print(c(p))

print(p) #how do i make this p be cat

Is there a way to do this?

Upvotes: 0

Views: 50

Answers (2)

Remi Guan
Remi Guan

Reputation: 22302

Another way that you can use global to define or change a global variable inside a function like this:

p = input(":")
def c (p):
    global p
    p = "cat"  # now the `p` become 'cat'
    return p 

print(c(p)) 
print(p)  # it's 'cat'

Upvotes: 0

Alex K
Alex K

Reputation: 8338

You have a scope issue here. You have this code:

p = input(":")
def c(p):
    p = "cat"
    return p 

While you could choose to use global, you could just more simply change the name of the variable that you pass in to something else. Currently, when you do p = "cat", the p you are referencing is the one INSIDE of the frame of your method, not the one in the global frame. If you change the name of the argument to be "z," then you'll be referencing the right p. So this would work:

p = input(":")
def c(z):
    p = "cat"
    return p 

You can read about frames and learn about how Python interacts with different frames at UC Berkeley's great online textbook for the introductory CS course: http://composingprograms.com/.

I recommend reading chapter 1, section 5 - it touches on ways to approach this problem.

Upvotes: 1

Related Questions