用户输入的程序输出给出不同的长度以与用户输入一致。输入 1 --> abc 输入 2--> 'abc'

Output of program for user input giving different length for consonant with user input. input 1 --> abc input2--> 'abc'

""" 为什么这 4 在第二个用户输入中作为 'abc'.ii 知道它正在计算引号,因为 python 将输入 'abc' 作为“'abc'”因此将 5 算作长度如何解决此问题以获得正确答案,就像上面显示的其他输入一样,下面的 n"""

计算元音 n 辅音

 def get_count(words):
    words=str(input('Enter:')).lower()
    vowels = ['a','e','i','o','u']
    v_count = 0
    c_count = 0
    for letter in words:
        if letter in vowels:
            v_count += 1
        else:
            c_count+=1
    print("vowel : {}".format(v_count), "consonant: {}".format(c_count))
get_count(input)

Result:

Enter:aBc
vowel : 1 consonant: 2
Enter:'abc'
vowel : 1 consonant: 4-  ??? why

Blockquote

Enter:abc
vowel : 1 consonant: 2

先判断字符是否在字母表中

def get_count(words):
    words=str(input('Enter:'))
    vowels = ['a','e','i','o','u']
    v_count = 0
    c_count = 0
    for char in words:
        if char.isalpha():
            if char.lower() in vowels:
                v_count += 1
            else:
                c_count+=1
    print("vowel : {}".format(v_count), "consonant: {}".format(c_count))
get_count(input)

长答案:所以您的字符串是 'abc',长度为 5 个字符。 python 正在检查:

  • 如果第一个字符 ' 是元音字母并且是 不太辅音 = 0+1
  • 第二个字符是a,它是元音所以 元音 = 0+1
  • third b 不在元音中,所以辅音 = 1+1 (现在是 2)
  • 第四个c不是元音,所以辅音= 2+1(现在是 3)
  • 第五个字符是 ',它不是元音字母, 所以辅音 = 3+1(现在是 4)

所以最后我们得到:元音:1 辅音:4

简答:您的输入被视为一个五个字符长的字符串,您的脚本遍历每个元素,包括单引号。