EX35 Study Drill 5 and More

How can I check if the input is int or floating point first, then convert whatever int/fp to an int?

Right now i’m using this:

if isinstance(eval(choice), (int, float)) == True:
how_much = int(choice)

however, after it checks True, I then cannot convert the input(how_much) to int.
It seems to be, along the way, the input string(e.g. ‘23.5’) becomes something else, so python throws me the error: “ValueError: invalid literal for int() with base 10: ‘23.5’.”

What should I do to fix this issue? or is there any simple/smarter way to achieve this goal (other than if “0” in choice or “1” in choice or … or if “9” in choice:)?

Thank you guys very much!:heart::heart::heart::heart:

That is a very good question. So, first thing is don’t do eval, that’s deadly. Someone could type python into the choice that also erases your hard drive. In a little game like this you wouldn’t do that, but if you don’t know about this then you’ll try to use eval all the time and one day get owned.

Now, then you have to be clear about the problem. Do you mean:

  1. Given a variable in python, figure out if it’s of type int or type float?
  2. Given a string I have to convert, figure out if it’s going to become an int or a float.

These are fairly different problems because, what you want in #1 is to just get a type so use isinstance(). But if what you want is #2 then that’s a whole huge can of worms that involves a regex or some tricky attempts at conversion.

Probably the most effective way is to first attempt to convert it to an int, and if that fails, then try to convert to a float, and if that fails, then it’s not a number at all. Take a look:

>>> x = "1.234"
>>> xi = int(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.234'
>>> xf = float(x)
>>> x = "1"
>>> xf = float(x)
>>> xi = int(x)

See how when I set x = "1.234" and then try to use int(x) it explodes? But trying to do float(x) works. Now if I set x = "1" then both float() and int() work, so that’s why the logic would work. Try to make an int, if that bombs then try to make a float, if that bombs then it’s neither:

   return int(choice)
except ValueError:
      return float(choice)
   except ValueError:
      return None

That’s just a rough outline you’ll have to develop further.

Thank you so much! Try Except is exactly what I need!
When I use
if isinstance(choice, (int, float)) == True:,
python seems always auto detects input content as string, no matter if it’s a number or not, which means it goes directly to else: every time. But Try Except solves it perfectly!:+1:
P.S: I learn eval from google, and thank you so much for the suggestion. Eval is deleted from my dictionary indefinitely.:laughing: