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!

2

5 Answers 5

2

You can use try except

while True:
    try:
        string = input('Enter your number:')
        n = int(string)
        print n
        break
    except ValueError:
        pass
3
  • You are missing a break somewhere :p Commented May 12, 2017 at 6:45
  • You are missing a : too. Also, you should try to avoid infinite while loops and give them a clever condition instead.
    – FMaz
    Commented May 12, 2017 at 7:07
  • Updated. Thank you both :)
    – itzMEonTV
    Commented May 12, 2017 at 7:16
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.

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()
1
  • This GetInput function does not return anything useful.
    – VPfB
    Commented May 12, 2017 at 18:46
0
n = None
while not isinstance(n, int):
    try:
        n = int(input('Enter your number:'))
    except:
        print('NAN')
1
  • You are catching a very broad exception. Somehow input console is corrupted that will stuck in a infinite loop.
    – Adnan Umer
    Commented May 12, 2017 at 12:42
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.