这个程序有什么问题?

2024-10-01 02:18:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用基本循环来计算元音的数量,得到的结果只有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))

Tags: orofinforinput数量stringraw
3条回答

首先,您不需要在这里使用函数,因为它实际上并不能为您带来任何好处。其次,您将使用名称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))

还要注意我是如何用一个简单的in检查来替换单调乏味的if m == 'a' or m =='e' ...。你知道吗

你有很多错误

  • 您反复使用变量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'):它又短又简单

你丢失了一个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':

相关问题 更多 >