[Tutor] "Guess My Number" Python 3.4.0 Program partially fixed but now has Logic Errors

Peter Otten __peter__ at web.de
Wed Apr 30 00:38:43 CEST 2014


Stephen Mik wrote:

> Stephen Mik-novice programmer-getting desperate

Don't despair just yet! As a programmer you will be constantly producing and 
fixing errors. That is business as usual.
What will change is that you will produce trickier bugs as your knowledge 
level increases...

> Dear Sir(s):
> I am new to Python programming,and I have a "Guess My Number" program
> which partially works. The main while control works,the guessing of an
> integer between 1 and 60 seems to give the "too high" or "too low" elif
> branches effectively. However,when the correct number is guessed the
> "elif" for the Congratulatory Message does not print out,and the number of
> attempts at guessing the mystery number does not print out. Instead, the
> program apparently goes into the main while control loop again and queries
> the User if they want to run the program again. I have attached a sample
> Python Shell run;along with code fragments of the relevant areas.
> Anybody,please help me work out this code and get "Guess My Number"
> correctly running. CONCERNED,Stephen W. Mik

Look at that loop once more:
 
>   while(smv_guessNumber!=smv_pickNumber): 
>      if (smv_guessNumber > smv_pickNumber): 
>        print("Guess of mystery number Too high,enter a lesser number: \n") 
>        smv_attemptCounter+=1 
>      elif (smv_guessNumber < smv_pickNumber): 
>        print("Guess of mystery number Too Low.Enter a greater number \n") 
>        smv_attemptCounter+=1 
>      elif (smv_guessNumber == smv_pickNumber): 
>        #Print Congratulatory Message,the mystery number,the number of 
attempts 
>        print("Congratulations! You have guessed the mystery number") 
[...]
>     smv_guessNumber=int(input("Take a new guess!")) 
  

Here's a simplified version:

while x != y:
    if ...
    elif ...
    elif x == y:
        print("congratulations")
    x = int(input())

Can you see now why the print statement cannot be reached? 
If x == y were true x != y would be false, and the loop would already have 
been terminated.

The easiest fix is to move the congratulations out of the loop:

while x != y:
    if x > y: ...
    elif x < y: ... # see note 1
    x = int(input())

print("congratulations") # at this point you can be sure that
                         # x == y. Otherwise the loop would still
                         # be running.


Note 1: you do not actually need the test here as you know that

x != y and (not x > y)

so that there's no other option than x < y.



More information about the Tutor mailing list