Python
Object Oriented Programming
Before We Begin
Let’s Cover A Few Things
Class Rules
Class Rules
Class Rules
Class Rules
Class Rules
Class Rules
Class Rules
Class Rules
You Are Never “Caught Up”
Computing Foundations
What are the components of a computer that allows the code to run?
Physical Devices
The Brains - Central Processing Unit
Data Storage & Programming Instructions: 1 Byte = 8 Bits
How is Data Stored?
Permanent Storage
Display
Converts to Machine Code
High Level Languages - Human REadable
What is Programming
What is Programming
Statements & Syntax
BASIC LET Balance = 500
AppleScript set balance to 500
Java balance = 500;
COBOL MOVE 500 TO BALANCE
C# int balance = 500;
Javascript var balance = 500; (Now “let” and “const”)
Picking the Right Language
Procedural: a systematic order of statements, functions and commands to complete a computational task or program.
Functional:a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
Object Oriented:like procedural programming, but it encapsulates data and behavior into objects.
Programming Language vs. Scripting Language
Programming (Native)
Scripting
High Level vs. Low Level
What is Python?
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
Why Python?
Important!!!
Python 2 vs. Python 3
Everything we’re going to be doing is with Python 3.
When looking up resources, make sure you are getting info on Python 3!
DropBox
Spotify
Etc…
All Built Using Python
What do you need to get started?
Online IDE
Using Replit
Using Replit
Using Replit
Your Cheat Sheet
What Can You Do With Python?
Key Terms
Key Terms
Key Terms
Key Terms
Key Terms
Key Words
Syntax
What is Computer Science?
An aside… This class is far more than just learning how to code. This class is about learning to solve problems. Computer Science is the study of computers and computational systems. Unlike electrical and computer engineers, computer scientists deal mostly with software and software systems; this includes their theory, design, development, and application. This is class goes beyond just theory and is focused on applied applications of that theory.
Computer Science includes artificial intelligence, computer systems and networks, security, database systems, vision and graphics, analytics, programming languages and more.
Although knowing how to program is essential to the study of computer science, it is only one element of the field. Computer scientists design and analyze algorithms to solve programs and study the performance of computer hardware and software. The problems that computer scientists encounter range from the abstract (what can computers do) to the tangible (designing the actual application.
Using Codecademy…
Einstein is quoted as having said that if he had one hour to save the world he would spend fifty-five minutes defining the problem and only five minutes finding the solution.This quote does illustrate an important point: before jumping right into solving a problem, we should step back and invest time and effort to improve our understanding of it.
~Passuello
Let’s Get Back To Understanding Python
Print Statement
Comments
# ← Creates Comment
Strings
“Strings”
Multiline String
my_story = ```
Hello� There� Ninja
```
Variables
= assignment operator.
Errors
# Two common errors that we encounter while writing Python are SyntaxError and NameError.
# SyntaxError means there is something wrong with the way your program is written — punctuation that does not belong, a command where it is not expected, or a missing parenthesis can all trigger a SyntaxError.
# A NameError occurs when the Python interpreter sees a word it does not recognize. Code that contains something that looks like a variable but was never defined will throw a NameError.
More Errors
Numbers
Calculations, Exponents & Modulo
Changing Numbers (Reassigning Values)
Concatenation
Plus Equals += (Increments)
Minus Equals (Decrement)
Article - Input
user_input = input(“Please enter something here: ”)
Hackathon - Pencil
Multiline Art - My Number 2 Pencil.
Create a #2 pencil using a multiline string.
Bonus Points: Use a function/loop and animate the pencil drawing a line (on loop).
Hackathon - Echo Chatbot
Create an app (“Chatbot”) that echoes back anything that the user inputs.
Git & GitHub
Introduction to Functions
What are functions?
What diet did the ghost developer go on?
BOOOOOLEAN
Why Functions?
DRY! Don’t Repeat Yourself.
DRY! Don’t Repeat Yourself.
DRY! Don’t Repeat Yourself.
How many times have you given the same advice, or directions, or whatever over and over again?
With functions, you would be able to write the code once and then call it whenever someone needed it.
defINING A Function
Let’s say you worked in a shop in NYC and someone asked you for directions every couple hours…
A function consists of many parts, so let’s first get familiar with its core - a function definition.
Calling a Function
The process of executing the code inside the body of a function is known as calling it (This is also known as “executing a function”). To call a function in Python, type out its name followed by parentheses ( ).
Reminder about “White Space”
In Python, the amount of whitespace tells the computer what is part of a function and what is not part of that function.If we wanted to write another statement outside of trip_welcome(), we would have to unindent the new line.
Parameters
Function parameters allow our function to accept data as an input value. We list the parameters a function takes as input between the parentheses of a function ( ).
Parameters Cont…
Multiple Parameters
Using a single parameter is useful but functions let us use as many parameters as we want! That way, we can pass in more than one input to our functions.
Commas separate the parameters.
Hackathon - Bank Balance
How many programmers does it take to change a light bulb?
None. It’s a hardware problem.
Types of Arguments
Positional - Keyword - Default
Built-In Functions vs. User Defined Functions
Hackathon - Computer Shopping
With the given variables, calculate the following:
.
Javascript
C#
Java
Returns
At this point, our functions have been using print() to help us visualize the output in our interpreter. Functions can also return a value to the program so that this value can be modified or used later. We use the Python keyword “return” to do this.
Why Use Returns?
The return statement allows a function to pass a value back to the caller, which can be used in other parts of the program.
Without return, the function can only print values or modify data, but it cannot pass data back for further use.
Returns
Important note: The return statement is used in a function to send a result back to the part of the code that called the function. It allows the function to produce a value that can be stored in a variable or used in other calculations.
Without a return statement, a function can perform actions like printing or modifying data, but it won't produce a result that can be reused elsewhere in the code.
Returns Example
Multiple Returns
Sometimes we may want to return more than one value from a function. We can return several values by separating them with a comma. Take a look at this example of a function that allows users in our travel application to check the upcoming week’s weather (starting on Monday):
Multiple Returns II
Return Review
Why return is Important:
Quiz 2: Functions
Control Flow
WAKE UP
Get Dress for School
After sleeping in, Get Dress for the day.
Pajama Day
Casual Clothes Day
Walk to school
Grab Umbrella & walk to school
Logic Gates != Bill Gates
Control Flow
You wake up and think, “Ugh. Is it a weekday?”
If so, you have to get up and get dressed and get ready for work or school. If not, you can sleep in a bit longer and catch a couple extra Z’s. But alas, it is a weekday, so you are up and dressed and you go to look outside, “What’s the weather like? Do I need an umbrella?”
These questions and decisions control the flow of your morning, each step and result is a product of the conditions of the day and your surroundings. Your computer, just like you, goes through a similar flow every time it executes code. A program will run (wake up) and start moving through its checklists, is this condition met, is that condition met, okay let’s execute this code and return that value.
This is the control flow of your program. In Python, your script will execute from the top down, until there is nothing left to run. It is your job to include gateways, known as conditional statements, to tell the computer when it should execute certain blocks of code. If these conditions are met, then run this function.
Boolean Expression
In order to build control flow into our program, we want to be able to check if something is true or not. A boolean expression is a statement that can either be True or False.
Boolean - Consider the Following
Consider the phrase:�Friday is the best day of the week… Is this a boolean expression?
No, this statement is an opinion and is not objectively True or False. Someone else might say that “Wednesday is the best weekday,” and their statement would be no less True or False than the one above.
How about the phrase:�Sunday starts with the letter 'C'.
Is this a boolean expression?
Yes! This expression can only be True or False, which makes it a boolean expression. Even though the statement itself is false (Sunday starts with the letter ‘C’), it is still a boolean expression.
Boolean
x = 5�y = 5�z = 10�x == y (True) ← This is the Boolean�x == z (False) ← This is the Boolean
Remember “=” is an assignment operator. It is assigning the value of 5 to the variable x. It’s a command.
“==” Is a condition check. Is the condition True or False. Is x equal to y? Is x = z?
== Is Equal To?
!= Is Not Equal To?
> Is Greater Than?
< Is Less Than?
>= Is Greater Than or Equal To
<= Is Less Than Or Equal To
Boolean
this_meme == funny
True
If Statement
Boolean variables and expressions are essential because they are the building blocks of conditional statements.
“IF” something is True, execute a block of code.
Relational Operators… Continued
So far we know two relational operators, equals and not equals, but there are more:��> greater than�>= greater than or equal to�< less than�<= less than or equal to
Let’s say we’re running a movie streaming platform and we want to write a program that checks if our users are over 13 when showing them a PG-13 movie. We could write something like:
if age <= 13:� print("Sorry, parental control required")
This function will take the user’s age and compare it to the number 13. If age is less than or equal to 13, it will print out a message.
Relational Operators… Challenge
The nearby college, Calvin Coolidge’s Cool College (or 4C, as the locals call it) requires students to earn 120 credits to graduate.
Write an if statement that checks if the student has enough credits to graduate. If they do, print the string:
"You have enough credits to graduate!"
Can a student with 120 credits graduate from Calvin Coolidge’s Cool College?
Boolean Operator: and
Often, the conditions you want to check in your conditional statement will require more than one boolean expression to cover. In these cases, you can build larger boolean expressions using boolean operators. These operators (also known as logical operators) combine smaller boolean expressions into larger boolean expressions.
Boolean Operators: or
The boolean operator "or" combines two expressions into a larger expression that is True if either component is True.
�Consider the statement:
Oranges are a fruit or apples are a vegetable.
This statement is composed of two expressions: oranges are a fruit which is True and apples are a vegetable which is False. Because the two expressions are connected by the “or” operator, the entire statement is True. Only one component needs to be True for an or statement to be True.
Boolean “or” Operator Continued
True or (3 + 4 == 7) # True
(1 - 1 == 0) or False # True
(2 < 0) or True # True
(3 == 8) or (3 > 4) # False
Notice that each or statement that has at least one True component is True, but the final statement has two False components, so it is False.
or Challenge
The registrar’s office at Calvin Coolidge’s Cool College has another request. They want to send out a mailer with information on the commencement ceremonies to students who have met at least one requirement for graduation (120 credits or 2.0 GPA).
Write an if statement that checks if a student either has 120 or more credits or a GPA 2.0 or higher, and if so prints:
"You have met at least one of the requirements."
or Solution
Boolean Operators: not
not
This operator is straightforward: when applied to any boolean expression it reverses the boolean value. So if we have a True statement and apply a not operator we get a False statement.
not True == False
not False == True
not Challenge
The registrar’s office at Calvin Coolidge’s Cool College has been so impressed with your work so far that they have another task for you.
They want you to return to a previous if statement and add in several checks using and and not statements:
If a student’s credits is not greater or equal to 120, it should print:
"You do not have enough credits to graduate."
If their gpa is not greater or equal to 2.0, it should print:
"Your GPA is not high enough to graduate."
If their credits is not greater than or equal to 120 and their gpa is not greater than or equal to 2.0, it should print:
"You do not meet either requirement to graduate!"
Make sure your return value matches those strings exactly. Capitalization, punctuation, and spaces matter!
not Challenge Answer
Else Statements
Else statements allow us to elegantly describe what we want our code to do when certain conditions are not met.
if weekday:
print("wake up at 6:30")
else:
print("sleep in")
If/Else Challenge
Calvin Coolidge’s Cool College has another request for you. They want you to add an additional check to a previous if statement. If a student is failing to meet both graduation requirements, they want it to print:
"You do not meet the requirements to graduate."
Add an else statement to the existing if statement.
If/Else Challenge Answer
Else If Statements
We have if statements, we have else statements, we can also have elif statements.
We can use elif statements to control the order we want our program to check each of our conditional statements. First, the if statement is checked, then each elif statement is checked from top to bottom, then finally the else code is executed if none of the previous conditions have been met.
Elif
Elif Challenge
Calvin Coolidge’s Cool College has noticed that students prefer to get letter grades.
Write an if/elif/else statement that:
If grade is 90 or higher, print "A"
Else if grade is 80 or higher, print "B"
Else if grade is 70 or higher, print "C"
Else if grade is 60 or higher, print "D"
Else, print "F"
Elif Challenge Solution
Pennies From Heaven
Changifier Inc. needs software written for their new penny conversion device. This device collects as many pennies as a person will give it and converts it to Dollar Bills, Quarters, Dimes, Nickels and Pennies. But to save resources when a user drops pennies in the change counter, the device must return the denominations in the fewest amounts possible
Control Flow Review Challenge
Little Codey is an interplanetary space boxer, who is trying to win championship belts for various weight categories on other planets within the solar system.
Write a space.py program that helps Codey keep track of their target weight by:
Checks which number planet is equal to.
It should then compute their weight on the destination planet.
Here is the table of conversion:
# Planet Relative Gravity
1 Venus 0.91
2 Mars 0.38
3 Jupiter 2.34
4 Saturn 1.06
5 Uranus 0.92
6 Neptune 1.19
Python Control Flow Quiz
https://forms.gle/Y6usB4Bd9sMASLXV7
2026
This is the greatest Programming Meme You’ll ever See!
Data Structures and Loops
What is a List
heights = [61, 70, 67, 64]
What is a list?
heights = [61, 70, 67, 64]
Notice that:
What Can A List Contain?
Empty List
List Methods (Built-In Functions)
List Methods (Built-In Functions)
Append Sample
Growing a List: Plus (+)
Append Multiple Items?
Let’s look at some documentation:�Extend?�https://www.delftstack.com/howto/python/append-multiple-elements-python/
Accessing List Elements
Accessing List Elements: Negative Index
Modifying List Elements
Shrinking a List: Remove
Two-Dimensional (2D) Lists
Accessing 2D Lists
Modifying 2D Lists
Review
WHY STARBUCKS IS BETTER THAN DUNKIN…
Dictionaries (Data Structures)
What is a Dictionary (Data Structure)
Dictionaries
A Dictionary is a mutable, unordered collection of key-value pairs. Can be any data-type.
Mutable: mutable objects (Values) are objects whose state can be changed after they have been created. Mutable objects include lists, dictionaries, and sets. Immutable: (Keys) objects, on the other hand, cannot be changed after they have been created. Immutable objects include strings, numbers, and tuples.
Key-Value Pair: A key-value pair is a data structure that consists of a key and a value. The key is used to identify the value, and the value is the data itself. Key-value pairs are often used in dictionaries and hash tables.
Real-Life Analogy
Dictionary Syntax
KEY
VALUE
KEY
VALUE
Creating Dictionaries - Curly Braces
You define a dictionary using curly braces {}.
Key-value pairs are separated by colons :
student_grades = {
"Alice": 90,
"Bob": 85,
"Charlie": 92
}
Keys are names (e.g., "Alice"), and values are grades (e.g., 90).
Accessing Data
To access a value in a dictionary, use the key inside square brackets [].
Example:�student_grades = {
"Alice": 90,
"Bob": 85,
"Charlie": 92
}
student_1 = student_grades["Alice"]
print(student_1) # Output: 90
Accessing Values in a Dictionary
Utilizing keys to retrieve values using get() method.
Adding & Updating Data
You can add new key-value pairs or update existing ones.
student_grades = {
"Alice": 90,
"Bob": 85,
"Charlie": 92
}
student_grades["David"] = 88 # Adding data
student_grades["Bob"] = 87 # Updating Data
print(student_grades) # Outputs: {'Alice': 90, 'Bob': 87, 'Charlie': 92, 'David': 88}
Removing Data
You can remove a key-value pair using the del keyword or the pop() method.
student_grades = {
"Alice": 90,
"Bob": 85,
"Charlie": 92
}
del student_grades["Charlie"] # Example using del
student_grades.pop("Bob") # Example using pop()
print(student_grades) # Prints {'Alice': 90}
Checking for a Key
student_grades = {
"Alice": 90,
"Bob": 85,
"Charlie": 92
}
if "Alice" in student_grades:
print("Alice's grade is", student_grades["Alice"])
Looping Through a Dictionary
student_grades = {
"Alice": 90,
"Bob": 85,
"Charlie": 92
}
for name, grade in student_grades.items():
print(name, "has a grade of", grade)
Key Characteristics
Use Cases
Adding and Modifying Dictionary Entries
Removing Entries and Clearing the Dictionary
Iterating through Dictionaries
Nested Dictionaries
Loops
While & For
While Loop
Checks to see if a condition is true. If it is, it runs the code within the loop.
While Loops
For Loops
You have a list of data.
For loops iterate through each item in the list and runs a command.
For each item, do something.
For Loops
Built-In Libraries (Python Standard Libraries
Classes
In object-oriented programming, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
Class = Blue Print
What is a Class in Python?
In object-oriented programming (OOP), a class is like a blueprint or template for creating objects. Objects have member variables and methods associated with them. In Python, a class bundles data (attributes) and functions (methods) into a single unit.
It's a reusable blueprint.
The "Why": From Functions to Blueprints
Up until now, we've been using functions to organize actions and variables to store data. But what happens when the data and the actions are deeply connected?
Components of a Class
Attributes: These are the variables defined inside the class. They represent the state or data of the object. For instance, for a Dog class, attributes might be name, age, and breed.
Methods: These are functions defined inside the class. They represent the behaviors or actions an object can perform. For our Dog class, methods might include bark(), sleep(), or eat().
Constructor (__init__) method: This is a special method that gets called when an object is instantiated. It's typically used to initialize the attributes of the class.
Important Concepts Below…
Inheritance: Allows a class (child) to inherit attributes and methods from another class (parent). This promotes code reuse.
Encapsulation: It refers to restricting access to certain components of the class (like attributes) and making them private. In Python, this is achieved using single or double underscores before the attribute name, though it's more of a convention than strict privacy.
Polymorphism: It allows objects of different classes to be treated as objects of a common superclass. For instance, if both Dog and Cat classes have a speak() method, they can be called in the same manner, even if their individual implementations differ.
The class Keyword
Definition: A class is a template or blueprint for creating objects.
The Constructor: __init__()
This is a special method, often called the "initializer" or "constructor." It runs automatically one time when you create a new object from the class. Its job is to set up the object's initial state.
The self Parameter
This is the most crucial—and often most confusing—concept for students. self is how an object refers to itself from within the blueprint. It's the first parameter of every method inside a class.
Attributes (or Properties)
These are the variables that belong to an object. They represent the object's data or state. We define them inside __init__ using self.
Object (or Instance)
An object is a single, concrete creation based on the class blueprint. You can create as many objects as you want from a single class.
Methods
These are the functions that belong to a class. They define the actions or behaviors an object can perform. They always take self as their first parameter.
Methods Continued
Pothole Alert & Best Practices
Three Pillars of Object Oriented Programming
Inheritance: "Don't Reinvent the Wheel"
Encapsulation: "A Protective Barrier"
Polymorphism: "One Method, Many Forms"
Definition: Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. This means that a method can process objects differently depending on their class type, even if they share the same method name.
Polymorphism Explained
Example Explanation: Imagine a scenario where you have different animals that can make sounds. Each animal has a speak() method, but each one speaks differently. Polymorphism allows us to use the same method (speak()) but have different outcomes based on the object calling it.
Polymorphism Example
# Superclass
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
# This method is meant to be overridden by subclasses
return "Some generic animal sound"
# Subclass - Dog
class Dog(Animal):
def speak(self):
return "Woof!"
# Subclass - Cat
class Cat(Animal):
def speak(self):
return "Meow!"
# Subclass - Parrot
class Parrot(Animal):
def speak(self):
return "Squawk!"
# Function demonstrating polymorphism
def animal_sound(animal):
print(f"{animal.name} says: {animal.speak()}")
# Creating instances of each subclass
dog = Dog("Buddy")
cat = Cat("Whiskers")
parrot = Parrot("Polly")
# Demonstrating polymorphism
animal_sound(dog) # Outputs: Buddy says: Woof!
animal_sound(cat) # Outputs: Whiskers says: Meow!
animal_sound(parrot) # Outputs: Polly says: Squawk!
What Is Polymorphism, Really?
Polymorphism, in the context of object-oriented programming, means that different classes can be treated as instances of the same superclass, and they can respond to the same method call in their own specific way. The key to polymorphism is that the method signature is consistent across classes, but each subclass provides its own unique implementation.
Why Is the Superclass Important?
The superclass provides a common interface or method signature that the subclasses share. While it's true that each subclass could have its own speak() method without a superclass, the power of polymorphism comes when you work with instances of these subclasses through the reference of the superclass. This allows you to write code that can handle different types of objects uniformly.
Understanding Dependency on the Superclass
Polymorphism leverages the idea that the subclasses inherit from the superclass and override its methods. This means you can refer to different subclasses through the same superclass type, and polymorphism ensures that the appropriate subclass method is executed.
Expanded Polymorphism Example
# Superclass
class Animal:
def __init__(self, name, age, habitat):
self.name = name
self.age = age
self.habitat = habitat
def speak(self):
# This method will be overridden by subclasses
return "Some generic animal sound"
def info(self):
# This method provides information about the animal
return f"{self.name} is {self.age} years old and lives in the {self.habitat}."
class Parrot(Animal):
def __init__(self, name, age, habitat, can_talk):
# Call the superclass constructor to initialize inherited attributes
super().__init__(name, age, habitat)
self.can_talk = can_talk # New attribute specific to the Parrot class
def speak(self):
return "Squawk! I can talk!" if self.can_talk else "Squawk!"
def info(self):
# Extends the superclass method by adding talking ability information
talking_status = "can talk" if self.can_talk else "cannot talk"
return f"{super().info()} This parrot {talking_status}."
# Demonstrating inheritance and polymorphism
animals = [
Dog("Buddy", 5, "house", "Golden Retriever"),
Cat("Whiskers", 3, "apartment", "black"),
Parrot("Polly", 2, "jungle", True)
]
for animal in animals:
# Each object is treated as an instance of the superclass 'Animal'
print(animal.info()) # Polymorphic behavior: calls the overridden `info()` method
print(f"{animal.name} says: {animal.speak()}")
print()
class Dog(Animal):
def __init__(self, name, age, habitat, breed):
# Call the superclass constructor to initialize inherited attributes
super().__init__(name, age, habitat)
self.breed = breed # New attribute specific to the Dog class
def speak(self):
return "Woof!"
def info(self):
# Extends the superclass method by adding breed information
return f"{super().info()} It is a {self.breed} breed."
class Cat(Animal):
def __init__(self, name, age, habitat, fur_color):
# Call the superclass constructor to initialize inherited attributes
super().__init__(name, age, habitat)
self.fur_color = fur_color # New attribute specific to the Cat class
def speak(self):
return "Meow!"
def info(self):
# Extends the superclass method by adding fur color information
return f"{super().info()} It has {self.fur_color} fur."
Decorators
Classes
Vehicle
model(string)�make(string)�year (number)�vin (string)�sold (boolean)
drive_forward(function)�drive_reverse(function)�acceleration(function)
Car_1
Chevrolet�Impala�1997�87EEJSKSB9WSR�True
drive_forward(function)�drive_reverse(function)�acceleration(function)
Car_2
Nissan�Rogue�2022�8SDJSDI8MNDBR�True
drive_forward(function)�drive_reverse(function)�acceleration(function)
Car_3
Ford�Not Gonna Run�2004�FDG567FDBR�False
drive_forward(function)�drive_reverse(function)�acceleration(function)
How Are Classes Used?
Classes are used to model real-world objects or concepts. By defining a class, you can create multiple instances (objects) of that class. Each object will have its own separate set of attributes but will be able to perform the methods defined in the class.
How many houses can 1 brick be part of vs. How many houses can one set of blueprints create?
Example of a Class
Output
What are Classes and Object
Classes Quick Summary
Modules, Packages, Libraries & Frameworks
Think of adding coding cheats and pre-written blocks of code that upgrades your coding power.
Modules:
In Python, a module refers to a file containing executable code, which can define functions, classes, and variables. Modules help in segmenting code into manageable and reusable parts, allowing for better code organization and modular programming.
Frequently used Modules
math: Provides mathematical functions, including trigonometric, logarithmic, and arithmetic operations.
datetime: Supplies classes for manipulating dates and times.
os: Offers a way of using operating system-dependent functionality like reading or writing to the file system.
sys: Gives access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
json: Allows encoding and decoding JSON data, useful for data serialization and parsing.
** These are built-in to python.
Libraries:
A library is a collection of pre-compiled routines or functions that a program can use. These routines or functions are packaged in a manner that allows them to be used and reused by multiple programs. Libraries provide standardized solutions for common tasks, reduce the need for writing code from scratch, and ensure more reliable and optimized execution.
Frequently used Libraries
requests: A simple library for making HTTP requests.
numpy: A library for numerical operations and working with arrays.
pandas: Provides data structures and data analysis tools for the Python programming language.
matplotlib: A plotting library for creating static, animated, and interactive visualizations.
scipy: Used for high-level computations and builds on the numpy library.
** These need installed with “pip install name_of_package”
Packages:
In software engineering, a package is a specific form of modularization that groups related classes, functions, and data together. In Python, a package is a way of structuring related modules into a single directory hierarchy. It provides a means of organizing related modules in a namespace, typically using a directory structure.
Frequently used Packages
scikit-learn: A tool for data mining and data analysis, providing simple and efficient tools for predictive data analysis.
beautifulsoup4: Used for web scraping purposes to pull the data out of HTML and XML documents.
pillow (PIL Fork): A Python Imaging Library that adds image processing capabilities.
django-rest-framework: A powerful and flexible toolkit for building Web APIs on top of the Django framework.
tweepy: An easy-to-use Python library for accessing the Twitter API.
Frameworks:
A framework is a comprehensive software solution that provides a skeleton or blueprint for developers to build applications. Unlike libraries, which offer specific functionalities, frameworks dictate the architecture and structure of the application. They come with pre-written code, best practices, and conventions, enabling rapid application development by allowing developers to focus on unique application logic rather than the routine aspects of development.
Frequently used Frameworks
Django: A high-level web framework that encourages rapid development and clean, pragmatic design.
Flask: A micro web framework written in Python, known for its simplicity and fine-grained control.
Pyramid: A small, fast, down-to-earth, open-source Python web framework.
FastAPI: A modern, fast (high-performance) web framework for building APIs with Python based on standard Python type hints.
Tornado: A scalable, non-blocking web server and web application framework.
Module: Pyautogui
pyautogui is a Python module that provides functions to programmatically control the mouse and the keyboard. It allows developers to automate GUI (Graphical User Interface) tasks, making it especially useful for tasks like:
What is Automation?
Why Use Automation?
Key Features of pyautogui
Mouse Control: You can move the mouse pointer to specific coordinates, click, right-click, middle-click, drag, and scroll.
Keyboard Control: It allows you to simulate key presses, key releases, and typing.
Screenshot Utilities: You can take screenshots using pyautogui and even locate where a particular image is on the screen.
Message Boxes: It provides simple functions to display message boxes for user interaction.
Fail-Safes: To prevent scripts from running out of control, pyautogui has a fail-safe feature. Moving the mouse cursor to the top-left corner of the screen will raise an exception and stop the script.
PIP - Install
Example pyautogui
Remember to install the module using pip first, in the terminal.
Moving the Mouse
The moveTo(x, y, duration) function moves the mouse to the specified coordinates on the screen.
Clicking
Use the click() function to simulate mouse clicks.
Mouse Dragging
You can simulate mouse dragging using the dragTo() function.
Keyboard Automation
Typing
Pressing Keys
Hotkeys:
Screenshots
Taking a Screenshot:
�Locating an Image on Screen:
Module Test - Voting Automation
Challenge
Using any library, module, package or framework - create a bot that will vote for yourself. The more votes, the more likely you are to win.
Sekol → Create a new Google Forms Favorite Animal Voting Bot.
Youtube Algorithms.
���I/O
I/O in Python: Reading and Writing to Text Files
Input / Output = I/O
Understanding File Handling
What is Input/Output (I/O)?
Basic File Handling in Python
These are the basic operations are fundamental to interacting with files.
Modes you’ll actually use
Modes Model
open(<file path>, mode)
Relative or Absolute path to the file. (Including the extension)
A String (Character) indicates what you want to do with the file. "r" or "w" or "a" or "r+".
Opening a File
"r": Opens a file for reading.
"w": Opens a file for writing (creates if doesn't exist, overwrites if exists).
"a": Opens a file for appending (creates if doesn't exist).
"r+": Opens a file for reading and writing.
Writing to a Text File
Appending Data to a File
Reading from a File
Handling File Not Found Errors
File Context Managers (with open)
Looping Through File Contents
Questions
APIs and Python
APIs and Python
Thinking Algorithmically (Data Structures Main Course)
Definition: An algorithm is a set of step-by-step instructions for solving a problem or accomplishing a task. Every computerized device uses algorithms, which cut the time required to do things manually.
Where are algorithms used every day?
Thinking Algorithmically (Data Structures Main Course)
Thinking Algorithmically (Data Structures Main Course)
Thinking Algorithmically (and Data Structures)
Divisible by 3 Exercise
Divisible by 3 Solution
7,581,627 is divisible by 9, but 364,521 is not. Why?
Thinking Algorithmically (and Data Structures)
Coins and Probabilities Exercise
Can you think of anything that doesn’t use an algorithm?
Long Division
Components Of Division
Today’s Hackathon - Algorithmic Games
Group up in a teams of 3-4 people and create the following algorithmic applications:
Encryption
Code Testing (AKA QA, AKA Continuous Testing)
Why Testing is Essential and How it Fits into Software Development?
What is Code Testing?
Code testing is like a “safety check” for your code
Why Code Testing is Important?
Imagine making a game – you wouldn’t want players to fall through the floor because of a bug!
Types of Code Testing in Software Development
Let's Jump Into Python Code Testing
Debugging is an essential part of writing code. It helps you find and fix errors, verify your program’s logic, and ultimately improve your code’s quality and reliability. One of Python’s most powerful and accessible tools for debugging is the built-in pdb module, a debugger that lets you interact with your code as it runs, check variable values, inspect program flow, and even change variable states on the fly.
Setting Up pdb
To use pdb, you need to import it in your code with:
import pdb # Import the debugger
Then, you can place a breakpoint in your code where you want it to pause execution with:
pdb.set_trace() # Set a breakpoint
When the program reaches pdb.set_trace(), it will pause, and you’ll enter the pdb interactive console. Here, you can use various commands to inspect, step through, and control the flow of your program.
Basic Commands in pdb
Once the code is paused at a breakpoint, you’ll have access to several commands in the pdb console. Here are the most commonly used ones:
Inspecting Variables and Expressions
When you’re in the pdb console, you can directly type variable names or expressions to see their current values. This lets you check if variables hold expected values or if something went wrong.
For example, if you have the following code:
import pdb
def add_numbers(a, b):
pdb.set_trace() # Start debugging here
result = a + b
return result
print(add_numbers(3, 4))
Once the program pauses at pdb.set_trace(), you can:
Setting Breakpoints Dynamically
With pdb, you can also set breakpoints dynamically in the console. This is useful if you decide you want to stop at specific parts of your code during a debugging session:
b <line_number>: Sets a breakpoint at a specific line number in the current file.
For example, b 10 sets a breakpoint at line 10.
b <filename>:<line_number>: Sets a breakpoint at a specific line in another file.
Example: b my_module.py:15 sets a breakpoint in my_module.py at line 15.
To clear breakpoints:
cl <breakpoint_number>: Clears a specific breakpoint by its index.
cl: Clears all breakpoints if no number is specified.
Tracking Execution Flow
The l (list) command shows a few lines of code around the current line, which helps provide context. It displays the code in chunks of 11 lines around the line being executed, which is useful for seeing the immediate code context without leaving the debugger.
l # Lists surrounding code
You can also use w (where) to see the current call stack, which tells you the sequence of function calls that led to the current breakpoint. This helps track the execution flow, especially in programs with nested functions or multiple function calls.
Changing Values on the Fly
While in a pdb session, you can assign new values to variables to see how it affects the code execution. This is especially helpful when testing hypothetical situations or seeing what happens with different data.
a = 10 # Changes the value of `a` to 10
result = a + b # Re-runs this line manually to check the new resul
Debugging with Conditional Breakpoints
Conditional breakpoints let you specify a condition for when pdb should stop at a breakpoint. This is helpful when you want the program to pause only under certain conditions, like a specific value of a variable.
Set a conditional breakpoint:
b <line_number>, <condition>
Example:
b 15, x == 5 # Stop at line 15 only if x equals 5
This way, you can avoid repetitive stopping by pdb unless a condition is met.
Practical Example: Debugging a Function
Here’s an example that demonstrates a few pdb commands:
import pdb
def greet(name):
if not name:
name = "world"
pdb.set_trace() # Start debugging here
greeting = "Hello, " + name + "!"
print(greeting)
greet("") # This should output "Hello, world!"
In this example:�When pdb.set_trace() runs, you can inspect name to check if it has been set correctly.�You might realize that name is empty and update it interactively if needed.�Use commands like n and s to move through the function and see what greeting becomes.�Type greeting after it’s created to verify the output.
Why pdb is a Great Tool for Debugging?
Interactive Learning: By stepping through the code, students can see the effects of each line in real-time.
Using pdb takes some practice, but it’s a powerful skill to add to any programmer’s toolkit!
SDLC - Software Development Lifecycle
Overview
The SDLC is a structured approach to software development, ensuring quality and efficiency.
The SDLC Models
Planning Phase
Planning Phase - Scope
Planning Phase - Timeline
Planning Phase - Resources
Planning Phase - Risk Management
Planning Phase - Stakeholder Engagement
Planning Phase - Project Documentation
Planning Phase - Summary
Requirements
The Requirements Gathering and Analysis stage is a critical part of the SDLC. It ensures that the software being developed meets the needs and expectations of stakeholders and users.
Requirements - Definition
This involves collecting information from stakeholders, users, and other relevant parties to understand their needs, goals, and expectations for the software.
SME - Subject Matter Experts
Requirements - Methods
Interviews: One-on-one discussions with stakeholders or users to understand their needs and objectives.
Surveys: Questionnaires distributed to gather feedback from a broader audience.
Workshops: Collaborative sessions where stakeholders and team members brainstorm and refine requirements.
Use Cases: Scenarios that describe how the software will be used in specific situations, providing a clearer picture of its functionality.
Requirements - Tie In
Gathering requirements ensures that the software's design and development align with stakeholders' needs. It serves as the foundation for subsequent SDLC stages, guiding the project's direction.
Requirements - Documentation
Documenting the gathered requirements in a clear, organized manner.
Requirements - Methods
Functional Requirements: Define what the software should do, detailing features and functionalities (e.g., user login, data processing).
Non-Functional Requirements: Describe the quality attributes of the software, such as performance, security, and usability.
Proper documentation ensures all team members and stakeholders understand the project's goals. It provides a reference for the design, development, and testing stages, ensuring alignment.
Requirements - Analysis
Analyzing the documented requirements to evaluate their feasibility, prioritize them, and identify potential gaps or conflicts.
Requirements - Analysis
Feasibility: Assessing whether the requirements can realistically be implemented, considering resources, technical constraints, and timelines.
Prioritization: Ranking requirements based on their importance to stakeholders and users, ensuring critical features are developed first.
Validation: Ensuring requirements are clear, complete, and aligned with the project's scope.
Analysis helps ensure that the requirements are realistic and align with the project's goals. It provides a roadmap for the design and development stages, minimizing risks and ensuring the project's success.
Requirements - Stakeholder Review
Requirements - Change Management
Requirements - Summary
The Requirements Gathering and Analysis stage sets the direction for the entire SDLC, ensuring that the software meets the needs of stakeholders and users. By gathering, documenting, analyzing, and managing requirements, this stage provides a clear roadmap for the design, development, and testing phases, minimizing risks and maximizing project success. It forms a crucial link between Planning and subsequent stages, ensuring all SDLC phases align with the project's goals.
See the next Slide Deck