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

Here, we are writing Python code to create a library with functions to input the values with expectation handling.
Submitted by IncludeHelp, on February 18, 2021

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

Problem Solution:

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

Python exception handling programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.