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.

Programming Noob
  • 1,232
  • 3
  • 14
  • 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

4 Answers4

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?

CambridgeCro
  • 144
  • 4
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
  • 28,235
  • 9
  • 60
  • 81
Ari Cooper-Davis
  • 3,374
  • 3
  • 26
  • 43
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
  • 943
  • 6
  • 21
0
number1 = float (input(‘ enter first value  ‘) )

number2 = float (input(‘ enter second value ‘) )

Formula = print ( (number1 + 20) * (10 + number2) )
4b0
  • 21,981
  • 30
  • 95
  • 142