DEV Community

M__
M__

Posted on

DAY 3 & 4: Conditions, Classes & Instances

Hello there 🙂,
Today I will catch you up on two challenges that I did as they are short.
The first one was on Conditions which I briefly spoke about on my previous post. The question was testing one's ability to work with conditional operators:
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

''' This is the function I created and if you call it with different arguments, you will get the various outputs'''

def checknum(N):
    if N%2 == 0  and N in range(2,5):
        print('Not Weird')
    elif N%2 == 0  and N in range(6,20):
        print('Weird')
    elif N%2 == 0  and N> 20:
        print('Not Weird')
    else:
        print('Weird')
Enter fullscreen mode Exit fullscreen mode

The next challenge was about Object Oriented Programming. Classes are a part of Object Oriented programming and an instance can be looked at as an object of the class. I learnt that a class is like a blueprint that can be used to make objects based on its specifications i.e. the attributes/properties and methods.

This task required you to make a class(Person) with an instance variable and then also have a constructor that takes a parameter. One was also required to have two instance methods (yearPasses() and amIOld()) .
My important take away from this task that is worth noting was that:
• An instance variable is unique to an object and is declared in the class constructor.
• A class variable is not unique and shared by all objects of the class.

class Person:

    def __init__(self,initialAge):
        self.age = initialAge
        if self.age <0:
            self.age = 0
            print('Age is not valid, setting age to 0')

    def amIOld(self):
        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')

    def yearPasses(self):
        self.age +=1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)