Search code examples
pythonmathnumbersstructureconventions

How to use numerical conditions in python?


Sorry for my noobness but I've never really used math in python. My goal is to create a dice rolling game.

def roll_dice():
    print("You rolled a " + str(random.randint(1,6)))

if dice == "1":
    roll_dice()

etc for as many as 3 dice. I need to know how to set winning conditions. I'm not sure how to get the code to know the numbers it rolled if they're random. I want the code to say something like

#this is under the 1 dice block
if value == >5():
    print ("You win")
elif value == <5():
    print ("Sorry, try again.")  

#This is under 2 dice
if value == >8,12<:
    print ("You win!")

etc etc, that^ isn't really my code, just an example of what I am trying to convey. For dice_roll using 1 dice, I want the winning condition for the dice to have rolled at least a 5, and for the 2nd dice roll to roll between 8 and 12 etc, but as you can see, I don't know how to compare the "value" to what number is randomly generated, nor do I know the proper conventions for if # is less than or greater than stuff. And would it be easier if I changed dice roll 2's values to 7-12 rather than rolling a dice with a 1-6 value twice?


Solution

  • Just set the value equal to your randint:

    value = random.randint(1,6)
    value2 = random.randint(1,6)
    
    def roll_dice():
        print(f"You rolled a {value}")
    
    if value > x:
        # Do smth
    if value == x:
        # Do smth
    if value >= x:
        # Do smth
    if value <= x:
        #Do smth
    if value != x:
        #Do smth
    if y <= value < x and value2 != z:
        #Do smth
    

    x,y and z are arbitrary constants

    Here are all the normal (non-bitwise) comparison operators in Python.