3:Class vs. Instance in Python

Class vs. Instance in Python


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

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




class Person:
    def __init__(self,initialAge):
        self.age = initialAge
        if self.age <=0:
            print('Age is not valid, setting age to 0.')
        # Add some more code to run some checks on initialAge
    def amIOld(self):
        if self.age < 13:
            print('You are young.')
        elif (13<=self.age< 18):
            print('You are a teenager.')
        else:
            print('You are old.')
    # Do some computations in here and print out the correct statement to the console
    def yearPasses(self):
        self.age +=1
 # Already provided by Hackerank in the challenge!
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("")

 

Comments

Popular posts from this blog

15: Linked List(python)