Vikky Omkar

Posted on

# 3 ways to find if a number is Odd/Even in Python

### Solution #1

``````def find(num):
# code logic here
if num%2 == 0:
numtype="even"
else:
numtype = "odd"
return numtype

num = int(input('Enter the number: '))  # 1. take your input
numtype = find(num)                     # 2. call the find function
print('Given number is',numtype).       # 3. print if the number is even or odd
``````

#### Output:

``````coder# python challenge07.py
Enter the number: 5
Given number is odd
coder# python challenge07.py
Enter the number: 8
Given number is even
``````

#### Explanation:-

1. input() function is used to take user input
2. find() function is called to to check if a number is off/even. This function returns numtype as odd/even
3. At last, print if the given number is odd/even

### Solution #2

Avoid usage of else block by assigning a default value (odd) to numtype

``````def find(num):
# code logic here
numtype = "odd"
if num%2 == 0:
numtype="even"
return numtype

num = int(input('Enter the number: '))      # take your input
numtype = find(num)                         # call the find function
print('Given number is',numtype)            # print if the number is even or odd
``````

#### Output:

``````coder# python challenge07.py
Enter the number: 5
Given number is odd
coder# python challenge07.py
Enter the number: 8
Given number is even
``````

### Solution #3

directly return numtype

``````def find(num):
# code logic here
if num%2 == 0:
return "even"
return "odd"

num = int(input('Enter the number: '))      # take your input
numtype = find(num)                         # call the find function
print('Given number is',numtype)            # print if the number is even or odd
``````

#### Output:

``````coder# python challenge07.py
Enter the number: 5
Given number is odd
coder# python challenge07.py
Enter the number: 8
Given number is even
``````

### Bonus

`numtype = num%2 == 0 and "even" or "odd"`

Find the video explanation also

Mr.13

Yeah! I was looking for this in post when he wrote 3 ways ðŸ¤£.

Thanks for the comment.

Tim West • Edited

We can get even more clever:

``````def is_odd_or_even(n):
return "odd" if n&1 else "even"
``````

The bitwise-and operator `&` behavior is trivia, but it's useful because the bitwise operators tend to be consistent across many programming languages.