这个程序有什么问题?

时间:2015-01-24 18:38:25

标签: python python-2.7

我试图仅使用基本循环来计算元音的数量,而我得到的唯一输出是0

s= str(raw_input("Enter a string of characters:"))
m =0
def numvow(s,m):
    for m in s:
        if m == 'a'or m =='e' or m =='i' or m =='o' or m =='u':
            m+=1
print("The number of vowels is " +str(m))

4 个答案:

答案 0 :(得分:1)

您错过了return m,也从未致电 numvow;另外,您将整个m重新分配给s中的单个字符,而不是使用单独的循环变量。所以,三个很好的理由它不起作用:-)。易于修复:

s = raw_input("Enter a string of characters:")
m = 0
def numvow(s,m):
    for c in s:
        if c == 'a' or c =='e' or c =='i' or c =='o' or c =='u':
            m+=1
    return m
m = numvow(s, m)
print("The number of vowels is " +str(m))

我通过删除对str的一个冗余调用进行了另一项改进(因为raw_input已经返回一个字符串,没有理由进行该调用)但还没有其他人,例如将if更改为更简洁的&更快

if c in 'aeiou':

答案 1 :(得分:1)

你有很多错误

  • 您一次又一次地使用变量m
  • 您没有调用该功能

程序的最小编辑将是

s= str(raw_input("Enter a string of characters:"))
c =0
def numvow(s,c):
    for m in s:
        if m == 'a'or m =='e' or m =='i' or m =='o' or m =='u':
            c+=1
    return c
c = numvow(s,c)
print("The number of vowels is " +str(c))

一些提示

  • 使用format进行连接"The number of vowels is {}".format(c)
  • raw_input返回str,因此广告
  • 你可以做if m in ('a','b','c','d','e'):简短而简单

答案 2 :(得分:0)

您有全局m和参数m。整数是不可变的,因此删除全局和参数m,为计算创建一个本地参数,并在函数末尾创建return m。使用与计数器不同的循环变量。然后实际调用函数:)

def numvow(s):
    m = 0
    for c in s:
        if c in 'aeiou':
            m+=1
    return m

s= raw_input("Enter a string of characters: ")
m = numvow(s)
print "The number of vowels is",m

输出:

Enter a string of characters: abcdefg
The number of vowels is 2

答案 3 :(得分:0)

首先,你不需要在这里使用一个功能,因为它并没有真正为你买任何东西。其次,您使用名称m来表示两个不同的变量。

s = str(raw_input("Enter a string of characters:"))
m = 0
for l in s:
    if l in 'aeiou':
        m += 1
print("The number of vowels is " + str(m))

另请注意我是如何使用简单的if m == 'a' or m =='e' ...支票替换繁琐的in

相关问题