0

I've got the following list

ninjas = ['ryu', 'crystal', 'yoshi', 'ken']

I'm playing around with loops and have the following for loop

for ninja in ninjas:
    if ninja == 'ryu':
        print(f'{ninja} - black belt')
    if ninja == 'ken':
        print(f'{ninja} - brown belt')
    else:
        print(ninja)

The output I want is

ryu - black belt
crystal
yoshi
ken - brown belt    

but the output I get is

ryu - black belt
ryu
crystal
yoshi
ken - brown belt

I'm assuming that after the first if statement it is looping back around to the start, hence the repeated 'ryu', how do I stop it doing that?

Thanks in advance

1
  • 1
    I'm assuming that after the first if statement it is looping back around to the start that is false, it continues to the next if statement which has an else condition. You need to nest your ifs Commented Oct 4, 2018 at 19:13

1 Answer 1

1

To get what you actually expect you need:

for ninja in ninjas:
    if ninja == 'ryu':
        print(f'{ninja} - black belt')
    elif ninja == 'ken':
        print(f'{ninja} - brown belt')
    else:
        print(ninja)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I had just figured out another way to do it seconds after you posted but yours is more concise so I much prefer it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.