Comparing int variables

I am trying to create some code that simulates the rolling of a stamp. I want the code to stop when it rolls 1, but my program keeps right on rolling that dies.

import random

def rollDie(die):
    die = random.randint(1,6)
    print(die)

die1 = 0

while die1 != 1:
    rollDie(die1)

      

My suspicion is that my code is comparing object id 1 and object id die1. As far as I can tell, "! =" Is an appropriate "not equal" comparison operator.

So what am I doing wrong and how do I compare the values โ€‹โ€‹of a variable as opposed to their object id?

+3


source to share


1 answer


You need to update the value of die1, the easiest way to use your function is to go back into the function and assign the return value to die1:

def rollDie():
    return random.randint(1,6)

die1 = 0

while die1 != 1:
    die1 = rollDie()
    print(die1)

      



die1 = rollDie()

will update every time through the loop, your code always keeps die1

its initial value 0

.

ints are immutable , so passing die1

to a function and setting die = random.randint(1,6)

won't change the original object, it will create a new object.

+3


source







All Articles