简体   繁体   中英

Infinite loop using 'while' and 'continue'

List song contains the lines of "Baby Shark". Output the lyrics of song line by line inside the loop, but skip the lines 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.

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 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')


So I changed the if statement a little to do something similar

if 'do do' in song[i]:

it checks if the sub-string 'do do' is in the song string

Ex: checking if 'do do' is in '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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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