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

==================================================
4

2 回答 2

13

使用raw_input()而不是input().

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

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

于 2013-03-03T20:45:28.320 回答
0

用于raw_input()python2 和input()python3。在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), "."
于 2013-03-03T20:54:29.563 回答