python input()未按预期工作

2024-03-29 09:54:15 发布

您现在位置: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 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

Tags: intrueinputstringislinesomething例子
3条回答

你想在python2中raw_input()

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

input()尝试评估(危险!)你的付出

您必须使用raw_input()(Python 2.x),因为^{}等同于eval(raw_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()可以这样做,因为它将输入转换为stringFor futher information, read Python docs

在Python3.x中,您的代码可以正常工作

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

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

相关问题 更多 >