'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.
Solution 1:[1]
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)
Solution 2:[2]
Instead assigning the value you can directly print.
print(positivepoints(sumdiceroll, 1))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Satyam S |
