PYTHON BASICS

NOTES ON PLURALSIGHT'S PYTHON GETTING STARTED COURSE
0

PYTHON 3

MEDIUM

last hacked on Jun 10, 2018

# Learning Python 3

1: Basics

Table of Contents


Java vs Python

Statically vs Dynamically Typed languages

// java
int answer = 32;
String name = "Python";
# python
answer = 42
name = "Python"
# this makes python a dynamically typed language

Except, we can do this:

def add_numbers(a: int, b: int) -> int:
   return a + b

Integers and Floats

answer = 42
pi = 3.1416

Strings

'Hello World' == "Hello World" == """Hello World"""

"hello".capitalize() == "Hello"
"hello".replace("e", "a") == "Hallo"
"hello".isalpha() == True
"123".isdigit() == True
"some,csv,values".split(",") == ["some", "csv", "values"]

String Format Function

name = "David"
machine = "Hal"

# the format function
"Nice to meet you {0}. I am {1}".format(name, machine)

# string interpolation
f"Nice to meet you {name}, I am {machine}"

Boolean and None

python_course = True
java_course = False

int(python_course) == 1
int(java_course) == 0

str(python_course) == "True"

alients_found = None

If Statements

number = 5
if number == 5:
  print("Number is 5")
else:
  print("Number is NOT 5")

# we can use the keyword `is` instead of `==` to check whether two variables are pointing at the same object

Truthy and Falsy Values

number = 5
if number:
  print("Number is defined and truthy")

text = "Python"
if text:
  print("Test is defined and truthy")

Boolean and None

python_course = True
if python_course:
  print("This will execute")

aliens_found = None
if aliens_found:
  print("This will NOT execute")

Skipping: * Not If * Multiple If Conditions * Ternary If Statements


Lists

student_names = []
student_names = ["Mark","Katarina","Jessica"]

student_names[0] == "Mark"
student_names[1] == "Katarina"
student_names[2] == "Jessica"

List Functions

student_names = []
student_names = ["Mark","Katarina","Jessica"]

student_names.append("Homer")

"Mark" in student_names == True

len(student_list) == 4
del student_names[2] # deletes "Jessica" and shifts elements accordingly

List Slicing

student_names = ["Mark", "Katarina", "Homer"]
student_names[1:] == ["Katarina", "Homer"]
student_names[1:-1] == ["Katarina", "Homer"]

Loops

For Loop

for name in student_names:
  print("Student name is {0}")

While Loops

x = 0
while x < 10:
  print("Count is {0}".format(x))
  x += 1

Infinite Loops

num = 10
while True:
  if num == 42:
    break
  print("Hello World")

Dictionaries

student = {
  "name": "David",
  "student_id": 12345,
  "feedback": None
}

Python dictionaries can easily be converted into JSON objects, so they are very useful in Web Development.

List of Dictionaries

all_students = [
  {"name": "David", "student_id": 12345, "feedback": None},
  {"name": "Jessica", "student_id": 12346, "feedback": None},
  {"name": "Erik", "student_id": 12347, "feedback": None}
]

Dictionary Data

student["name"] == "David"
student["last_name"] == KeyError
student.get("last_name", "Unknown") == "Unknown"
student.keys() = ["name", "student_id", "feedback"] # super useful
student.values() = ["David", 12345, None ]
student["name"] = "David"
del student["name"]

Exceptions

KeyError Exception Handling

student = {
    "name": "David",
    "student_id": 12345,
    "feedback": None
}

try:
    last_name = student["last_name"]
except KeyError:
    print("Error finding last_name!")
print("This code executes!")

TypeError Exception Handling

student = {
    "name": "David",
    "student_id": 12345,
    "feedback": None
}

student["last_name"] = "Campos"

try:
    last_name = student["last_name"]
    print(last_name)
    numbered_last_name = 3 + "last_name"
except KeyError:
    print("Error finding last_name!")
except TypeError:
    print("Can't add these two together!")
print("This code executes!")

General Exception Handling

student = {
    "name": "David",
    "student_id": 12345,
    "feedback": None
}

student["last_name"] = "Campos"

try:
    last_name = student["last_name"]
    print(last_name)
    numbered_last_name = 3 + "last_name"
except KeyError:
    print("Error finding last_name!")
except TypeError:
    print("Can't add these two together!")
except Exception:
    print("Unknown error")
print("This code executes!")

We probably want more information about whatever error is happening, so we throw the error generated.

student = {
    "name": "David",
    "student_id": 12345,
    "feedback": None
}

student["last_name"] = "Campos"

try:
    last_name = student["last_name"]
    print(last_name)
    numbered_last_name = 3 + "last_name" # this relates to
except KeyError:
    print("Error finding last_name!")
except TypeError as error:
    print("Can't add these two together!")
    print(error)
# except Exception:
#     print("Unknown error")
print("This code executes!")

Other Data Types

complex
long # only in Python 2
bytes and bytearray
tuple = (3,3,1,"Mark") # like list, but immutable
set and frozenset
set([3,2,1]) # etc

2: Functions, Files, Yield, and Lambda

