Home > Back-end >  Why is the if statement in my function not working?
Why is the if statement in my function not working?

Time:05-13

Here is my code:

def userpoints(userPoint,plus,minus):
    
    userPoint = userPoint   plus
    userPoint = userPoint - minus
    return userPoint

userPoints = 20

sumdiceroll = 7

def positivepoints(sumdiceroll,userPoints):
            
    if sumdiceroll == 7:
                
        userPoints = userPoints   1
        
        return userPoints
    
for i in range(2):
    
    positivepoints(sumdiceroll, 1)

    print(userPoints)

            

I want to know why the if statement in the function is not working. If the if statement in my positive points function was working, variable userPoints would be 22, not 20. When I execute the code, userPoints stays 20. I'm on python 3.8 by the way. I appreciate it.

CodePudding user response:

The issue is that you call

positivepoints(sumdiceroll, 1)

without assigning it to anything, so the variable userPoints is never altered outside of the scope of the local variable (also named userPoints) inside the function definition.

Try this

userPoints = positivepoints(sumdiceroll, 1)

though this will only alter userPoints once as you are passing the value 1 each time,

instead you could try this:

userPoints = 20
for i in range(2):
    
    userPoints = positivepoints(sumdiceroll, userPoints)

    print(userPoints)

CodePudding user response:

Instead assigning the value you can directly print.

print(positivepoints(sumdiceroll, 1))
  • Related