Python 3.4 - Coding Practice

The modulo operator:

for i in range(10):
    print(i, i%2,)
    if i%2 == 0:
        print('no remainder')
    else:
        print('you have a remainder')

Assigning variables and basic math operators:

x, r, g, z = (12, 34, 34, 45)

print(x + g)

print(r + g + x)

t = [1,2,3,4,5]

print(len(t))

t.append(6)

t.pop(0)

print(t)

Classes contain functions and attributes for that class. You can assign a variable and/or function to a class.

class Car:
    color = "blue"    def drive(self):
        print('i am driving now')
    def paint_car(self, color):
        self.car_color = color



newcar = Car()
othercar = Car()

print(newcar.color)

print(othercar.color)

newcar.paint_car('yellow')

print(newcar.car_color)

By using classes and assigning functions to the class.  You can then create an instance of that class and assign different attributes and functions to that instance.

class Car:
    def __init__(self, color, model):
        """
        :rtype: object        """        self.color = color
        self.model = model
        self.engine = 'off'
    def start_engine(self):
        if self.engine == 'off':
            print('starting engine')
            self.engine = 'on'        else:
            print('the engine is running')

    def stop_engine(self):
        if self.engine == 'on':
            print('stop engine')
        else:
            print('engine is off')

    def drive(self):
        if self.engine == "on":
            print('driving the car')
        else:
            print('engine needs to be on first')

    def display_car(self):
        print(self.color)
        print(self.model)
        print("the engine is " + self.engine)


mycar = Car('red', 'subaru')


mycar.display_car()
mycar.start_engine()
mycar.stop_engine()

You can have an instance object inherit the class of another class:

class Car:

    def __init__(self):
        self.color = 'blue'        self.model = 'subaru'        self.engine = False
    def start_engine(self):
        print("starting the engine")
        self.engine = True
    def stop_engine(self):
        print('turning off the engine')
        self.engine = False
    def drive(self):
        if self.engine:
            print('driving the car')
        else:
            print('you need to start the engine first')

class Honda(Car):
    pass
mycar = Honda()
mycar.drive()



So you can create a class and have people input data into that class and store it and do things with the data, i.e. a database.



Comments

Popular posts from this blog

Pyhton 3.4 - Continue

Conversations Ongoing: Valuing Modernization in Early European History

Conversations Ongoing: A Bunch of Amateurs