I am trying to write a program which accepts multiple inputs from user and do whatever is required but i don't want the program execution stop when user gives some error in the input rather i would like that line of program to be repeated again and again until the user gives a valid input or cancel the operation.
For example i have the following piece of program :-
# Error handling
i=int(eval(input("Enter an integer: " )))
print(i)
Now if the user enters a string following error is occurs :
Enter an integer: helllo
Traceback (most recent call last):
File "C:/Users/Gaurav's PC/Python/Error Management.py", line 2, in <module>
i=int(input("Enter an integer: " ))
ValueError: invalid literal for int() with base 10: 'helllo'
HERE, I want Python to re-run the line 2 only for a valid input until user inputs a correct input or cancel the operation and once a correct input is passed it should continue from line 3, How can i do that?
I have tried a bit about it using try and except statement but their are many possible errors and i cannot find a way to run that line again without re-writing it in the except block and that too works for one error or the number of times i copy the same code in the except block.
You can put it in a while loop and check to see if an an input is an integer or not:
def is_integer(s):
try:
int(s)
return True
except ValueError:
return False
while True:
i = input("Enter an integer: " )
if is_integer(i):
print(i)
break
Try :
while True:
try:
i = int(input("Enter number : "))
break
except:
continue
Or you can use pass instead of continue.
Related
Is there a way to make an exception for the same error if the previous exception raises an error? I know this example doesn't make sense, but it's the easiest way to demonstrate what I mean. For example:
import string
a = input('')
try:
print(str(int(a)+1))
except ValueError:
print(string.punctuation.index(a))
Is there a way to work it so if it isn't a number, it goes to except ValueError to run if it is in string.punctuation, but then if that raises a ValueError then it goes to another except ValueError to say that it isn't a number or symbol? etc. something like this but in a code that works:
import string
a = input('')
try:
print(str(int(a)+1))
except ValueError:
print(string.punctuation.index(a))
except ValueError:
print('Not a number or symbol!')
You'll need another try block within the except to catch the second ValueError.
import string
a = input() # no need for an empty arg
try:
print(int(a) + 1) # no need for explicit str conversion
except ValueError:
try:
print(string.punctuation.index(a))
except ValueError:
print('Not a number or symbol!')
I wanted to know how to hide errors in python:
Let's say I made a calculator and then typed:
if number1 != int:
print("NaN")
But it will print this message and give out the error which is built into python which is:
Traceback (most recent call last):
but how do I hide this Traceback error and only show the error message which is "NaN"
Thank you for the answer.
Even though you are talking about try...except, the following statement makes no sense.
You telling python to compare 1 to data type int
if number1 != int: print("NaN")
If you want to check a particular data type, use isinstance(<variable>,<data type>)
if isinstance(number1,int): print("NaN")
You can use try...except method to catch various errors:
try:
number1=int(input("Enter a number: "))
...
except ValueError:
print("NaN")
Note that this will catch only ValueError. If you want to catch all errors, use except Exception or except:
To "hide" a Error message (NameError) you can try the following, but this is only because number1 is not defined:
try:
if number1 != int: print("NaN")
except NameError:
print("Error is hidden!")
except:
print("Catch all other Exceptions!")
For more see the following link.
I think you want to check if the inserted numer is not an integer. This can be done with the following code:
number = "asdf"
if type(number) != int:
print("NaN")
else:
print("Valid number!")
import math
r=input("Please enter the radius")
h=input("Please enter the height")
def cone_area(r,h):
while True:
try:
r,h = float(r),float(h)
break
except ValueError:
return 'Error not a number'
a=((math.pi*r*(r+math.sqrt(r*r+h*h)))) # surface area formula
return round(a,4)
print(cone_area(r,h))
Here is the full error message:
Please enter the radius ↩
Error ↩
Traceback (most recent call last):
File "__tester__.python3", line 3, in <module>
r=input("Please enter the radius") #asks user for radius and height
EOFError: EOF when reading a line
For clarification, it works fine using python idle but I have to submit this for work into an online python interpreter which is where I get the error message. Another user also confirmed they could replicate this on linux. Where did I go wrong in my code?
Use try except to solve this problem
try:
print(input())
except EOFError:
exit()
Extra:
the while True: can be removed to increase efficient a bit.
Full code:
import math
def cone_area(r,h):
try:
r,h = float(r),float(h)
except ValueError:
return 'Error not a number'
a=((math.pi*r*(r+math.sqrt(r*r+h*h)))) # surface area formula
return round(a,4)
try:
while True: #infinity amount of input until EOF
r=input("Please enter the radius")
h=input("Please enter the height")
print(cone_area(r,h))
except EOFError:
print("input finish")
Why does my program work in PyCharm but in online interpreter gives this error:
Traceback (most recent call last): File "Solution.py", line 4, in
s = input() EOFError: EOF when reading a line
Here's the part of code that matters:
i = 0
while True:
s = input()
if s == '':
break
else:
...
I'm trying to input strings until empty string occurs but it always gets stuck on line with empty string.
Thanks in advance and sorry if I'm sloppy with my question (my 1st question).
Perhaps you can handle there exception with try and except:
while True:
try:
s = input()
...
except EOFError:
break
...
I am doing some practice problems from online with python and I have a question about how to stay in a script if an error is raised. For example, I want to read in values from prompt and compare them to a set integer value inside the script. The only problem is that when someone enters something other than a number 'int(value)' (ex. value = 'fs') raises an error and exits the script. I want to have it so if this happens I stay inside the script and ask for another value to be entered at the prompt.
Use try/except.
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
success = false
while not success:
try:
value = raw_input('please enter an integer')
int(value)
success = true
except:
pass
How about catching it?
try:
a = int('aaa')
except ValueError:
print('Still working')
Ah, you just want to catch the error (as long as it isn't final): see http://docs.python.org/tutorial/errors.html for details? Or are you looking for something else?
for this, you use try... except as explained in the python documentation
Read up on the try: except: idiom here
if you are doing it as a function you can do it as a decorator of the function
def retry(func):
def wrapper(*args,**kwargs):
while True:
try:
return func(*args,**kwargs)
except Exception as e:
print(f"{e} running again") # or simply pass
return wrapper
#retry
def myfunction():
if badthinghappend:
raise Error
return something