Home > other >  Infinite loop using 'while' and 'continue'
Infinite loop using 'while' and 'continue'

Time:06-07

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.

CodePudding user response:

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)

CodePudding user response:

In addition to @Barmar's answer, you should fix your indents, as it seems everything after your song array declaration is indented.

  • Related