Instagram
youtube
Facebook
Twitter

Python If-Else HackerRank Solution

Python If-Else HackerRank Solution

In this tutorial, we will solve the HackerRank If-else problem in Python.

question

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

 

Input Format

A single line containing a positive integer, n.

Constraints

  • 1 ≤ n ≤ 100

Output Format

Print Weird if the number is weird. Otherwise, print Not Weird

Sample Input 0

3

Sample Output 0

Weird

Explanation 0

n = 3

n is odd and odd numbers are weird, so print Weird.

Sample Input 1

24

Sample Output 1

Not Weird

Explanation 1

n = 24

n > 20 and n is even, so it is not weird. 

Solution: Method 1

if __name__ == '__main__':
    n = int(input().strip())
if n%2 != 0:
    print("Weird")
elif n%2 == 0 and n>2 and n<=5:
    print("Not Weird")
elif n%2 ==0 and n > 6 and n <=20:
    print("Weird")
else:
    print("Not Weird")

 


Steps Used in solving the problem -

Step 1: first n will take int type input.

Step 2: then we had given an if condition i.e if n%2 is not equal to zero (odd number) then the compiler will print “Weird”.

Step 3: the second condition is if n%2 is equal to zero (even number) and n is greater than 2 and less than equals 5  then the compiler will print “Weird”.

Step 4: Similarly, if n%2 is equal to zero (even number) and n is greater than 6 and less than equals 20  then the compiler will print “Weird”.

Step 5: if the integer doesn't follow any of these conditions then the compiler will print "Not Weird".

 

Solution: Method 2

if __name__ == '__main__':
    n = int(input().strip())
if n%2 != 0:
    print("Weird")
elif n in range(2,5) and n%2==0:
    print("Not Weird")
elif n in range(6,21) and n%2==0:
    print("Weird")
else:
    print("Not Weird")

 

Steps Used in solving the problem -

Step 1: first n will take int type input.

Step 2: then we had given an if condition i.e if n%2 is not equal to zero (odd number) then the compiler will print “Weird”.

Step 3: the second condition is if n is in the range (2,5) and n%2 is equal to zero(even number) then the compiler will print “Weird”.

Step 4: Similarly, if n is in the range (6,21) and n%2 is equal to zero (even number) then the compiler will print “Weird”.

(Note - I have given a range from 6 to 21 so, the compiler will take 20 also)

Step 5: if the integer doesn't follow any of these conditions then the compiler will print "Not Weird".