I’m new to coding and am working on a text RPG. I’ve been able to get it able to tell me whether or not I have a random encounter, but not what I come across. I am trying to add an encounter table with 2d6 and am having trouble understanding "if" statements and how to check between a range of numbers.
import random
Encounter = 5
d20 = random.randint(1,20)
print("your d20 rolled a" , d20)
d6 = random.randint(1,6)
#print("your d6 rolled a" , d6)
d6x2 = d6 + random.randint(1,6)
print("you rolled a", d6x2, "on two d6")
if Encounter >= 5:
if d20 >= 10:
print("You have an encounter!")
if d6x2 == (2,5):
print("A guard catches you trying to escape!")
elif d6x2 == (6,8):
print("Thank goodness, it's just a rat.")
elif d6x2 == (9,12):
print("Oh great, another prisoner. I wonder if he wants to join you...")
elif d20 < 10:
print("You got lucky and don't have an encounter")
else:
print("You don't have an encounter")
Even though d6x2 is returning values in the ranges stated the encounter text isn’t printing. I’m not sure what I’m doing wrong here and have had a really had time trying to word my question while looking elsewhere on the internet so I’m sorry if this doesn’t make much sense. Why won’t the "if" and "elif" text print?
I have tried changing if d6x2 == (2,5):
to if d6x2 == range(2,5)
but I’m sure I’m using that function wrong.
>Solution :
d6x2
is a single integer and it can never be equal to a tuple ((2, 5)
) or a range (range(2, 5)
). You should either use mathematical inequalities:
if 2 <= d6x2 <= 5:
or the in
operator with range
:
if d6x2 in range(2, 6):