1

I want to execute specific code if an input value is an integer. If the user enters an integer, specific code should be executed. Otherwise, it should show an error explaining that the input value is not an integer and prompt again for input. This should happen until an integer is entered or the program is terminated.

Here's my code:

print('Hello, what is your name?')
name = input()
print('Hello ' + name + ', I am thinking of a number between 1 to 20.
    Please take a guess.')

inputNumber = input()

if inputNumber == int: # Check if inputNumber is an integer
    # Run specific code
else:
    print('Please enter the int')
    # Prompt again
Eric Reed
  • 377
  • 1
  • 6
  • 21
  • So what's your question? The code appears to be almost correct. – Carcigenicate Aug 23 '17 at 13:22
  • 7
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Steven Laan Aug 23 '17 at 13:24

4 Answers4

3

You need to try to cast it into integer assuming the input given by user is integer and then proceed further, in your code snippet input() function takes input from the user and converts it into string See Documentation therefore if b == int: will always give you false.

Correct procedure:

import random
print('Hello , What is your name')
name = input()
print('hello ' + name + ' i am thinking a number between 1 to 20. Please take a guess')
while(True):
    try:
        inputNumber = int(input())
        # now it is sure that input number is integer.
        ### CODE

    except ValueError:
        print('please enter the int')

here I have updated as per infinite loop but you can modify as per your code logic something like while(inputNumber != randomNumber) but for this you will need to take the input from user before the while loop starts something like :

import random
print('Hello , What is your name')
name = input()
print('hello ' + name + ' i am thinking a number between 1 to 20. Please take a guess')

randomNumber = random.randint(1,21)
try:
    inputNumber = int(input())
except ValueError:
    print('please enter int only')
while(inputNumber != randomNumber):
    try:
        print('try again!')
        inputNumber = int(input())
        # now it is sure that input number is integer.

        if (inputNumber == randomNumber):
            print('correct')
            break

    except ValueError:
        print('please enter the int')
warl0ck
  • 3,356
  • 4
  • 27
  • 57
  • Yes correct but how to take execution back to step where user have to input again. if user enter a string value except section will run , but what i want that if input is not a integer it should prompt again user to input. – Dilip Kr. Sharma Aug 23 '17 at 13:56
  • well you can put the try catch code in `while loop` – warl0ck Aug 23 '17 at 13:56
1

It makes for a bit more interactive a game with feedback if your guess was too high or low.

import random
lower = 1
upper = 20
rand  = random.randint(lower,upper)

name = input('Hello , What is your name? ')

entered = input('hello %s i am thinking a number from %s to %s. Please take a guess: ' % (name, lower, upper))

while True:
    try:
        guess = int(entered)
        if   guess > rand:
            print('Lower!')
        elif guess < rand:
            print('Higher!')
        elif guess == rand:
            break
    except:
        print('You did not enter a valid integer!')

    entered = input('Try again: ')

print('Congratulations! You guessed correctly!')
Evan
  • 2,120
  • 1
  • 15
  • 20
  • please execute your self. 1st TRY block is not executing properly ,2nd how can you put multiple if to check same condition , it should elif . – Dilip Kr. Sharma Aug 23 '17 at 14:20
  • This code works fine on my machine. Also, those are separate if statements and python has no problem with you making as many as you'd like. A small inefficiency and not pythonic, but it does not impact this program in any meaningful way. Just fixed regardless. If you still have an error, post it here and we can work through it. – Evan Aug 23 '17 at 14:22
0

Thanks everyone for helping me, Specially Warlock & Evan. I am pasting code here just to confirm that problem is resolved.

  ##This the guess the number.
  import random
  print('Hello , What is your name')
  name = input()
  print('hello '+ name +' i am thinking a number between 1 to 20. Please take a guess')
  guess = random.randint(1,10)

  while True:

        try :
              inputNumber = int(input())

              if inputNumber > guess :
                    print('Lower!')
              elif inputNumber < guess :
                    print('Higher!')
              elif inputNumber == guess :
                    print('Well Done, Its a Correct Guess')
                    break

        except:
              print('Enter a number dear')

  print('Thanks for playing')
-2

You can put your code (including the if) in a while loop. Something like this:

invalidInput = True
while invalidInput:

   # Ask for user input

   if (test_if_user_input_is_valid) :
      invalidInput = False
      # Rest of the code

   else:
      # Ask the user for the right format. This takes back to the beginning of while loop
  • I just kept his original code and tested for a boolean. Edited to remove original code if that's the issue. Honest question: What's wrong with using `while` here? – Marcelo Vital Aug 23 '17 at 17:20
  • I was talking about the inputNumber == int . That will always return false I think. – SH7890 Aug 23 '17 at 17:24
  • Agree, that's not the right way for testing for ints. Just copied from original code and didn't notice – Marcelo Vital Aug 23 '17 at 17:25