30 Day code challenge- python

Ganesh Uthiravasagam
2 min readMar 11, 2021

--

Day 4 - Class vs Instance

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. Besides, 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 age≥13 and age < 18, print You are a teenager.
  • Otherwise, print You are old.
Sample input and output

Input Format

The first line contains an integer, T (the number of test cases), and the T subsequent lines each contain an integer denoting the age of a Person instance.

Output Format

Complete the method definitions provided in the editor so they meet the specifications outlined above; the code to test your work is already in the editor. If your methods are implemented correctly, each test case will print 2 or 3 lines.

Solution

Explanation

initialAge = -1, Since initialAge<0 so age is set to 0 and prints “Age is not valid setting to 0” followed by the young message. Three years pass and age=3, so we print the young message again.

initialAge = 10, since it’s less than 13, the output will be “You are young”, After passing three years the value becomes 13 and “You are a teenager gets printed” similarly other values are estimated.

Bonus Tip: __init__ method is known as constructor which must be initiated while building a class. OOPs, concept is very important when building projects which makes the code readable.

See you on day 5

--

--

No responses yet