【问题标题】:A for loop and while loop problem.The result isn't what I expected一个 for 循环和 while 循环的问题。结果不是我所期望的
【发布时间】:2020-05-12 03:42:50
【问题描述】:

总的来说,我是 Python 和 Stackoverflow 的新手,如果我的格式很糟糕而且我不擅长英语,我很抱歉。但我对这段代码有疑问。

w = input('Please enter a word: ')
total = 0
for i in w:
     if i in 'AEIOUaeiou':
        print(i,end='')

这是代码的结果

Please enter a word: Elephant
Eea

这是工作,但我不知道如何使结果像这样

Please enter a word: Elephant
Total vowel found = 3
Eea
Total consonant found = 5
lphnt

【问题讨论】:

  • 如果你想计算一些东西,你需要增加total。并打印结果。也不确定while循环在哪里

标签: python python-3.x for-loop while-loop


【解决方案1】:

这是您的代码的解决方案 :) 您只需要一些额外的格式就可以了!

word_format = input("Please enter a word: ")
total_vowels = 0
total_constants = 0
vowel_list = []
constant_list = []
for check in word_format:
    if check in "AEIOUaeiou":
        total_vowels += 1
        vowel_list.append(check)
    else:
        total_constants += 1
        constant_list.append(check)


# Here is our capture:
print(f"Total vowels found: {total_vowels}")
print(''.join(vowel_list))
print(f"Total constants found: {total_constants}")
print(''.join(constant_list))

这是结果!

Please enter a word: Elephant
Total vowels found: 3
Eea
Total constants found: 5
lphnt

【讨论】:

    【解决方案2】:
    w = input('Please enter a word: ')
    vowels = []
    consonants = []
    for i in w:
         if i in 'AEIOUaeiou':
            vowels.append(i)
         else:
            consonants.append(i)
    print('Total vowel found = ',len(vowels))
    print(''.join(vowels))
    print('Total consonant found = ',len(consonants))
    print(''.join(consonants))
    

    输入:大象

    输出:

    Please enter a word: Elephant
    Total vowel found =  3
    Eea 
    Total consonant found =  5
    lphnt 
    

    【讨论】:

      【解决方案3】:

      实际上问题出在您的 if 语句中,在 if 语句之后您正在打印“i”,即“AEIOUaeiou”中存在的输入单词的字母,这就是它只打印元音的原因。使用此代码:-

      w = input('Please enter a word: ')
      vowels=""
      consonent=""
      for i in w:
            if i in 'AEIOUaeiou':
               vowels+=i
            else:
               consonent+=i
      print (f"total vowels found={len(vowels)}")
      print(vowels)
      print (f"total consonents found ={len(consonent)}")
      print(consonent)
      

      现在输出将是:

      Please enter a word: elephant
      total vowels found=3
      eea
      total consonents found=5
      lphnt
      

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        您不需要任何循环。只需使用过滤器并加入。它会加速你的代码。

        w = "Elephant"
        
        v="".join(filter(lambda x: x in "AEIOUaeiou", w))
        c="".join(filter(lambda x: x not in "AEIOUaeiou", w))
        
        print(v, len(v))
        print(c, len(c))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-23
          • 2018-11-21
          • 2018-11-05
          • 1970-01-01
          • 2021-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多