output odd numbers without if [closed]
I need to output only odd numbers from this program:
m = int(input())
n = int(input())
for i in range(m, n - 1, -1,):
print(i)
pls without if
Solution 1:
Using and
instead of if
:
i&1 and print(i)
(Better use range with step -2, I just dislike such restriction questions and always try to work around the restrictions in unintended ways).
Solution 2:
Without a guarantee that your start value is odd it becomes a little more tricky since you cannot simply step by 2. You can still get away with it(slightly) using conditionals like so:
m = int(input())
n = int(input())
for i in range(m, n):
output_str = (f"{str(i % 2)}" or "") * i
output_str += (i % 2) * '\n'
print(output, end="")
I should put a disclaimer here that I'm strictly answering the question. I do not exactly endorse this method.
Solution 3:
You can use a striding range as long as you make sur to adjust the starting number:
m = int(input())
n = int(input())
for i in range(m+1-m%2,n+1,2): # start at next odd if m is even
print(i)
If you want them in decreasing order:
m = int(input())
n = int(input())
for i in reversed(range(m+1-m%2,n+1,2)):
print(i)