0

I have a question concerning int(). Part of my Python codes looks like this

string = input('Enter your number:')
n = int(string)
print n

So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.

I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.

Thanks!

Greenhill
  • 113
  • 5
  • 2
    Possible duplicate: http://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number – Phillip K May 12 '17 at 06:42
  • 2
    Possible duplicate of [How to check if string input is a number?](http://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) – Chiheb Nexus May 12 '17 at 06:45

5 Answers5

2

You can use try except

while True:
    try:
        string = input('Enter your number:')
        n = int(string)
        print n
        break
    except ValueError:
        pass
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
1

Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
0
n = None
while not isinstance(n, int):
    try:
        n = int(input('Enter your number:'))
    except:
        print('NAN')
Vetsin
  • 2,245
  • 1
  • 20
  • 24
  • You are catching a very broad exception. Somehow input console is corrupted that will stuck in a infinite loop. – Adnan Umer May 12 '17 at 12:42
0

What you're looking for is

Try / Except

How it works:

try:
    # Code to "try".
except:
    # If there's an error, trap the exception and continue.
    continue

For your scenario:

def GetInput():
    try:
        string = input('Enter your number:') 
        n = int(string) 
        print n
    except:
        # Try to get input again.
        GetInput()
Joe
  • 159
  • 3
  • 14
0

While the others have mentioned that you can use the following method,

try :
except :

This is another way to do the same thing.

while True : 
    string = input('Enter your number:')
    if string.isdigit() : 
        n = int(string)
        print n
        break
     else : 
        print("You have not entered a valid number. Re-enter the number")

You can learn more about Built-in String Functions from here.

dsrinivas
  • 1
  • 1