Home > Blockchain >  Python beginner help input error handling
Python beginner help input error handling

Time:11-24

I am just starting to learn Python and am trying to handle errors a user might input. All the program does is use the math module, asks the user for an integer and returns the factorial of the number.

I am trying to catch errors for negative numbers, floats and text.

If I enter an integer the code runs like it should.

When I enter a wrong value, like -9 or apple, the try/except seems to not catch the error and I get the traceback information. The user shouldn't see this.

Any suggestions or pointers?

import math
from datetime import datetime
import time

num = 0
start = 0
end = 0
# max value is 2147483647
#if __name__ == '__main__':
try:
    num = input("Enter a number: ")
except OverflowError:
    print("Input cannot exceed 2147483647")
except ValueError:
    print("Please enter a non-negative whole number")
except NameError:
    print("Must be an integer")
else:
    start = datetime.now()
    print("The factorial of ", num, " is : ")
    print(math.factorial(int(num)))
    end = datetime.now()
    print(f"Time taken in (hh:mm:ss.ms) is {end - start}")

I am using Python 3.10 on a Windows 10 Pro (64-bit) PC if that matters.

Norman

CodePudding user response:

That is because input() do not raise an error just because you want just a number. You have to check the type of input by yourself and then also raise an error by yourself. e.g.

if not isinstance("string", int):
    raise ValueError

edit: also have a look here for more information about input(): https://www.python-kurs.eu/python3_eingabe.php It always returns a string, so you have to convert your input actively in the type you want and make your type check during/after the conversion

CodePudding user response:

Your code is missing the operation which can cause the exception: in fact, input('...') returns a string representing whatever user inputs. This means that your num variable is a string (you can check by printing type(num).
You have to try to cast it into an integer:

try:
   num = int(input('...'))
except ValueError:
   print('invalid input')

Be carefull: if user input the value "-3", it will be accepted: the string will be cast into the integer -3 and this is correct.
If user inputs words like 'apple' or floats like 3.14, the exception raised is ValueError.
My suggest is to do something like this:

try:
   num = int(input('...'))
   if num >= 0:
      # computing factorial
   else:
      print('error: only positive numbers will be accepted')
      return
except ValueError:
   print('invalid input')
  • Related