NameError:名称 'now' 未定义

3 投票
2 回答
34513 浏览
提问于 2025-04-17 17:47

从这段源代码来看:

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 个回答

0

在Python 2中使用 raw_input(),在Python 3中使用 input()。在Python 2里,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), ".")

把 '+' 替换成 ',' 意味着你不需要把函数的返回值强制转换成字符串。

如果你想用Python 2,可以把下面的部分改成:

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

在Python中,使用raw_input(),而不是input()

在Python 2里,后者会尝试对输入的内容进行eval()处理,这就是导致错误的原因。

而在Python 3中,没有raw_input()这个函数;input()就可以正常使用(它不会进行eval()处理)。

撰写回答