Reputation: 9363
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
Upvotes: 2
Views: 14476
Reputation: 820
You need to change you code to
for i in range(1,100):
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
Because otherwise it will individually look at each if statement and when its on 3 for example it does the first part of code but when it triesif i % 3 == 0 and i % 7 == 0:
it will be false so it prints i
Upvotes: 0
Reputation: 1
If I understand you right, these are the conditions: 1) if the number is divisible by 3 print "Hi" 2) if the number is divisible by 7 print "Bye" 4) if the number is divisible by 3 and 7 print "HiBye" 5) if none of the above conditions are met, print the number.
for i in range(1,100):
if i % 3 == 0 and i % 7 == 0:
print "HiBye"
elif i % 3 == 0:
print "Hi"
elif i % 7 == 0:
print "Bye"
elif i % 3 != 0 and i % 7!= 0:
print i
This code works for the above conditions. It states them explicitly and forces the logic.
Upvotes: 0
Reputation: 1124278
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
Upvotes: 9