4

Every time I try me code it works but when I type in 'stop' it gives me an error:

ValueError: invalid literal for int() with base 10: 'stop'

def guessingGame():
    global randomNum
    guessTry = 3

    while True:
        guess = input('Guess a Number between 1 - 10, You have 3 Tries, or Enter Stop:  ')
        if int(guess) == randomNum:
            print('Correct')
            break

        if int(guess) < randomNum:
            print('Too Low')
            guessTry = guessTry - 1
            print('You have, ' + str(guessTry) + ' Guesses Left')

        if int(guess) > randomNum:
            print('Too High')
            guessTry = guessTry - 1
            print('You have, ' + str(guessTry) + ' Guesses Left')

        if guessTry == 0:
            print('You have no more tries')
            return

        if str(guess) == 'stop' or str(guess) == 'Stop':
            break
martineau
  • 119,623
  • 25
  • 170
  • 301
Chris Pickett
  • 57
  • 1
  • 1
  • 5

3 Answers3

12

The string passed to int() should only contain digits:

>>> int("stop")
Traceback (most recent call last):
  File "<ipython-input-114-e5503af2dc1c>", line 1, in <module>
    int("stop")
ValueError: invalid literal for int() with base 10: 'stop'

A quick fix will be to use exception handling here:

def guessingGame():
    global randomNum
    global userScore
    guessTry = 3

    while True:
        guess = input('Guess a Number between 1 - 10, You have 3 Tries, or Enter Stop:  ')
        try:
            if int(guess) == randomNum:
                print('Correct')
                break

            if int(guess) < randomNum:
               print('Too Low')
               guessTry = guessTry - 1
               print('You have, ' + str(guessTry) + ' Guesses Left')

            if int(guess) > randomNum:
                print('Too High')
                guessTry = guessTry - 1
                print('You have, ' + str(guessTry) + ' Guesses Left')

            if guessTry == 0:
                print('You have no more tries')
                return
        except ValueError:
            #no need of str() here
            if guess.lower() == 'stop':
                break
guessingGame()

And you can use guess.lower() == 'stop' to match any uppercase-lowercase combination of "stop":

>>> "Stop".lower() == "stop"
True
>>> "SToP".lower() == "stop"
True
>>> "sTOp".lower() == "stop"
True
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • As per Andenthal's comment for the other answer, you could do `if guess.lower() == 'stop'` and catch all "stop" capitalization possibilities. – SethMMorton May 24 '13 at 19:51
  • 1
    FWIW, it would be better to not call `int` three times when one is enough, and to keep the try block as short as possible. – bruno desthuilliers May 24 '13 at 21:20
  • For the record, strings passed to `int()` may contain leading and trailing whitespace as well as digits. – martineau Oct 05 '16 at 20:29
1

Here's a more pythonic (Python 3) version.

def guessing_game(random_num):
    tries = 3
    print("Guess a number between 1 - 10, you have 3 tries, or type 'stop' to quit")

    while True:
        guess = input("Your number: ")
        try:
            guess = int(guess)
        except (TypeError, ValueError):
            if guess.lower()  == 'stop' :
                return
            else:
                print("Invalid value '%s'" % guess)
                continue

        if guess == random_num:
            print('Correct')
            return
        elif guess < random_num:
            print('Too low')
        else:
            print('Too high')

        tries -= 1
        if tries == 0:
            print('You have no more tries')
            return

        print('You have %s guesses left' % tries)
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

You are trying to convert the string "stop" to an integer. That string has no valid representation as an integer, so you get that error. You should put

if str(guess) == 'stop' or str(guess) == 'Stop':
break

as the first check

Another suggestion is to use lowercase on the input and then check for the lowercase 'stop'. That way you will have to check just once and it will capture either 'Stop', 'STOP', 'sTOp', etc..

if str(guess).lower() == 'stop':
break
Pablo Mescher
  • 26,057
  • 6
  • 30
  • 33
  • 1
    (not an error in your code, just a suggestion) Instead of checking for both lower and camel case, why not convert the string to lower/upper (since I assume you don't care about case sensitivity)? Then it will catch any of the following: 'stop', 'Stop', 'STOP', etc you get the idea `if str.lower(guess) == 'stop'` – Andenthal May 24 '13 at 19:44
  • @pablo: There's no such thing as a "cast" in Python. `int` is a type (a class) and `int(somestring)` instanciates a new int. – bruno desthuilliers May 24 '13 at 21:19