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)
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
在我的代码中,我尽量避免引发异常进行检查。虽然这个解决方案更复杂,但我将使用正则表达式实现此检查。更多的信息可以在这个问题中找到。请注意,我已将$
添加到正则表达式中,以仅匹配由单个数字组成的字符串。
的完整代码看起来如下:
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)
示例输出
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']