MBM February 2016

Python 3.5.1 Introduction to Python 2.1 Mark Clarkson - While Loop Issue

I'm working my way through this set of tutorials. In section 3.2a - While Loops the following code is supposed to loop until the user enters the target number (7) then display a congratulations message however regardless of what number is entered Python either gives a right answer or a wrong answer, even 7 will sometimes flag a wrong answer. I know there are other ways to perform this sort of task but I would like to get the code from the tutorial working.

targetNumber = 7
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
    print("Wrong, try again ")
    guess = input("Guess a number between 1 and 10 ")
    print("Congratulations - that's right!")

Answers


James Scholes February 2016

Python's input function (or raw_input in Python 2.x) returns a string entered by the user. targetNumber, on the other hand, is an integer. In the Python Interpreter, try:

>>> 7 == "7"
False

You need to cast the user's input to an integer first.

try:
    guess = int(input("Please enter a number: "))
except ValueError:
    print("That is not a valid number!")


alpha1554 February 2016

You should convert the target numger to an string before comparison. Also, you should exclude the congratulations message from the loop. I would suggest :

targetNumber = str(7)
guess = input("Guess a number between 1 and 10 ")
while guess != targetNumber:
    print("Wrong, try again ")
    guess = input("Guess a number between 1 and 10 ")
print("Congratulations - that's right!")

The detail is that input returns a string and if you compare a string to an integer, it will always return false.

Post Status

Asked in February 2016
Viewed 3,905 times
Voted 10
Answered 2 times

Search




Leave an answer