30 Days of Code in HackerRank with Python (Day 4: Class vs. Instance)

Saptashwa Banerjee
2 min readJul 4, 2020

--

Objective
In this challenge, we’re going to learn about the difference between a class and an instance; because this is an Object Oriented concept, it’s only enabled in certain languages. Check out the Tutorial tab for learning materials and an instructional video!

Task
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 initialAge 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, you must 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 and age≥13, print You are a teenager..
  • Otherwise, print You are old..

To help you learn by example and complete this challenge, much of the code is provided for you, but you’ll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don’t worry if you don’t understand it all quite yet!

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.
Code for Day 4

Explanation
Here lets start from the line 21, looking at the sample input first “t” is a variable which take the total number of input. Then in the for loop we took the ages in the variable “age”,and then pass it to the class “Person” whose result is stored in the variable “p”. Now we have to create two instance:

p.yearPasses()

p.amIOld()

In the instance “p.yearPasses()” we have to simply increase the age by unity and the for loop in line “26” increases it 3 times.

And in the instance “p.amIOld()” simply we passed the given condition as given in the task

if(self.age < 13):

print(“You are young.”)

elif(self.age >= 13 and self.age < 18):

print(“You are a teenager.”)

else:

print(“You are old.”)

I hope it is clear till this one, now if the given age is in negative then we simply make it “0”.

if(initialAge < 0):

print(“Age is not valid, setting age to 0.”)

self.age = 0

else:

self.age = initialAg

So now you may have a moderate idea about class and instance, in a nutshell instance are present under a class. This program may be a little hard for beginner but soon you will be able to solve more such problems so stay tuned! And see you in Day 5.

--

--