0

i'm new to python and started programming a simple calculator.

Now i want my calculator to recognize if the number entered is a float or int and answer accordingly.

so after they typed in the input for both numbers they want to add

n1 = (input("Geben Sie ihre erste Nummer ein: "))
n2 = (input("Geben Sie ihre zweite Nummer ein: "))

is there any way to check if the variables n1 and n2 are a float or integer and make a if statement for the right answer.

so for example if n1 = 2 and n2 = 4 the answer is 6, but if n1 = 2.3 and n2 = 4.2 the answer would be 6.5

I really hope you understand what i'm trying to say because i i certaintly don't.

Have a wonderful day.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
serdar
  • 1
  • 1
    As the input will be returned as a string, this should answer your question: https://stackoverflow.com/questions/46647744/checking-to-see-if-a-string-is-an-integer-or-float or https://stackoverflow.com/questions/15357422/python-determine-if-a-string-should-be-converted-into-int-or-float – ksbg Sep 28 '22 at 10:45
  • is `1e0` an int? Python wouldn't recognise it as an int, but it's just another way of saying the number one (i.e. an integer expressed in scientific notation). Another way of asking this is, do you care about Python's syntactic rules or numeric rules from maths – Sam Mason Sep 28 '22 at 10:48
  • Does this answer your question? [Checking to see if a string is an integer or float](https://stackoverflow.com/questions/46647744/checking-to-see-if-a-string-is-an-integer-or-float) – Robert Sep 28 '22 at 14:12

1 Answers1

0

You first need to transform the string returned by 'input' into a number:

try:
   n1 = int(n1)
except ValueError:
   try:
      n1 = float(n1)
   except ValueError:
      # n1 isn't even a number

There is a more advanced but more pretty solution:

parsed_n1 = None
with contextlib.suppress(ValueError):
   # first try it as a float
   parsed_n1 = float(n1)
   # float parsing succeeded, parse it as an int - when it doesn't work 'parsed_n1' won't be reassigned
   parsed_n1 = int(n1)

if parsed_n1 is None:
   raise Exception("No number was entered")

n1 = parsed_n1

then you can easily check wether 'n1' is an int or float by using 'isinstance'

if isinstance(n1, int):
   # n1 is an integer
elif isinstance(n1, float):
   # n1 is a float
else:
   # n1 isn't a number (or a complex number)
Robin Gugel
  • 853
  • 3
  • 8