Home > Software design >  Greater than or less than values not working in if statement
Greater than or less than values not working in if statement

Time:12-08

I am having some issues with a piece of test code I was working on. I am still new and I am sorry if it's confusing for you. I was trying to make a little dice game were if you got the higher value, you would win. But every time it will just say I won and I don't know why. I am sorry if it's obvious, I just couldn't seem to figure it out.

mylist = {"Yes", "Sure", "yes", "sure"}
mylist2 = {"No", "Nope", "no", "nope"}

print("Dice game test")

def opponent():
    opponent = random.randint(1,6)
    return(f'He rolled a {opponent}')
o = opponent()

def player():
    player = random.randint(1,6)
    return(f'You rolled a {player}')
p = player()

answer = input("Ready to roll?")
if answer in mylist:
    if (p > o):
        print(f'{p} and {o}. You won, Test complete')
    elif (o > p):
        print(f'{p} and {o}. You lost, Test complete')
    elif (p == o):
        print(f'{p} and {o}. You got a tie, Test Complete')
    else:
        print("An error occurred")
else:
    print("Wrong input")

Basically it seems to only ever tell me I won even if the number that shows in the text for player is smaller than the opponents. I was just needing to figure out how get it to display the numbers correctly and match up with the win or lose text.

CodePudding user response:

Your problem is that you return a string and not the random int.

Your code should look like this:

mylist = {"Yes", "Sure", "yes", "sure"}
mylist2 = {"No", "Nope", "no", "nope"}

print("Dice game test")

def getopponent():
    opp = 4
    print(f'He rolled a {opp}')
    return opp
o = getopponent()

def getplayer():
    player = 1
    print(f'You rolled a {player}')
    return player
p = getplayer()

answer = input("Ready to roll?")
if answer in mylist:
    if (p > o):
        print(f'{p} and {o}. You won, Test complete')
    elif (o > p):
        print(f'{p} and {o}. You lost, Test complete')
    elif (p == o):
       print(f'{p} and {o}. You got a tie, Test Complete')
    else:
        print("An error occurred")
else:
    print("Wrong input")
  • Related