Our App - PyStudentManager

--

Functions

print("Hello World")
str(3) == "3"
int("15") == 15
username = input("Enter the user's name: ")

students = []

def get_students_titlecase():
  students_titlecase = []
  for student in students:
    students_titlecase = student.title()
    return students_titlecase

def print_students_titlecase():
  students_titlecase = []
  for student in students:
    students_titlecase = student.title()
  print(students_titlecase)

def add_student(name):
  students.append(name)

student_list = get_students_titlecase()

Function Arguments

students = []


def get_students_titlecase():
    students_titlecase = []
    for student in students:
        students_titlecase = student.title()
    return students_titlecase


def print_students_titlecase():
    students_titlecase = []
    for student in students:
        students_titlecase = student.title()
    print(students_titlecase)


def add_student(name, student_id=332):
    student = {"name": name, "student_id": student_id}
    students.append(student)


# learning *args
def print_var_args(name, *args):
    print(name)
    print(args)


# learning *kwargs
def print_var_kwargs(name, **kwargs):
    print(name)
    print(kwargs["description"], kwargs["feedback"])

student_list = get_students_titlecase()

add_student(name="Mark", student_id=15)

print_var_args(
    "Mark",
    "Loves Python",
    None,
    "Hello",
    True
)

print_var_kwargs(
    "Mark",
    description="Loves Python",
    feedback=None,
    pluralsight_subscriber=True
)

Adding Students to Our App

students = []


def get_students_titlecase():
    students_titlecase = []
    for student in students:
        students_titlecase = student["name"].title()
        # method title() returns a copy of the string in which
        # the first characters of all the words are capitalized
    return students_titlecase


def print_students_titlecase():
    students_titlecase = get_students_titlecase()
    print(students_titlecase)


def add_student(name, student_id=332):
    student = {"name": name, "student_id": student_id}
    students.append(student)


def do_you_want_to_add_student(answer):
    while answer == "Yes":
        student_name = input("Enter student name: ")
        student_id = input("Enter student ID: ")
        add_student(student_name, student_id)
        answer = input("Do you want to add another student?: ")
    for student in students:
        print(student["name"])


students_list = get_students_titlecase()

# student_name = input("Enter student name: ")
# student_id = input("Enter student ID: ")

# add_student(student_name, student_id)
# print_students_titlecase()


answer = input("Do you want to add a student?: ")
do_you_want_to_add_student(answer)

Nested Functions and Closures

Essentially, we can have functions inside of functions.

def get_students():
    students = ["mark", "james"]

    def get_students_titlecase():
        students_titlecase()
        for student in students:
            students_titlecase.append(student.title())
        return student_titlecase
    students_titlecase_names = get_students_titlecase()
    print(students_titlecase_names)

--

Opening, Reading, and Writing Files

functions.py

students = []


def get_students_titlecase():
    students_titlecase = []
    for student in students:
        students_titlecase.append(student["name"].title())
        # method title() returns a copy of the string in which
        # the first characters of all the words are capitalized
    return students_titlecase


def print_students_titlecase():
    students_titlecase = get_students_titlecase()
    print(students_titlecase)


def add_student(name, student_id=332):
    student = {"name": name, "student_id": student_id}
    students.append(student)


def save_file(student):
    try:
        f = open("students.txt", "a")
        f.write(student + "\n")
        f.close()
    except Exception:
        print("Could not save file")

def read_file():
    try:
        f = open("students.txt", "r")
        for student in f.readlines():
            add_student(student)
        f.close()
    except Exception:
        print("Could not read file")

student_list = get_students_titlecase()

read_file()
print_students_titlecase()

student_name = input("Enter student name: ")
student_id = input("Enter student ID: ")

add_student(student_name, student_id)
save_file(student_name)

students.txt

David
James

Yield

students = []

def read_file():
    try:
        f = open("students.txt", "r")
        for student in read_students(f):
            students.append(student)
        f.close()
        print("Reading...")
    except Exception:
        print("Could not read file")

def read_students(f):
    for line in f:
        yield line

read_file()
print(students)

Lambda Functions

def double(x):
  return x * 2
double = lambda x: x * 2

# useful when writing higher order functions
# i.e. functions that take other functions as arguments/parameters
double(5) == 10

Summary


Object Oriented Programming - Classes and Why Do We Need Them?

Module Overview

Classes and Why Do We Need Them?

students = []

class Student:

    school_name = "Springfield Elementary"

    def __init__(self, name, student_id=332):
        self.name = name
        self.student_id = student_id
        students.append(self)

    def __str__(self):
        return "Student" + self.name

    def get_name_capitalize(self):
        return self.name.capitalize()

    def get_school_name(self):
        return self.school_name

# here we practice inheritance & polymorphism
class HighSchoolStudent(Student): # high school student inherits from student

    school_name = "Some High School"

    def get_school_name(self):
        return "some other shit"

    def get_name_capitalize(self):
        original_value = super().get_name_capitalize() # here we access the super-class method
        return original_value + "-HS" # then we override the value

COMMENTS







keep exploring!

back to all projects