1

in part of one program i wanted to ensure that user inputs only so i used:

num=int(raw_input()) while type(num)!= int: num=int(raw_input('You must enter number only')) print num 

But by doing this , if the user inputted some non-integer like strings or anything else the whole code is displayed error. so how can i make user re-enter the value until they input an integer.

the output was like:

input your number hdhe --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-2-4b5e9a275ca4> in <module>() 1 print'input your number' ----> 2 num=int(raw_input()) 3 while type(num)!= int: 4 num=int(raw_input('You must enter number only')) 5 print num ValueError: invalid literal for int() with base 10: 'hdhe' 
1
  • 1
    Just delete the int() when defining num : num = raw_input() Commented Aug 16, 2020 at 13:02

4 Answers 4

2
while True: try: n = int(input('input your number : ')) break except ValueError: print('You entered a non integer value, try again.') continue print('yay!! you gave the correct value as int') 

Now you can do any cosmetic changes as you please.

Happy coding.

Sign up to request clarification or add additional context in comments.

Comments

0

Your num = int(raw_input()) has already ensured it must be an int and would raise ValueError if not int. So your while loop never gets to execute because it'll never get a non-int variable for num. Instead remove int() from the num variable and your good to go!

Comments

0

You can use isinstance to check whether the input is intor not.

if input is not int loop until the user enters int.

For instance:

num = input("Enter an integer:") if not isinstance(num, int): while not isinstance(num, int): try: num = int(input('You must enter integer only')) except ValueError as ve: pass 

Out:

Enter an integer:e You must enter integer onlyr You must enter integer onlye You must enter integer only4 Process finished with exit code 0 

Comments

0

You cast the input from the user directly to int on line 2. If this is not an integer a ValueError exception is thrown. We can modify your implementation and catch the exception when this happens, only exiting the loop when no exception occurs and num is an integer.

while True: num=raw_input() try: num=int(num) break except ValueError: print "Input is not an integer!" print num 

You might also be able to use a regular expression to check if the input value is an integer, or some other library function that checks whether the string from raw_input() is an integer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.