从这个源代码:
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
==================================================
在 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), "."