从这个源代码:
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
==================================================
答案 0 :(得分:13)
使用raw_input()
代替input()
。
在Python 2中,后者尝试eval()
输入,这是造成异常的原因。
在Python 3中,没有raw_input()
; input()
可以正常工作(它不会eval()
)。
答案 1 :(得分:0)
在python3中使用raw_input()
用于python2和input()
。在python2中,input()
与说eval(raw_input())
如果您在命令行上运行此操作,请在此$python3 file.py
中另外$python file.py
而不是for i in range(len(strong)):
,我相信strong
应该说string
< / p>
但是这段代码可以简化一点
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), "."