Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Check whether a whole number plus Numeric Numbe

anuraa

Legendary Coder
I need to verification for the following code and also, alternative ways to do.

1. Check whether it is a whole number

Code:
if round(number) != number:
    raise TypeError("Number is not a whole number")

2. Number is not numeric

Code:
try:
  total = total + number
except ValueError:
  raise TypeError("Number is not numeric")

Rather than catching as an exception, I would like to know how to check this with a an if condition as in above 1.

Thanks for helps
 
Solution
One way

Python:
def check(arg):
    if isinstance(arg, str) and arg.isdigit():
        print(f'{arg} is a whole number')
    elif isinstance(arg, int):
        print(f'{arg} is a whole number')
    else:
        print(f'{arg} is not a whole number')
check(5)
check(5.0)
check(6+3)
check('88')
check('6+4')
check('10.0')

Output
Code:
5 is a whole number
5.0 is not a whole number
9 is a whole number
88 is a whole number
6+4 is not a whole number
10.0 is not a whole number
One way

Python:
def check(arg):
    if isinstance(arg, str) and arg.isdigit():
        print(f'{arg} is a whole number')
    elif isinstance(arg, int):
        print(f'{arg} is a whole number')
    else:
        print(f'{arg} is not a whole number')
check(5)
check(5.0)
check(6+3)
check('88')
check('6+4')
check('10.0')

Output
Code:
5 is a whole number
5.0 is not a whole number
9 is a whole number
88 is a whole number
6+4 is not a whole number
10.0 is not a whole number
 
Last edited:
Solution
I agree 5.0 is a whole number but, python sees a float. It cound be rounded or some other method to remove the decimal and be made a whole number. As for the string 6+4, could probably spit the string and covert to int and then add and return the sum.
 
One way to check if a numeric value is a whole number is

Code:
if int(num) == num:

To check if a value can be converted to a numeric without using a "try" you can do

Code:
if type(value) in (int, float):
 
I got bored so I made a one-liner to do it. Sorry in advance (I formatted it to make it look nicer)...

Python:
from typing import Union


def check(num: Union[int, str]) -> str:
    return (
        "Whole number"
        if (
            num == round(num)
            if type(num) == float
            else [
                output := eval(num if type(num) == str else str(num)),
                output_type := type(output),
                output_type == int
                or (output_type == float and output == round(output)),
            ][-1]
        )
        else "Not whole number"
    )


print(
    check(5),
    check(5.0),
    check(6 + 3),
    check(6.3 + 3.6),
    check("5"),
    check("5.0"),
    check("6 + 3"),
    check("6.3 + 3.6"),
    sep="\n",
)
Output
Code:
Whole number
Whole number
Whole number
Not whole number
Whole number
Whole number
Whole number
Not whole number
 
Last edited:
I'm assuming you posted this for feedback.

"check" is a very non-descriptive name for a function. It should be renamed to something like "isWholeNum".

Your type hint on the def says it returns a boolean value, yet in line 3 you return "Whole number".

You don't need to import typing. There is a new syntax (see code)

"num == int(num)" is likely more efficient than "num == round(num)"

You did not include a doc string.

It is not obvious what the code is doing. Shorter is not always better. Clearer is better.

Code:
def isWholeNum(val: int | float | str) -> bool:
    """Returns True if <val> is
         1 - an integer value
         2 - a float that can be expressed as an integer value
         3 - a string that can be converted to an integer value"""

    if type(val) == int:
        result = True
    elif type(val) == float:
        result = val == int(val)
    else:
        try:
            num = float(val)
            result = num == int(num)
        except ValueError:
            result = False

    return result

There is probably a clearer way to express this using the new "match" construct but I'm not up to speed on that yet. But if we are using a try/except we might as well just do:

Code:
def isWholeNum(val) -> bool:
    """Returns True if <val> is
         1 - an integer value
         2 - anything that can be expressed as an integer value"""

    try:
        num = float(val)
        result = num == int(num)
    except ValueError:
        result = False

    return result
 
Last edited:
A basic example of the case use. Doesn't handle operations if in a string such as 6+2

Python:
def wholenumber(arg):
    match arg:
        case int(arg):
            return True
        case float(arg):
            return False
        case str(arg):
            if arg.isdigit() and type(int(arg)) == int:
                return True
            else:
                return False
       
if wholenumber(5.2):
    print('is whole number')

else:
    print('not whole number')
 
Last edited:
I'm assuming you posted this for feedback.

"check" is a very non-descriptive name for a function. It should be renamed to something like "isWholeNum".

Your type hint on the def says it returns a boolean value, yet in line 3 you return "Whole number".

You don't need to import typing. There is a new syntax (see code)

"num == int(num)" is likely more efficient than "num == round(num)"

You did not include a doc string.

It is not obvious what the code is doing. Shorter is not always better. Clearer is better.

Code:
def isWholeNum(val: int | float | str) -> bool:
    """Returns True if <val> is
         1 - an integer value
         2 - a float that can be expressed as an integer value
         3 - a string that can be converted to an integer value"""

    if type(val) == int:
        result = True
    elif type(val) == float:
        result = val == int(val)
    else:
        try:
            num = float(val)
            result = num == int(num)
        except ValueError:
            result = False

    return result

There is probably a clearer way to express this using the new "match" construct but I'm not up to speed on that yet. But if we are using a try/except we might as well just do:

Code:
def isWholeNum(val) -> bool:
    """Returns True if <val> is
         1 - an integer value
         2 - anything that can be expressed as an integer value"""

    try:
        num = float(val)
        result = num == int(num)
    except ValueError:
        result = False

    return result
1) I wrote the code because I wanted to challenge myself. The question had already been solved, and so I didn't mean for it to be useful.
2) Yes check isn't the best name.
3) I use pypy which is at Python 3.9 and the feature was added in Python 3.10. But I know what you mean.
4) True, but micro-adjustments weren't on my mind.
5) No one else has included one.
6) I specifically said I got bored so I made a one-liner to do it. Sorry in advance. So I didn't mean to make it easy to understand.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom