0

I need to enter different values to input(), sometimes integer sometime float. My code is

number1 = input()
number2 = input()
Formula = (number1 + 20) * (10 + number2)

I know that input() returns a string which is why I need to convert the numbers to float or int. But how can I enter a float or integer without using number1 = int(input()) for example? because my input values are both floats and integers so I need a code that accepts both somehow.

L0987
  • 139
  • 6
  • 1
    Why not just make all the inputs floats? If the inputs will always be real numbers within a pretty large size and precision, it doesn't make a difference except for the output type. – wjandrea Apr 07 '22 at 22:00
  • Is the input trusted? Then you could simply use `eval(input())`. – wjandrea Apr 07 '22 at 22:04
  • Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) Specifically [this answer](https://stackoverflow.com/a/379966/6045800) – wjandrea Apr 07 '22 at 22:06

3 Answers3

2

If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?

0

You could check for the presence of a decimal point in your string to decide if you want to coerce it into a float or an int.

number = input()

if '.' in number:
    number = float(number)
else:
    number = int(float(number))
wjandrea
  • 23,210
  • 7
  • 49
  • 68
Ari Cooper-Davis
  • 3,056
  • 1
  • 25
  • 41
0

You can always just use float:

number1 = float(input())

If you'd like to cast any of your result to integer you always can easily do this

int_res = int(res)  # res was float; int_res will be an integer
SimfikDuke
  • 640
  • 3
  • 17