2

I have looked at this link and a few others but they seem to mainly focus on python version two: Two values from one input in python? (Note: Just like the asker in the link above, I've also coded in C)

Is there a version 3 equivalent to all this? If I were to write the code:

integer_n, float_n = int(input("Enter a integer and float: "))

#And the user enters:
#4, 5.5

Since python implicitly converts an integer to a float, this should work. But Im getting an error from the IDE.

Community
  • 1
  • 1
J.doe
  • 37
  • 5

2 Answers2

3

The input function return a string, so you need to convert the object's type after reading them form stdin. And as a more safe approach you better to get the numbers separately and use a try-except expression in order to handle the unexpected errors:

while True:
    try:
        integer_n = int(input("Enter an integer:"))
        float_n = float(input("Enter a float: "))
    except ValueError:
        print("Please enter valid numbers.")
    else:
        break
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    I agree with this answer. There is no way to handle this without parsing user input which could be messy. Taking each number separately is better and will take one less key stroke from the user. – Igor Apr 25 '16 at 18:24
0

You can do it like this:

    integer1, float1 = input("Enter an integer and float:").split()

Of course this is just a simple example, it doesn't check the data type.

Matt
  • 2,602
  • 13
  • 36
  • I see the problem now, when the print function takes in two values at once, we'd have to use the split function like your example. But the types when we first store the two values are string types and not integer or float. So we would have to later on manually convert them as float or integer to use simple arithmetic on them. So that means instead of converting input on that line when I take in input, I should've just left it as input. Much obliged – J.doe Apr 25 '16 at 18:45