名称错误:名称“now”未定义。

3

从这段源代码中:

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)) + ".")

运行时,我遇到了以下错误:

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

==================================================

2
for i in range(len(strong)): 不确定你是不是复制/粘贴错误了,但我很确定你的意思应该是 len(string) - user520288
2个回答

13
使用 raw_input() 替代 input()
在 Python 2 中,后者尝试对输入进行 eval(),这就是引发异常的原因。
在 Python 3 中,没有 raw_input()input() 将正常工作(它不会进行 eval())。

谢谢!为什么老师的视频中可以运行,我使用的是Python 3.3,他可能使用了不同的版本? - stevengfowler
1
如果您使用的是Python 3,则“input()”将起作用。由于它不起作用,这意味着您(无意中?)使用的是Python 2。 - NPE
当我输入python --version时,我得到的是Python 3.3.0。那么,我一定在使用3.3版本? - stevengfowler
1
@stevengfowler:我没有水晶球,但是你问题中的异常只能来自于Python 2.x。 - NPE
3
你可能会对调用的Python版本感到困惑。在程序开头添加 import sys,然后加上 print(sys.version),这几乎可以显示2.x版本。 - DSM

0

在Python2中使用raw_input(),而在Python3中使用input()。在Python2中,input()等同于eval(raw_input())

如果您在命令行上运行此代码,请尝试使用$python3 file.py而不是$python file.py。此外,在for i in range(len(strong)):中,我认为strong应该改为string

但是,这段代码可以简化很多

def num_vowels(string):
    s = s.lower()
    count = 0
    for c in s: # for each character in the string (rather than indexing)
        if c in ('a', 'e', 'i', 'o', 'u'):
            # if the character is in the set of vowels (rather than a bunch
            # of 'or's)
            count += 1
    return count

strng = input("Enter a statement:")
print("The number of vowels is:", num_vowels(strng), ".")

将“+”替换为“,”意味着您不必显式地将函数返回强制转换为字符串
如果您更喜欢使用python2,请将底部部分更改为:
strng = raw_input("Enter a statement: ")
print "The number of vowels is:", num_vowels(strng), "."

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接