Let'sCode
Let'sCode

Reputation: 55

Function giving a None value when it should output an integer

I'm writing a simple 'guess the number' game and wants the program to check if the input given is an integer before proceeding to compare it with the generated number. Here's the code:

import random

def guessFunc():
    try:
        guess1 = int(input())
        return guess1
    except ValueError:
        print('Input an integer!')
        guessFunc()

secretNumber = random.randint(1,20)
for guessTaken in range(1,7):
    print('Guess a number. You have ' + str(7 - guessTaken) + ' guesses left.')

    guess = guessFunc()

    if guess < secretNumber:
        print('Too low')
    elif guess > secretNumber:
        print('Too high')
    else:
        break

if guess == secretNumber:
    print('You got it! You took ' + str(guessTaken) + ' guesses.')
else:
    print('The number is ' + str(secretNumber))

When I test the program, if I always input an integer, the program runs as expected. If I input anything else (a string for instance), it sends a message asking for an integer, which is also expected. But if I then input an integer, the program causes an error as follow:

if guess < secretNumber:

TypeError: unorderable types: NoneType() < int()

I don't understand why the function is outputting a None value. It only happens when I first input a string followed by an integer.

Separately, is there a cleaner/neater way to write the code to check whether the input is an integer in this case?

Upvotes: 0

Views: 174

Answers (1)

Jorick Spitzen
Jorick Spitzen

Reputation: 1639

Your 'recursive' call in line 9 guessFunc() is not being returned, it's just being called. If you change that to return guessFunc() it works.

With regards to your question about checking for integers, your way is actually a very Pythonic way of doing it. Instead of checking whether or not the input is an integer, which would take time always, you assume it's an integer and handle the exception when something goes wrong, which takes time only when something goes wrong.

Upvotes: 3

Related Questions