Python - Other

Inheritance

Chef.py

class Chef:

    @staticmethod
    def make_chicken(self):
        print("The chef makes a chicken.")

    @staticmethod
    def make_salad(self):
        print("The chef makes a salad.")

    @staticmethod
    def make_special_dish(self):
        print("The chef makes bbq ribs.")


ChineseChef.py

from Chef import Chef


class ChineseChef(Chef):

    @staticmethod
    def make_special_dish(self):
        print("The chef makes orange chicken.")

    @staticmethod
    def make_friend_rice(self):
        print("The chef makes fried rice.")


from Chef import Chef
from ChineseChef import ChineseChef

myChef = Chef()
myChef.make_chicken(myChef)
myChef.make_special_dish(myChef)

myChineseChef = ChineseChef()
myChineseChef.make_chicken(myChineseChef)
myChineseChef.make_special_dish(myChineseChef)

//Output : The chef makes a chicken.
//         The chef makes bbq ribs.
//         The chef makes a chicken.
//         The chef makes orange chicken.

LCM of Two Numbers

# To find LCM of two numbers
def lcm(num1, num2):
    if num1 > num2:
        greater = numl
    else:
        greater = num2

    while True:
        if (greater % num1 == 0) and (greater % num2 == 0):
            break
        greater += 1
    return greater

print(f'lcm = {lcm(12, 14)}')

List Functions

lucky_number = [4, 8, 15, 16, 23, 42]
friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"]

print(friends)
//Output : ['Kevin', 'Karen', 'Jim', 'Oscar', 'Toby']

friends.extend(list(map(str, lucky_number)))
print(friends)
//Output : ['Kevin', 'Karen', 'Jim', 'Oscar', 'Toby', '4', '8', '15', '16', '23', '42']

friends.append("Creed")
print(friends)
//Output : ['Kevin', 'Karen', 'Jim', 'Oscar', 'Toby', '4', '8', '15', '16', '23', '42', 'Creed']

friends.insert(1, "Kelly")
print(friends)
//Output : ['Kevin', 'Kelly', 'Karen', 'Jim', 'Oscar', 'Toby', '4', '8', '15', '16', '23', '42', 'Creed']

friends.remove("Jim")
print(friends)
//Output : ['Kevin', 'Kelly', 'Karen', 'Oscar', 'Toby', '4', '8', '15', '16', '23', '42', 'Creed']

friends.pop()
print(friends)
//Output : ['Kevin', 'Kelly', 'Karen', 'Oscar', 'Toby', '4', '8', '15', '16', '23', '42']

friends.sort()
print(friends)
//Output : ['15', '16', '23', '4', '42', '8', 'Karen', 'Kelly', 'Kevin', 'Oscar', 'Toby']

friends.reverse()
print(friends)
//Output : ['Toby', 'Oscar', 'Kevin', 'Kelly', 'Karen', '8', '42', '4', '23', '16', '15']

print(friends.count("Kevin"))
//Output : 1

friends2 = friends.copy()

print(friends2)
//Output : ['Toby', 'Oscar', 'Kevin', 'Kelly', 'Karen', '8', '42', '4', '23', '16', '15']

friends.clear()
print(friends)
//Output : []

Lists

friends = ["Kevin", 2, False]
friends[1] = "Mike"

print(friends)
//Output : ['Kevin', 'Mike', False]
print(friends[0])
//Output : Kevin
print(friends[-1])
//Output : False
print(friends[1:])
//Output : ['Mike', False]
print(friends[1:2])
//Output : ['Mike']
print(friends.index("Kevin"))
//Output : 0

Mad Libs Game

color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
celebrity = input("Enter a celebrity: ")

print("Roses are " + color)
print(plural_noun + " are blue")
print("I love " + celebrity)
//Output : Enter a color: red
//         Enter a plural noun: they
//         Enter a celebrity: you
//         Roses are red
//         they are blue
//         I love you

Modules and Pip

useful_tools.py

import random

feet_in_mile = 5280
meters_in_kilometer = 1000
beatles = ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Star"]


def get_file_ext(filename):
    return filename[filename.index(".") + 1:]


def roll_dice(num):
    return random.randint(1, num)


import useful_tools as tools

print(tools.roll_dice(10))
//Output : 6


Object Functions

Student.py

class Student:

    def __init__(self, name, major, gpa, is_on_probation):
        self.name = name
        self.major = major
        self.gpa = gpa
        self.is_on_probation = is_on_probation

    def on_honor_roll(self):
        if self.gpa >= 3.5:
            return True
        else:
            return False


from Student import  Student

student1 = Student("Oscar", "Accounting", 3.1, False)
student2 = Student("Phyllis", "Business", 3.8, False)

print(student1.on_honor_roll())
//Output : False

print(student2.on_honor_roll())
//Output : True

Printing Prime Numbers

# printing prime numbers in a range
lower = 100
upper = 200
for num in range(lower, upper+1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
        else:
            print(num) # prime

Python Interpreter

Window

Open CMD and type python3.

Reading Files

Mode

r - Opens a file for reading. (default)

w - Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

x - Opens a file for exclusive creation. If the file already exists, the operation fails.

a - Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.

t - Opens in text mode. (default)

b - Opens in binary mode.

+ - Opens a file for updating. (reading and writing)


employees.txt

Jim - Salesman
Dwight - Salesman
Pam - Receptionist
Michael - Manager
Oscar - Accountant
Toby - Human Resources
Kelly - Customer Service


employee_file = open("../employees.txt", "r")

if employee_file.readable():
    print(employee_file.read())
else:
    print("Access denied.")

employee_file.close()

//Output : Jim - Salesman
//         Dwight - Salesman
//         Pam - Receptionist
//         Michael - Manager
//         Oscar - Accountant
//         Toby - Human Resources
//         Kelly - Customer Service


employee_file = open("../employees.txt", "r")

if employee_file.readable():
    print(employee_file.readline())
else:
    print("Access denied.")

employee_file.close()

//Output : Jim - Salesman


employee_file = open("../employees.txt", "r")

if employee_file.readable():
    print(employee_file.readlines()[1])
else:
    print("Access denied.")

employee_file.close()

//Output : Dwight - Salesman


employee_file = open("../employees.txt", "r")

if employee_file.readable():
    for employee in employee_file.readlines():
        print(employee)
else:
    print("Access denied.")

employee_file.close()

//Output : Jim - Salesman
//          
//         Dwight - Salesman
//          
//         Pam - Receptionist
//          
//         Michael - Manager
//          
//         Oscar - Accountant
//          
//         Toby - Human Resources
//          
//         Kelly - Customer Service


Return Statement

def cube(num):
  print("code")
  return pow(num, 3)


result = cube(4)
print(result)
//Output : code
//         64

Reverse a Given Number

# reversing a given number
def rev_num(num):
    rev = 0
    while num > 0:
        reminder = num % 10
        rev = (rev * 10) + reminder
        num = num // 10
    return rev

print(f"reverse of the given number is {rev_num(56789)}")