Python Quick Reviews

Nov. 2, 2020 pexels-pixabay-35888.jpg Vuong Huynh

Comments

# This is a one-line Python comment - code blocks are so useful!
"""This type of comment is used to document the purpose of functions and classes."""

Declaration/Initialization

# Remember values, not variables, have data types.
# A variable can be reassigned to contain a different data type.
answer = 42
answer = "The answer is 42."

Data Types

boolean = True
number = 1.1
string = "Strings can be declared with single or double quotes."
list = ["Lists can have", 1, 2, 3, 4, "or more types together!"]
tuple = ("Tuples", "can have", "more than", 2, "elements!")
dictionary = {'one': 1, 'two': 2, 'three': 3}
variable_with_zero_data = None

Simple Logging

print("Printed!")

Conditionals

if cake == "delicious":
    return "Yes please!"
elif cake == "okay":
    return "I'll have a small piece."
else:
    return "No, thank you."

Loops

for item in list:
    print(item)

i = 1
while i < 5:
  print(i)
  i += 1

Functions

def divide(dividend, divisor):
    quotient = dividend // divisor
    remainder = dividend % divisor
    return quotient, remainder

def calculate_stuff(x, y):
    (q, r) = divide(x,y)
    print(q, r)

print(divide(7, 2))                 # (3, 1)
calculate_stuff(7,2)                # 3 1

Classes

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age 

    def birthday(self):
        self.age += 1

Python Practice

You can use this class to represent how classy someone or something is.

Classy is interchangeable with fancy. If you add fancy-looking items, you will increase your "classiness".

Create a function in Classy that takes a string as input and adds it to the items list.

Another method should calculate the classiness value based on the items.

The following items have classiness points associated with them:

tophat = 2

bowtie = 4

monocle = 5

class Classy():
    def __init__(self):
        self.items = []
    
# Function getClassiness is to calculate classiness points of each item
    def getClassiness(self):
        classiness_item = 0
        
        if len(self.items) > 0:
            for item in self.items:
                if item == "tophat" :
                    classiness_item += 2
                elif item == "bowtie" :
                    classiness_item += 4
                elif item == "monocle" :
                    classiness_item += 5
        return classiness_item

# Create function addItem to append new items
    def addItem(self, item):
        self.items.append(item)

# Test cases
me = Classy()

# Should be 0
print(me.getClassiness())

me.addItem("tophat")
# Should be 2
print(me.getClassiness())

me.addItem("bowtie")
me.addItem("jacket")
me.addItem("monocle")
# Should be 11
print(me.getClassiness())

me.addItem("bowtie")
# Should be 15
print(me.getClassiness())