Home > front end >  I used a function and the return value is different from what the function actually returns when I c
I used a function and the return value is different from what the function actually returns when I c

Time:04-03

function problem

def playerguess(guess):
    guess=0
    while guess not in [1,2,3]:
        guess=int(input('Guess 1,2 or 3:      '))
    return guess

playerguess(guess)
print(guess)

I tried to make the guess=1 and the function made it to 1 but when i checked the guess value it's 0

CodePudding user response:

first guess is a local variable or a global variable if it is a global variable use declare outside of the function scope and use global keyword in the function playerguess().

I'm assuming that guess is not a global variable so the second. snipped that could solve your issue.

second see that while is checking that guess values is in the array [1,2,3] and you have declare and assigned guess with 0 you always will received 0 as return values because guess variable.

something simple you could do is using flags variable:

def playerguess():
    guess=0
    cap = True
    while cap:
        guess=int(input('Guess 1,2 or 3:      '))
        if guess not in [1,2,3]:
            cap = False
    return guess

g= playerguess()
print(g)

CodePudding user response:

Python doesn't handle arguments passed in to functions the way you are expecting. It passes arguments by assignment, which is different than pass-by-reference in C or Java. Importantly, you can't change the value of an argument (by rebinding it, rather than mutating it in place) and see that change outside of the function.

Here's a simpler example that doesn't confuse things with a return value:

def foo(x):
    x  = 1

y = 1
foo(y)
print(y)

This code prints 1, since the foo function can't rebind the variable y in the global namespace. The = operator in the function only rebinds x, which is a local variable. You can remove the function entirely, and do the assignment, just like the interpreter does:

y = 1
x = y    # this is equivalent to passing y as an argument to foo
x  = 1   # this is equivalent to the code in the function
print(y) # prints 1

The only substantive difference between this example and your code is that you're using the same name for the global variable and the local variable in your function. That can work, since they're different namespaces.

Probably you don't want to be passing any arguments to your guess function. Just get rid of it, and assign the value returned by the function to something.

guess = playerGuess()
  • Related