-1

I am trying to complete a short python code to output names of ducks. For those ducks whose first letters are 'O' and 'Q', they must be printed with a 'u' after the first letter. I have tried out my code but for some reason it prints the u with every single letter whether it is a 'Q' or any other letter.

prefixes = "JKLMNOPQ"
suffix = "ack"

for p in prefixes:
    print(p + suffix)
    if(p == 'O' or 'Q'):
        print(p + 'u' + suffix)

2 Answers2

1

try this...

if p == 'O' or p == 'Q':

stanely
  • 342
  • 1
  • 8
1

Your problem is this expression:

p == 'O' or 'Q'

This evaluates to (p == 'O') or 'Q' and since the boolean value of a non-empty string is always True, the expression is always True.

You want:

p in ['O', 'Q']

You could also do p == 'O' or p == 'Q' or p == etc., but that gets very repetitive.

So, you get:

prefixes = "JKLMNOPQ"
suffix = "ack"

for p in prefixes:
    if p in ['O', 'Q']:
        print(p + 'u' + suffix)
    else:
        print(p + suffix)
Grismar
  • 27,561
  • 4
  • 31
  • 54