简体   繁体   English

使用“while”和“continue”的无限循环

[英]Infinite loop using 'while' and 'continue'

List song contains the lines of "Baby Shark".列表歌曲包含“Baby Shark”的台词。 Output the lyrics of song line by line inside the loop, but skip the lines do do, do do do do.在循环内逐行输出歌曲歌词,但跳过行do do,do do do do。

song = ['Baby shark', 'do do, do do do do',
  'Baby shark', 'do do, do do do do',
  'Baby shark', 'do do, do do do do',
  'Baby shark',
  'Mama shark', 'do do, do do do do',
  'Mama shark', 'do do, do do do do',
  'Mama shark', 'do do, do do do do',
  'Mama shark']

    songs = ''
    i = 0
    while i < len(song):
      if song[i] in ('d',',', 'o')
        i += 1
        continue
      songs += song[i]
      i+= 1
    print(songs)

This is the loop I wrote, but it's throwing a syntax error for my "if song[i] in ('d', ',','o') line of code.这是我写的循环,但它为我的“if song[i] in ('d', ',','o') 行代码抛出了一个语法错误。

I know the content is silly but this was one of the questions and I am really struggling with loops.我知道内容很愚蠢,但这是问题之一,我真的在为循环而苦苦挣扎。

your if statement was你的 if 语句是

if song[i] in ('d', ',', 'o'):

here you check if all the song is one of these letters.在这里,您检查所有歌曲是否都是这些字母之一。

Ex: checking if 'Baby shark' is one of these ('d', ',', 'o')例如:检查'Baby shark'是否是其中之一('d', ',', 'o')


So I changed the if statement a little to do something similar所以我稍微改变了 if 语句来做类似的事情

if 'do do' in song[i]:

it checks if the sub-string 'do do' is in the song string它检查子字符串'do do'是否在song字符串中

Ex: checking if 'do do' is in 'do do, do do do do'例如:检查'do do'是否在'do do, do do do do'

song = [
    'Baby shark',
    'do do, do do do do',
    'Baby shark',
    'do do, do do do do',
    'Baby shark',
    'do do, do do do do',
    'Baby shark',
    'Mama shark',
    'do do, do do do do',
    'Mama shark',
    'do do, do do do do',
    'Mama shark',
    'do do, do do do do',
    'Mama shark'
]

# removed indentation
songs = ''

i = 0

while i < len(song):
    # edited the if statement and added the ":"
    if 'do do' in song[i]:
        i += 1
        continue
    songs += song[i]
    i+= 1
print(songs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM