pythonuser-inputdefault-valuestring-conversionmultiple-input

Multiple User-inputs, Default input, and String-to-Array Conversion


Hello all I would like to make a program that takes in two user inputs. The first is a scalar and the second is a provided list or array. The number would be a multiplier for which to scale the array and the output would be the multiplied array.

import numpy as np

a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]

Also, for added convenience to the user, I'd like there to be a default scalar of 1 if no number is entered.

I am sorry for the lack of code but everything I've tried has not worked anyway.

I know that using

x, y = input().split() 

will enable the user to enter two inputs such as

3 a

or

5.5 b

which is how I'd like the inputs to be entered. However, while the number can be converted to a float, I do not know how to interpret the letter a or b from a string to the their array names.

float(x)*np.array(y)

The following error I believe to have occurred due to the mismatch of data types.

 float(x)*np.array(y)
TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

If anyone can offer a solution or if there is a better way to do this than your input would be greatly appreciated. Thank you.


Solution

  • I guess this helps! This also handles the case where the user doesn't specify a multiplier, then it automatically defaults to 1

    import numpy as np
    
    a = np.array([1, 3, 5, 7, 9])
    b = np.array([2, 4, 6, 8, 10])
    
    y,*x = input().split()
    if not x:
        x=[1]
    
    print(float(x[0])*eval(y))