0

I'm struggling to code an if-statement series for an arbitrary and stupid game I designed called 'guessing game'. What should I add so that one loop compares the previous and the current answer and show it on console?

import random
    
listte = range(1, 21) # list contains 1-20
number = random.choice(listte) # computer generated number from the list
    
for i in range(3):
    answer = int(input("What is your guess?"))
    prevanswer = None # I came up with this but not really working?
    if answer == number:
        print "You got it!"
    elif answer < number:
        print "Nope, higher"
    # this elif is not working with below codes
    elif answer < number and answer > prevanswer:
        print "still higher"
    elif answer > number:
        print "lower!"
    prevanswer = i # also not working but this is what I came up with

An example execution scenario:

computer generated : 15

guess 1 : 17
prints "lower!"

guess 2: 10
print "make it higher"

guess 3: 12
print "still higher" 
0

1 Answer 1

2

First, move the setting of prevanswer = None to before the loop. Otherwise, you're erasing the memory of what went before.

Second, take a look at your if/elsif code sequence. You have the right tests, but in the wrong order:

elif answer < number:

This will execute EVERY TIME answer is less than number. Below that you have:

elif answer < number and answer > prevanswer:

This is "good" code, in the sense that it should accomplish what you seem to want. But this is a MORE RESTRICTED case than the earlier one. That is, whenever answer < number, only SOMETIMES will answer > prevanswer. So you should check for the subset of possibilities BEFORE the general case of all answer < number.

Try this:

elif answer < number and answer > prevanswer:  # specific case
    ...
elif answer < number: # general case

And finally, don't set

prevanswer = i

but rather

prevanswer = answer
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.