Solomon Kim
Solomon Kim

Reputation: 11

Why is the if statement in my function not working?

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.

Upvotes: 0

Views: 67

Answers (2)

Satyam S
Satyam S

Reputation: 23

Instead assigning the value you can directly print.

print(positivepoints(sumdiceroll, 1))

Upvotes: 0

Patrick
Patrick

Reputation: 1191

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)

Upvotes: 1

Related Questions