How to input multiple numeric types in the same line in Python

Viewed 1139

I'm trying to do basic arithmetic with different numeric types. The input is one floating number (4.2), two integers (3)(2), one string('Hello'). How can I read the input from the user in one the same line? Each numeric type is separated by a space only, with no commas. I've managed to make it work by defining the inputs separately on one line per input.

`    a = float (input())
     b = int (input())
     c = int (input())
     d = str (input())
     print (round (a * b,2),end=d*c)    `

The actual result works fine if the input is provided in different lines but I would like to get all the input in one line. Thank you.

5 Answers
items = input.split(' ')
items = [int(i) for i in items]
print (round (items[0] * items[1],2),end=items[2]*items[3]) 

Please note this will crash if you enter more or less than 4 space separated values.

You can split the input and unpack the list input().split(" ") returns to your four variables. Note that these are still strings, so you still have to convert them to float and int:

a, b, c, d = input().split(" ")
a = float(a)
b = int(b)
c = int(c)
print(round(a * b, 2), end=d*c)

You could also use the Python package argparse if you wanted to pass the values in at the command line.

import argparse

parser = argparse.ArgumentParser(description='Enter two integers, a float, and a string.')
parser.add_argument('-i', '--integers', dest='integers', action='store', nargs='+', default=[], help='Capture a list of integers (default: None)')
parser.add_argument('-f', '--floats', dest='arg_float', action='store', default=0.0, help='Capture a single float (default: 0,0)')
parser.add_argument('-s', '--strings', dest='arg_string', action='store', default="Nothing", help='Capture a single string (default: "Nothing")')

args = parser.parse_args()
print(args)

int1    = args.integers[0]
int2    = args.integers[1]
float1  = args.arg_float
string1 = args.arg_string

print("int1 =", int1)
print("int2 =", int2)
print("float1 =", float1)
print("string1 =", string1)

Output:

C:\Users\MyAccount\>python testinput.py -i 1 2 3  -f 2.2 -s "MyText"
Namespace(arg_float='2.2', arg_string='MyText', integers=['1', '2', '3'])
('int1 =', '1')
('int2 =', '2')
('float1 =', '2.2')
('string1 =', 'MyText')

when we enter any numeric type to input(),it converts it into string .so we can enter any data type but it will be a string. first we have to enter values separated by space and then we have to use split() method to separate and then we have to convert them into data type we want.

  >>> data_types = input("Enter numbers").split()
  >>> 30 21.112 25 3.250

Now it's stored in a list but as string. Using indexing you can access them and convert them as you want and use.

>>> print(data_types)
>>> ['30','21.112','25','3.250']

Example:

>>> avg =(int(data_types[0])+123)/2

you can create a function that will parse your user input.



user_input = "2.5 3 4 x"

def parser(input_str):
    results = []
    entries = input_str.split(" ")
    for entry in entries:
        for convert in [int, float]:
            try:
                entry = convert(entry)
            except ValueError:
                continue
            break
        results.append(entry)
    return results

a, b, c, d = parser("2.5 2 bob")
print(round (a * b,2),end=d*c)
Related