lslak
lslak

Reputation: 105

Comparing variables of int

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

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 the object Id of 1 and the object Id of die1. As far as I can tell "!=" is the appropriate "not equal to" compare operator.

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

Upvotes: 3

Views: 51

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You need to update the value of die1, the easiest way using your function is to return in 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 each time through the loop, your code always keeps die1 at it's initial value 0.

ints are immutable so passing die1 to the function andsetting die = random.randint(1,6) would not change the original object, it creates a new object.

Upvotes: 3

Related Questions