Can you help me to check a number is even or odd without using any conditions.

Dani AI

Generated

A short, practical addendum that complements the replies already here: it is possible to test parity in Python without using explicit conditional statements. was right to look at bitwise techniques; is right that "branching" usually implies conditionals, but you can avoid them by using operations and indexing; and to clarify — zero is an even number by definition.

A compact, readable idiom that uses the least-significant bit as an index:

n = int(input("Enter an integer: "))
print(('even', 'odd')[n & 1])

How this works: the least-significant bit (LSB) of an integer is 0 for even numbers and 1 for odd numbers. n & 1 extracts that bit; using it as a tuple index selects the correct label without an if or a conditional expression. This also behaves sensibly for negative integers in Python (e.g., -3 & 1 yields 1).

Notes and cautions:

  • Do not use a mask that tests a different bit (for parity you must test the LSB — mask value 1). Testing the 2's bit, for example, checks a different bit and can give misleading results.
  • This assumes integer input; convert or validate input first if needed.
  • For production code, prefer the clearest form for maintainers. The bitwise/index trick is concise, but n % 2 or an explicit if may be easier for others to read; performance differences in CPython are usually negligible.

Recommended Answers

All 5 Replies

Can't!!
Your question has words "OR" this means you've to use a branched code...

Can you help me to check a number is even or odd without using any conditions.

I think Bitwise & operator can be useful.

No & 2 == 0 means Odd
and
No & 2 == 2 means Even
(here No is any number)

Is this correct?

I think it also using condition but different approach rather than modulus

I think Bitwise & operator can be useful.

No & 2 == 0 means Odd
and
No & 2 == 2 means Even
(here No is any number)

Is this correct?

I think it also using condition but different approach rather than modulus

Though zero isn't an even number, it's even enough.

No & 2 == 2 would return false for No = 0.

.
.
.

Modulus wins!

Though zero isn't an even number, it's even enough.

No & 2 == 2 would return false for No = 0.


Modulus wins!

Yes, I agree
but you can change the condition like

No & 1 == 1 means Odd

otherwise Even

commented: Yes, the bitwise AND will always return true when comparing an odd number with 1 since 1 bitAND 1 is true (or 1) +3

}
Console.WriteLine("enter number to check even or odd");
int n=Convert.ToInt32(Console.ReadLine);
string []array=new string[]{"Even","Odd"};
Console.WriteLine(n%2);
}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.