1

I'm currently following a Python course in uni, I just started like a week ago. For this exercise I need to print 'Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo' using a for loop. I have the following:

a = "Buffalo"
for req in range(0,8,1):
    print(a,end=" ")

This results in 8x Buffalo, but the 2nd,4th,5th,6th and 8th buffalo should be in lowercase. Can anyone tell me how to do this? I can't find it anywhere online

tomasvg
  • 21
  • 2
  • 3
    You cannot find it online because you have to think for yourself and solve the problem. Decompose the problem into smaller logical units and work you way up. – ApplePie Nov 23 '20 at 11:58
  • Thank you, for some reason I had a really hard time coming up with the answer to this one. I will do more so from now on! – tomasvg Nov 23 '20 at 12:02

1 Answers1

2

You need to run a for loop (as you are already doing) for particular number of times and you need to alternate the printing of your str (1st, 3rd, 5th => 'Buffalo' and 2nd 4th 6th => 'buffalo').

You can either use a flag (bool) which you can toggle in each iteration and then use it's value to print the str alternatively

Or

make use of the number i in your for loop. The value in i always alternate between even and odd in every iteration. You can use this property.

See this answer to know how to check for even or odd. This is one of the way and resembles c way of checking even odd.

Try this:

a = "Buffalo"
for i in range(0, 8):
    if i & 1:
        print(a.lower(), end = ' ')
    else:
        print(a, end = ' ')
print()

Using Bitwise AND operator (copied from the answer mentioned in the link)

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.
abhiarora
  • 9,743
  • 5
  • 32
  • 57