How to accept the integer and float values in same input variable in python?

Question:

How to Accept the integer and float values in the same input variable in python

def interest_rate():
    while True:
        interest_rate = input("Enter the annual interest rates: ")
        if interest_rate.isdigit() == True:
            interest_rate = int(interest_rate)
            if interest_rate >= 0:
                break
            else:
                print("Please Enter the interest rate 0 or greater then 0")
        else:
            print("Please Enter A Number")
    return interest_rate
Asked By: Naveen

||

Answers:

The value returned from input() is a string <class ‘str’>. If you want to convert that to some numeric value you call int() or float() according to your needs. Do this in a try/except ValueError code block. Note that, for example, the string ‘1.5’ could be converted to float but ‘1.5’.isdigit() == False

Assuming you need a float then:

def interest_rate():
    while True:
        try:
            if (ir := float(input('Enter the annual interest rate: '))) < 0.0:
                raise ValueError('Please enter a value greater than or equal to zero')
            return ir
        except ValueError as _e:
            print(_e)

print(interest_rate())
Answered By: OldBill