Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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/5/ruby/22.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 - Fatal编程技术网

python输入()未按预期工作

python输入()未按预期工作,python,Python,我是一名python新手。我对循环越来越熟悉,并从一本书中尝试了这个例子 while True: s = input('Enter something : ') if s == 'quit': break print('Length of the string is', len(s)) print('Done') 然而,输出如下 Enter something : ljsdf Traceback (most rec

我是一名python新手。我对循环越来越熟悉,并从一本书中尝试了这个例子

while True:
        s = input('Enter something : ')
        if s == 'quit':
                break
        print('Length of the string is', len(s))
print('Done')
然而,输出如下

Enter something : ljsdf
Traceback (most recent call last):
  File "trial_2.py", line 2, in <module>
    s = input('Enter something : ')
  File "<string>", line 1, in <module>
NameError: name 'ljsdf' is not defined
输入:ljsdf
回溯(最近一次呼叫最后一次):
文件“trial_2.py”,第2行,在
s=输入('输入某物:')
文件“”,第1行,在
NameError:未定义名称“ljsdf”
您想要python2中的
原始输入()

while True:
    s = raw_input('Enter something : ')
    if s == 'quit':
            break
    print 'Length of the string is', len(s)
print 'Done'

input()


计算输入字符串,不像。

您必须使用
raw\u input()
(Python 2.x),因为它等效于
eval(raw\u input())
,所以它将您的输入作为有效的Python表达式进行解析和计算

while True:
        s = raw_input('Enter something : ')
        if s == 'quit':
                break
        print('Length of the string is', len(s))
print('Done')
注意:


input()
不会捕获用户错误(例如,如果用户输入了一些无效的Python表达式)
raw_input()
可以执行此操作,因为它将输入转换为
字符串

您的代码在Python3.x中运行良好

但如果您使用的是Python2,则必须使用raw_input()输入字符串

在Python2.x中,
input()
被设计为根据用户的输入返回数字、int或float,您还可以输入变量名

您需要使用:

raw_input('Enter something: ')
之所以出现此错误,是因为Python认为“ljsdf”是变量的名称,这就是它引发此异常的原因:

name错误:未定义名称“ljsdf”

因为“ljsdf”未定义为变量:D


raw\u input()
使用起来更安全,然后将输入值转换为:D

之后的任何其他类型:这基本上是的副本,尽管如果不知道在哪里查找,您可能无法找到它……我认为您的注释有点落后
raw\u input()
不会将输入转换为字符串,甚至不会尝试将所述字符串计算为代码。我刚才引用的raw\u input()在Kamodo Editor中不起作用..而且input()也不起作用。。我在下面看到了这个错误>名称错误:未定义名称“原始输入”
raw_input('Enter something: ')