0
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?

Benjamin
  • 11,560
  • 13
  • 70
  • 119
arij asad
  • 1
  • 2

2 Answers2

1

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.

Alex K
  • 8,269
  • 9
  • 39
  • 57
0

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'
Remi Guan
  • 21,506
  • 17
  • 64
  • 87