0

I am new to python. I am trying to write a program that counts a range of values but for multiples of 3 and 4 adds 3 and 4 to them resepectively and when the number is multiple of both adds that number to it. So for instance 1,2,3,4,5,6,7,8,9,10,11,12 should read in the end program as: 1,2,6,8,5,9,7,12,10,11,24

But my code is getting stuck somewhere.

for i in range (1,20):
   if i%3==0 and i%4==0:
       i=i+12
   if i%3==0:
       i=i+3
   if i%4==0:
       i=i+4
   print i
2
  • You may want to use the += syntax as well. Instead of i=i+4, you could use i+=4. It'll make it cleaner. Commented Sep 12, 2014 at 20:49
  • Please note my edited answer Commented Sep 12, 2014 at 22:07

3 Answers 3

3

This line has a typo

if i%3==0 and 1%4==0:  # your second condition is 1 % 4 == 0, which is always false

I think you meant

if i%3==0 and i%4==0:
Sign up to request clarification or add additional context in comments.

Comments

2

It is better (accurate and cleaner) if you use a different variable.

for i in range (1,20):
   n = i
   if i%3==0 and i%4==0:
       n=i+12
   if i%3==0:
       n=i+3
   if i%4==0:
       n=i+4
   print n

Now you will notice this fixed it for the 9 case, but not the 12 case! We now need to add the use of elif. Also, if a number is a multiple of 3 and 4, then it is also a multiple of their lowest common multiple, in this case 12. So you could re-write your first step to just check for multiples of 12. This gives us:

for i in range (1,20):
   n = i
   if i%12==0
       n=i+12 # or possibly i + i
   elif i%3==0:
       n=i+3
   elif i%4==0:
       n=i+4
   print n

The reason this works is because without the elif the i was getting added to multiple times. For example, with 9, you get to 9%3 ==0, True. Now i is set to 12. Next statement? 12%4 ==0 True. So another 4 is added.

Alternatively, if you would like to do some crazy python stuff:

for i in range(1, 20):
    print i + next((n for n in (12, 4, 3) if i % n == 0), 0)

(Shout out to Jon Clements for this 2-liner answer)

Comments

1

You're allowing multiples cases (if conditions) for each iteration. I think you probably wanted to do exclusive cases.

Maybe something like:

for i in range(1, 20):
    print i, "=>",
    if i % 3 == 0 and i % 4 == 0:
        i += i
    elif i % 3 == 0:
        i += 3
    elif i % 4 == 0:
        i += 4
    print i

Comments

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.