Q:

Create a library with functions to input the values with exception handling in Python

belongs to collection: Python Exception Handling Programs

0

Create a Python library with the function to input the values with expectation handling and demonstrate with the example.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Here, we are creating a Python library "MyLib.py" with two functions,

  • GetInt() – To input the integer number.
  • GetFloat() – To input the float number.

When we input the values other than integer/float the ValueError will occur, this error is also being handled in the functions.

Then, we are creating a main file "Main.py", where we are reading and printing the values.

MyLib.py:

def GetInt(msg):
 while(True):
  try:
     k = int(input(msg))
     return k
  except ValueError as e:
    print("Input Integer Only...")

def GetFloat(msg):
 while(True):
  try:
     k = float(input(msg))
     return k
  except ValueError as e:
    print("Input Real Number Only...")

Main.py:

import  MyLib

k=MyLib.GetInt("Enter First Number: ")
print("First numbe is: ",k);

j=MyLib.GetInt("Enter Second Number: ")
print("Second number is: ",j);

Output:

RUN 1:
Enter First Number: 10
First numbe is:  10
Enter Second Number: 20
Second number is:  20

RUN 2:
Enter First Number: 10
First numbe is:  10
Enter Second Number: 20.3
Input Integer Only...
Enter Second Number: Hello
Input Integer Only...
Enter Second Number: 20
Second number is:  20

RUN 3:
Enter First Number: 123Hello
Input Integer Only...
Enter First Number: 12.34
Input Integer Only... 
Enter First Number: 20
First numbe is:  20 
Enter Second Number: 30
Second number is:  30

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

IndexError Exception in Python with Example... >>
<< Add two integers only with Exception Handling in P...