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:-
- input() function is used to take user input
- find() function is called to to check if a number is off/even. This function returns numtype as odd/even
- 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
Top comments (2)
Yeah! I was looking for this in post when he wrote 3 ways 🤣.
Thanks for the comment.
We can get even more clever:
The bitwise-and operator
&
behavior is trivia, but it's useful because the bitwise operators tend to be consistent across many programming languages.