NameError:未定义名称"now"

ste*_*ler 3 python nameerror

从这个源代码:

def numVowels(string):
    string = string.lower()
    count = 0
    for i in range(len(string)):
        if string[i] == "a" or string[i] == "e" or string[i] == "i" or \
            string[i] == "o" or string[i] == "u":
            count += 1
    return count

print ("Enter a statement: ")
strng = input()
print ("The number of vowels is: " + str(numVowels(strng)) + ".")
Run Code Online (Sandbox Code Playgroud)

运行时出现以下错误:

Enter a statement:
now

Traceback (most recent call last):
  File "C:\Users\stevengfowler\exercise.py", line 11, in <module>
    strng = input()
  File "<string>", line 1, in <module>
NameError: name 'now' is not defined

==================================================
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 13

raw_input()而不是input().

在Python 2中,后者尝试eval()输入,这是导致异常的原因.

在Python 3中,没有raw_input(); input()会工作得很好(它没有eval()).

  • @stevengfowler:你可能会对调用哪个python感到困惑.添加`import sys`然后`print(sys.version)`到程序的开头 - 这几乎肯定会显示2.something. (3认同)