Python if and else print condition
You need to use elif
instead of if
, and test for the 3 and 7 case first:
if i % 3 == 0 and i % 7 == 0:
print "HiBye"
elif i % 3 == 0:
print "Hi"
elif i % 7 == 0:
print "Bye"
else:
print i
You used independent if
statements. Each if
statement is tested and their block is executed, regardless of what other if
statements your code may execute before or after. elif
blocks, however, are attached to their if
statement and Python will only ever execute one of the blocks, the first one whose condition is true.
So in the above if..elif..elif..else
series of tests, if i % 3 == 0 and i % 7 == 0
is True, none of the other branches will be executed, including the else
branch.
Now the output looks like:
>>> for i in range(1, 22):
... if i % 3 == 0 and i % 7 == 0:
... print "HiBye"
... elif i % 3 == 0:
... print "Hi"
... elif i % 7 == 0:
... print "Bye"
... else:
... print i
...
1
2
Hi
4
5
Hi
Bye
8
Hi
10
11
Hi
13
Bye
Hi
16
17
Hi
19
20
HiBye
Related videos on Youtube
Comments
-
Srivatsan almost 2 years
If an integer is divisible by 3, print "Hi"
If it is divisible by 7, print "Bye"
If it is divisible by both 3 and 7, print "HiBye"
As of now I have tried:
for i in range(1,100): if i % 3 == 0: print "Hi" if i % 7 == 0: print "Bye" if i % 3 == 0 and i % 7 == 0: print "HiBye" else: print i
But my numbers are repeated. i.e. this is the output I get.
1 2 Hi 3 4 5 Hi 6 Bye 7 8 Hi 9 10 11 Hi 12 13 Bye 14 Hi 15 16 17 Hi 18 19 20 Hi Bye HiBye
As you can see, the 3 is repeated again. I think the mistake is in the
else: print i
statement
-
Vera Worri over 7 yearsI changed it to fix the problem
-
Martijn Pieters over 7 yearsWhy the last
elif
? Why not just useelse
? -
Vera Worri over 7 yearsJust to make sure the condition is met. In these cases, I find it better to be explicit. It's really the order that python is iterating and passing through the numbers that matters.
-
Martijn Pieters over 7 yearsIt's overly verbose and redundant. You are making Python do extra work that you already tested for.
-
Vera Worri over 7 yearsYeah.. I know. But I found that building in some redundancy when trying to solve a problem helps figure out what python is doing.