school = 'Massachusetts Institute of Technology'
numVowels = 0
numCons = 0
for char in school:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1
elif char == 'o' or char == 'M':
print char
else:
numCons -= 1
print 'numVowels is: ' + str(numVowels)
print 'numCons is: ' + str(numCons)
这是python代码逻辑上它应该打印' o' 3次,但我无法弄清楚为什么numcons的值应该是-21但是它来了-25是否有人有答案
答案 0 :(得分:0)
它不应该显示“o”,因为如果字符是“o”,那么它将触发第一个if
语句。因此,除了使用elif
之外,请使用if
语句,除非这对您来说不是最佳选择。
if char == "o" or char == "M":
print char
TL; DR:将elif
更改为if
。
答案 1 :(得分:0)
首先,elif
它是else: if
。在你的情况下,这意味着如果char
不是一个较低的元音而且它是' o'或者' M'它会打印出来。对于' o,这些是相互矛盾的陈述。适当的条件是
if char in 'aeiu': #Better use in than multiple comparisons
numVowels += 1
elif char == 'o':
numVowels += 1
print(char)
elif char == 'M':
print(char)
else:
numCons -= 1
另一个问题是你只是与LOWER元音进行比较,所以AEIOU的元音会进入else
语句,影响你的numCons
计数器。一个更好的代码可能是
if char.lower() in 'aeiou': #If it's vowel
numVowels += 1
else:
numCons -= 1
if char in 'Mo': #I think you want here the capital letter and the 'o' from 'of', char.isupper() or char == 'o' should be a better condition
print(char)