Home > Software design >  Validation if all input items are floats in Python
Validation if all input items are floats in Python

Time:11-19

in this following code, I tried to create a validation point that validates if all input items are floats (input if of form "1,2,3,4,b,w,..."), however I couldn't understand how to do it without hurting the list itself. the wanted output is [1.0,2.0,3.0,4.0] when all items are floats, or an error message if the didn't answer only numbers.

list1_str = input("Enter list1: ")
list1_str1 = list1_str.replace(" ", "").split(",")
for i in list1_str1: 
  if list1_str1[i].isdigit:
    break
  else: print("item is not float")
list1 = [float(i) for i in list1_str1] #turn list to floats

What did I do wrong?

CodePudding user response:

You could split this into two parts: 1) validate input type and 2) if correct, cast as numeric type:

def validate_list(my_list):
    is_valid = all([j.isnumeric() for j in my_list])
    return is_valid

def cast_numeric(my_list):

    if not validate_list(my_list):
        raise ValueError("non-numeric string value found")
    else:
        return [float(j) for j in my_list]


# examples:
l1 = list("12345")
l2 = l1   ["not a num"]


validate_list(l1) # true
cast_numeric((l1) # [1.0, 2.0, 3.0, 4.0, 5.0]


validate_list(l2) # false
cast_numeric((l2) # raises error message

CodePudding user response:

There are some mistakes in your code.

  • isdigit is not a property, its a method so call it like isdigit()
  • You have put a break in your loop, which is not necessary.

See the below code for some versions of things you want to do

list1_str = input("Enter list1: ")
list1_str1 = list1_str.replace(" ", "").split(",")

# This is enough to get all the float values.
numericals = [float(num) for num in list1_str1 if num.isdigit()]

# Let'say you want to print a validation message, then it can be 

if not all([num.isdigit() for num in list1_str1]):
    print("Invalid float items found")

#Let's say you want to print the invalid ones as well, then 
wrong_ones = [num for num in list1_str1 if not num.isdigit()]
if wrong_ones and len(wrong_ones) > 0:
    print(f"The items {wrong_ones} are invalid floats in input")

Hope this makes it bit clear for you

  • Related