如何使用while循环解决此问题

时间:2019-12-04 07:21:23

标签: python python-3.x

家庭作业:

  

考虑包含值Great things never come from comfort zones的字符串's'。

     

确定编号。使用while循环在其中存在元音。将数字存储在变量count中,然后打印出来。

代码:

    s="Great things never come from comfort zones"
    vowels=["a","e","i","o","u"]
    count=0
    while chars in s:
        if chars in vowels:
            count=count+1

我知道如何使用for循环来解决这个问题,但是尝试在while循环中解决这个问题,但是会出错。

我认为我在递增while循环时犯了一些错误。

1 个答案:

答案 0 :(得分:0)

s = "Great things never come from comfort zones"
vowels = ["a","e","i","o","u"]
count = 0
while len(s) > 0:
    char = s[-1] # assign last character of 's' to 'char' important to do this first
    s = s[:-1] # now remove the last character from 's'
    if char in vowels:
        count += 1
print(count)

您需要定义一个条件,该条件将终止while循环。在这里,我们从's'截取字符,直到它为空(s =''或len(s)= 0),然后while循环将终止。