Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Greater than or less than values not working in if statement

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading