0

I am learning python and was writing this game, where the program picks a random number and asks the user to guess the number. In this case, a user can enter an empty string or an alphabet by mistake. So, i felt the need to check the type of the user input before doing the comparison as shown below. Also, this lead me to the following stackoverflow entry Checking whether a variable is an integer or not

My question is why checking of types is considered a bad practice and how can i accomplish my task by not checking the type?

import random

num =  random.randint(1,10)

while True:
    guess = input('Guess a number between 1 and 10: ')
    if(bool(guess)):
            try:
                    guess = int(guess)
            except:
                    print("Please enter a numeric value")
                    continue
    else:
            print("you have to enter some number")
            continue
    if guess == num:
            print("you guessed it right")
            break
    elif guess < num:
            print("Try higher")
    elif guess > num:
            print("Try lower")
Community
  • 1
  • 1
Jimm
  • 8,165
  • 16
  • 69
  • 118
  • 3
    You aren't checking for any types in your above code, it's fine. – simonzack Dec 28 '13 at 18:12
  • You're not checking the type here, you're converting from a string to an integer which is ok. Checking the type would mean using `isinstance(guess, int)`, for example. And this is bad practice because it leaves you without the benefits of OOP. – Mihai Maruseac Dec 28 '13 at 18:12
  • first ask for forgiveness than for permission- as the linked post told you! Why should you check if it is an integer, if you must (should) integrate exceptionhandling... – LPH Dec 28 '13 at 18:16

2 Answers2

1

As the comments have stated, at no point do you check the type. What you do is validate and convert the input, which is appropriate for this program (and indeed, should be used in any program that accepts user input).

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Try this instead:

import random

num = random.randint(1, 10)
while True:
    try:
        guess = int(input('Guess a number between 1 and 10: '))
        if guess == num:
            print('You have guessed the correct number')
            break
        if guess < num:
            print('Try higher.')
        else:
            print('Try lower.')
    except ValueError:
        print('Please enter a number.')

The idea is that simply converting the input and handling the error leads to much cleaner code. In Python circles, checking the type via isinstance is known as Look Before You Leap which is discouraged. Just attempt the operation in question and handle the failure case (usually by exception handling). This is termed Easier to Ask Forgiveness than Permission.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113