30 Days of Code: HackerRank Solutions for Python (Day 3)
2 min readJan 20, 2021
The one-stop spot for beginners.
Day 3: Intro to Conditional Statements
Task
Given an integer, n, perform the following conditional actions:
- If n is odd, print
Weird
- If n is even and in the inclusive range of 2 to 5, print
Not Weird
- If n is even and in the inclusive range of 6 to 20, print
Weird
- If n is even and greater than 20, print
Not Weird
Complete the stub code provided in your editor to print whether or not n is weird.
Solution
# %2 == 1, any odd number
# %2 == 0, any even numberif __name__ == '__main__':
n = int(input().strip())if n%2 == 1:
print ('Weird')
# if n is an odd number print Weird. If it is not odd it moves on to the next conditional statement.elif n%2 ==0 and n in range(3,6):
print ('Not Weird')
#if n is an even number and is in range 3 and 6 print Not Weird. (3,4,5)elif n%2==0 and n in range (6,21):
print ('Weird')
#if n is not between the numbers 3 and 6 but in the ranges of 6 and 21 print Weird. The range is to 21 because we want to include 20.(6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)else:
print ('Not Weird')
#if n is anything else print Not Weird.You could also do.
elif n%2==0 and n>20:
print ('Not Weird')
#if n is greater than 20 print Not Weird.
The reason why we don’t start every conditional statement with ‘if’ is so that the run time is quicker. When we use ‘if’, every number runs through every conditional statement which isn’t always necessary. With the ‘elif’ statement it will only check the condition if it fails the above ‘if’ statement.
Thanks for stopping by. If you want to see more solutions share and clap for more!