Home > OS >  How can I make my program to know if the list the user inputted is a string or a number?
How can I make my program to know if the list the user inputted is a string or a number?

Time:10-14

n=int(input("Number of items to be added on the list: "))
list1 = []
for i in range(n):
    element = input("enter items:")
    list1.append(element)
    

CodePudding user response:

try:
    float(your_input)
    # it's a number

    try:
        int(your_input)
        # it's a whole number

    except ValueError:
        # it's a decimal number

except ValueError:
    # it's not a number

CodePudding user response:

In my code, I try to avoid raising Exceptions for checks. Although this solution is more complex I would implement this check using a regular expression. More information on that can be found in this SO question. Note that I've added $ to the regex to match only consisting of a single number.

The complete code would look as follows:

import re

floatrgx = re.compile(r"[ -]?([0-9]*[.])?[0-9] $")

n=int(input("Number of items to be added on the list: "))
list1 = []
for i in range(n):
    element_is_float = False
    while not element_is_float:
        element = input(f"Enter next item ({i 1}/{n}):")
        element_is_float = (not floatrgx.match(element) is None)
        if not element_is_float:
            print(f"Error: {element} is not a floating point number!")
    
    list1.append(element)

Example output

Number of items to be added on the list: 3
Enter next item (1/3):3.1FOO13
Error: 3.1FOO13 is not a floating point number!
Enter next item (1/3):3.1415
Enter next item (2/3):pi
Error: pi is not a floating point number!
Enter next item (2/3):13
Enter next item (3/3):42

> list1
['3.1415', '13', '42']
  • Related