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.

3
  • 2
    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. Commented Apr 7, 2022 at 22:00
  • Is the input trusted? Then you could simply use eval(input()). Commented Apr 7, 2022 at 22:04
  • Does this answer your question? How do I parse a string to a float or int? Specifically this answer Commented Apr 7, 2022 at 22:06

4 Answers 4

4

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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))

1 Comment

This'll fail on scientific notation like 1e10 as well as special values nan and inf.
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

Comments

0
number1 = float (input(‘ enter first value  ‘) )

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

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

1 Comment

Be careful with so-called "smart quotes", e.g. ‘’. They'll cause SyntaxErrors with Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.