Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何自动确定用户输入的类型?_Python_Python 2.x - Fatal编程技术网

Python 如何自动确定用户输入的类型?

Python 如何自动确定用户输入的类型?,python,python-2.x,Python,Python 2.x,我想制作一个简单的数学函数,它接受用户输入,但允许用户不输入整数/浮点。我很快就了解到Python默认情况下不识别类型。快速谷歌搜索显示使用literal\u eval,但如果输入字符串,则返回ValueError:malformed string。这就是我到目前为止所做的: from ast import literal_eval def distance_from_zero(x): if type(x) == int or type(x) == float: return ab

我想制作一个简单的数学函数,它接受用户输入,但允许用户不输入整数/浮点。我很快就了解到Python默认情况下不识别类型。快速谷歌搜索显示使用
literal\u eval
,但如果输入字符串,则返回
ValueError:malformed string
。这就是我到目前为止所做的:

from ast import literal_eval

def distance_from_zero(x):
  if type(x) == int or type(x) == float:
    return abs(x)
  else:
    return "Not possible"

x = literal_eval(raw_input("Please try to enter a number "))

print distance_from_zero(x)

正如您提到的,如果您得到类似于
ast.literal\u eval('c1')
的输入,您将得到格式错误的字符串错误(
ValueError
)。如果执行类似于
ast.literal\u eval('1c')
的操作,您还将得到
SyntaxError
。您需要获取输入数据,然后将其传递给
literal\u eval
。然后,您可以捕获这两个异常,然后返回您的
“不可能”

from ast import literal_eval

def distance_from_zero(x):
    try:
        return abs(literal_eval(x))
    except (SyntaxError, ValueError):
        return 'Not possible'

    x = raw_input("Please try to enter a number ")

    print distance_from_zero(x)

只需回答您的问题为什么
ValueError:如果您阅读文本评估文档,则会出现格式错误的字符串

安全地计算表达式节点或包含Python的字符串 表情。提供的字符串或节点只能由 以下Python文本结构:字符串、数字、元组、列表、, 口授、布尔语和无语

所以字符串应该用“”括起来,就像在编辑器中编写的那样,比如
s=“string”
原始输入接受输入并转换为字符串数据类型,因此我尝试过使用
literal\u eval

>>> x=raw_input()
string
>>> x= "\""+x+"\"" # concatenating the "" to string
>>> literal_eval(x)
'string'
>>>

。注意:
raw_input
是Python2特有的。感谢您的详细解释!我想我需要学习更多,因为我甚至不知道
try
,除了存在的
。绝对没有想到使用错误作为条件!