HackerRank Day 4 Solution in Python: Class vs Instance

Today we will see the HackerRank Day 4 Solution in Python. The problem is named Class vs Instance which is part of 30 Days of code on HackerRank. Let’s get started!

Day 4: Class vs Instance Problem statement

We have to write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as  is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0.. In addition, we should write the following instance methods:

  1. yearPasses() should increase the age instance variable by 1.
  2. amIOld() should perform the following conditional actions:
    • If age<13, print You are young..
    • If age>=13 and age<18, print You are a teenager..
    • Otherwise, print You are old..

Sample Input

4
-1
10
16
18

Sample Output

Age is not valid, setting age to 0.
You are young.
You are young.

You are young.
You are a teenager.

You are a teenager.
You are old.

You are old.
You are old.

You can solve the problem here.

HackerRank Day 4 Solution in Python

class Person:
    def __init__(self,initialAge):
        #Check is age is negative
        if initialAge<0:
            print("Age is not valid, setting age to 0.")
            self.age=0
        else:
            self.age=initialAge
    
    #Method to perform given conditional statements 
    def amIOld(self):
        #If age less than 13
        if self.age<13:
            print("You are young.")
        #If age greater than 13 and lesser than 18
        elif self.age>=13 and self.age<18:
            print("You are a teenager.")
        #If age greater than 18
        elifc self.age>18:
            print("You are old.")
    
    #Method to increment age
    def yearPasses(self):
        self.age+=1
        
t = int(input())
for i in range(0, t):
    age = int(input())         
    p = Person(age)  
    p.amIOld()
    for j in range(0, 3):
        p.yearPasses()       
    p.amIOld()
    print("")

Code Explanation

  • After getting the input, create an object for the Person class with input age as a parameter
  • Then in the constructor, check if the age is negative, then print Age is not valid, setting age to 0 and then setting the age value to 0. Else initialize age with the corresponding value
  • in the amIOld method check if the age is less than 13 and print You are young.
  • Then check if the age is greater than 13 and less than 18, then print You are a teenager.
  • If the age is greater than 18 then print You are old

Also Read:

Share:

Author: Ayush Purawr