I'm working on a program that accepts user input to calculate the mean, median, and mode. The issue is that I need to guess which separator the user will input.
For example:
def get_dataset():
while True:
try:
dataset = [float(_) for _ in input("\nEnter Dataset: ").split()]
except ValueError:
print("\nInvalid Input")
continue
if len(dataset) < 2:
print("\nPlease enter at least 2 values.")
else:
return dataset
print(get_dataset())
>>> Enter Dataset: 12 3 4
[12.0, 3.0, 4.0]
I've only managed to check for spaces and tried to use sep=', '
but the result is still the same except that it removes the brackets. Basically, what I'm trying to do is to get the program to accept input such as 1, 2, 3
, 1 2 3
, and 1,2,3
. Any other given separators will just result in an invalid input message.
As suggested in comment, just replace comma ,
by space character
before splitting the input string.
def get_dataset():
while True:
try:
dataset = [float(_) for _ in input("\nEnter Dataset: ").replace(',', ' ').split()]
except ValueError:
print("\nInvalid Input")
continue
if len(dataset) < 2:
print("\nPlease enter at least 2 values.")
else:
return dataset
>>> print(get_dataset())
Enter Dataset: >? 12,3,4
[12.0, 3.0, 4.0]