1 of 290

Python

Object Oriented Programming

2 of 290

Before We Begin

Let’s Cover A Few Things

3 of 290

Class Rules

4 of 290

Class Rules

  • ABC - Always be Coding
  • No Food or Drink in Lab (Water exception with spill proof bottle, i.e. screw top lid - may be set on the counter.)
  • No cell phones.
    • Exception: MFA/2FA - Must ask for permission and then they must be stowed away.
    • Phones on desk = write-up
  • Lockers: All backpacks/jackets or any gear must be kept in your locker.
  • Computers are to be used for educational purposes only. No downloading of games/steam/xbox/ etc.
  • Breakfast - Eat in cafeteria before coming to class. If you drive, get here in enough time to eat and be in class before the bell rings.
  • DO NOT Download Software unless direct permission given by Mr. Sekol.

5 of 290

Class Rules

  • You are only to use Discord/#Slack/Microsoft Teams or any other class messaging platform at designated times set by the teacher.
    1. When using Discord all MCCTC Student Handbook Rules apply.
    2. You are to be professional and treat each other with respect.
    3. Memes, comments or posts that violate MCCTC Student Handbook Rules, will result in disciplinary action.
  • If any hardware or software malfunctions, it is the student’s responsibility to advise the instructor to receive help. Do not try to fix hardware problems yourself without direction from the teacher.
  • If projects require soldering, you are not to use the soldering irons without teacher supervision. Before using a soldering iron student, must complete a soldering iron safety exam and demonstrate proper safe usage of equipment.

6 of 290

Class Rules

  • Virtual Reality/Augmented Reality Equipment.
    • Before the use of equipment, you are to disinfect the headset, controllers and computer.
    • Bandanas/Head covering must be used at all times when using either VR or AR equipment.
    • When you are completed using equipment you are to disinfect and clean the equipment used.
    • Before using VR/AR students are to ensure the area is clean and free of any obstacles. Student is to ensure geo-fence is activated and geofence is up protecting the playable area.
  • Any student defaming other student work or damaging student files will be disciplined as a vandal by administration and/or the district.

7 of 290

Class Rules

  • Treat all students with respect, even when you disagree.
    • No foul language
    • No derogatory remarks
    • Be a team player and help each other.
  • Horseplay or immature behavior, harassment, or disruptions of other students working is not allowed.
  • Do not copy other student work or files. Do not delete, manipulate or move student work or files.
  • Do not write on any equipment, mouse pads, books or tables, or remove any equipment from the lab.

8 of 290

Class Rules

  • Storing of personal files on the computer or server is not allowed (games, music, programs, etc.). While you may save your schoolwork to your computer, it is your Frequently computers are formatted and upgraded. This means if you save your homework on the computer, your work will be gone. It is your responsibility to ensure you have a backup of your work.
    • All work created, stored, or accessed must adhere to school, district and/or governmental guidelines for student behavior.
  • Do not change computer configurations (including the mouse cursor, screensaver and desktop background) or hack into any system.
  • Do not use the technology to hack any system or use the knowledge gained in this class to break any laws or access systems you do not have permission to.

9 of 290

Class Rules

  • Do not circumvent, or attempt to circumvent, the MCCTC internet filter.
  • Do not use the computer to harm other people. (No VPN’s or anything that changes the DNS)
  • Plagiarism, While you are encouraged to use coding documentation, manuals and online resources, copying another person's work and submitting it in as your own is expressly prohibited and will result in a zero.
  • Artificial Intelligence - AI, GPT’s, Machine Learning Etc. AI is to be used as a tool to augment your learning, not replace it. Copying and pasting AI produced code without understanding it, is the same as plagiarism. AI is not to be used for written assignments. Unless specifically directed, for assignments, you are not to use AI. (There will be a lot of projects to use AI on)

10 of 290

Class Rules

  • Don’t be a jerk.
  • Be a good human.
  • Everyone needs a break.
  • Not everyone runs at the same pace.
  • Always Be Coding.

11 of 290

You Are Never “Caught Up”

  • Missing Assignments
  • Expanded Assignments
  • Side-Quests
  • Credentials (There’s way more than you could ever complete in 2 years.)
  • Business Professionals of America
  • Capstone
  • Portfolio Projects

12 of 290

Computing Foundations

What are the components of a computer that allows the code to run?

13 of 290

Physical Devices

14 of 290

The Brains - Central Processing Unit

15 of 290

Data Storage & Programming Instructions: 1 Byte = 8 Bits

16 of 290

How is Data Stored?

17 of 290

Permanent Storage

18 of 290

Display

19 of 290

20 of 290

Converts to Machine Code

21 of 290

High Level Languages - Human REadable

22 of 290

23 of 290

What is Programming

  • A Set of Instructions…
    • What does this mean?
    • Photoshop, Overwatch, Dreamweaver - Nothing but a set of instructions.
  • Giving Driving Directions.
    • Point A to Point B
    • Needs broken down so the receiving person can understand it.

24 of 290

What is Programming

  • Bigger programs are just a larger set of simple instruction.

25 of 290

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”)

26 of 290

Picking the Right Language

List of Languages

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.

27 of 290

Programming Language vs. Scripting Language

Programming (Native)

  • Compiler-based language
  • Lower Level
  • Designed for full usage of language and machine resources
  • Operating System Dependent
  • Full program.

Scripting

  • Interpreted Language
  • Higher Level
  • Designed for speed and faster coding.
  • Interpreted by some other software. Operating system less important.*
  • Just a piece of code.

28 of 290

High Level vs. Low Level

29 of 290

What is Python?

30 of 290

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

  • web development (server-side)
  • software development
  • mathematics
  • system scripting

31 of 290

Why Python?

  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.

32 of 290

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!

33 of 290

Google

Instagram

DropBox

Spotify

Reddit

Etc…

All Built Using Python

34 of 290

What do you need to get started?

  1. IDE - Integrated Development Environment
    1. Online - Replit.com
    2. Visual Studio Code
      1. PC - Windows
      2. Mac
      3. Linux (Chromebook if it has Linux installed)
  2. Python 3.XX Installed on Computer

35 of 290

Online IDE

36 of 290

Using Replit

37 of 290

Using Replit

38 of 290

Using Replit

39 of 290

Your Cheat Sheet

40 of 290

What Can You Do With Python?

41 of 290

Key Terms

  • Print: outputs information to console.
  • Input
  • Variables
    • Local & Global
  • Data Types
    • String: text
    • Numbers: int & float
    • Sequence: list, tuples, ranges
    • Mapping Type: dict
    • Set Types: set, frozen set
    • Boolean Type: bool
    • Binary Types: bytes, bytearray, memoryview

42 of 290

Key Terms

  • Comments
  • Numbers
  • Casting
    • int to string
    • string to int
  • Strings
    • Multiline
    • Slicing
    • Modifying
    • Concatenate String
    • Format String
    • Escape Characters
  • String Methods
    • upper()
    • lower()
    • split()
    • replace()
    • islower()
    • index()
    • count()

43 of 290

Key Terms

  • Boolean
    • True False
  • Operators (Arithmetic)
    • +, -, *, /, %, **, //
  • Assignment Operators
    • =, +=, -=, *=, /=, %=...
  • Comparison Operators
    • ==, !=, >, <, >=, <=
  • Logical Operators
    • and, or, not
  • Identity Operators
    • is, is not
  • Membership Operators
    • in, not in

44 of 290

Key Terms

  • Lists
    • Built-in list functions
  • Tuples
  • Sets
  • Dictionaries
  • Conditional Statements
    • If…Else…Elif
    • For Each
    • Nested If
  • Loops
    • While Loops
    • For Loops
    • Do While
    • Break Statement
  • Functions
    • Def
  • Lambda Functions
  • Arrays - Sike - These are so mid :)

45 of 290

Key Terms

  • Class
  • Objects
  • Inheritance
  • Iterators
  • Scope
  • Modules
  • Dates
  • Math
  • PIP
  • Try…Except (aka Try Catch)
  • RegEx
  • File Handling
    • Create, Read, Update, Delete
  • Libraries
  • Exceptions

46 of 290

Key Words

Words set aside for the compiler.

https://www.w3schools.com/python/python_ref_keywords.asp

47 of 290

Syntax

  • White Space Matters (Unlike Javascript, C++, C#, Java)
  • Goodbye Curly Braces {}... sort of.
  • Indentation Matters - Identifies Codeblocks.

48 of 290

49 of 290

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.

50 of 290

Using Codecademy…

51 of 290

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

52 of 290

Let’s Get Back To Understanding Python

53 of 290

Print Statement

print

54 of 290

Comments

# ← Creates Comment

55 of 290

Strings

“Strings”

56 of 290

Multiline String

my_story = ```

Hello� There� Ninja

```

57 of 290

Variables

= assignment operator.

58 of 290

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.

59 of 290

More Errors

60 of 290

Numbers

  • Integers
  • Floats

61 of 290

Calculations, Exponents & Modulo

  • +, -, *, /
  • Exponents **
  • Modulo %

62 of 290

Changing Numbers (Reassigning Values)

63 of 290

Concatenation

64 of 290

Plus Equals += (Increments)

65 of 290

Minus Equals (Decrement)

66 of 290

Article - Input

67 of 290

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).

68 of 290

Hackathon - Echo Chatbot

Create an app (“Chatbot”) that echoes back anything that the user inputs.

69 of 290

Git & GitHub

70 of 290

Introduction to Functions

What are functions?

  • Functions are a convenient way to group our code into reusable blocks.
  • A function contains a sequence of steps that can be performed repeatedly throughout a program without having to repeat the process of writing the same code again.

71 of 290

What diet did the ghost developer go on?

72 of 290

BOOOOOLEAN

73 of 290

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.

74 of 290

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.

75 of 290

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 ( ).

76 of 290

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.

77 of 290

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 ( ).

78 of 290

79 of 290

Parameters Cont…

80 of 290

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.

81 of 290

Hackathon - Bank Balance

82 of 290

How many programmers does it take to change a light bulb?

None. It’s a hardware problem.

83 of 290

Types of Arguments

  1. Positional: arguments that can be called by their position in the function definition.
  2. Keyword Arguments: arguments that can be called by their name.
  3. Default Arguments: arguments that are given default values.

84 of 290

Positional - Keyword - Default

85 of 290

Built-In Functions vs. User Defined Functions

86 of 290

Hackathon - Computer Shopping

With the given variables, calculate the following:

87 of 290

.

Javascript

C#

Java

88 of 290

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.

89 of 290

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.

90 of 290

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.

91 of 290

Returns Example

92 of 290

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):

93 of 290

Multiple Returns II

94 of 290

Return Review

Why return is Important:

  • Flexibility: It allows you to reuse the value that a function calculates, rather than just printing it to the console.�
  • Modularity: Functions can perform complex calculations and return the result for further use in the program.�
  • Clarity: It separates the process of computing a result from displaying it, which makes functions easier to manage and test.

95 of 290

Quiz 2: Functions

96 of 290

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

97 of 290

Logic Gates != Bill Gates

98 of 290

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.

99 of 290

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.

100 of 290

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.

101 of 290

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?

102 of 290

== 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

103 of 290

Boolean

104 of 290

this_meme == funny

True

105 of 290

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.

106 of 290

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.

107 of 290

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?

108 of 290

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.

109 of 290

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.

110 of 290

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.

111 of 290

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."

112 of 290

or Solution

113 of 290

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

114 of 290

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!

115 of 290

not Challenge Answer

116 of 290

117 of 290

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")

118 of 290

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.

119 of 290

If/Else Challenge Answer

120 of 290

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.

121 of 290

Elif

122 of 290

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"

123 of 290

Elif Challenge Solution

124 of 290

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

The Pennies from Heaven

125 of 290

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

126 of 290

Python Control Flow Quiz

https://forms.gle/Y6usB4Bd9sMASLXV7

127 of 290

2026

128 of 290

This is the greatest Programming Meme You’ll ever See!

129 of 290

Data Structures and Loops

  • A data structure is a particular way of organizing data in a computer so that it can be used effectively.
  • Data structures like lists and dictionaries can help us store and retrieve information more effectively, while classes allow us to create our own data types. (No Arrays in Python)
  • Loops make it easier to repeat the same action many times without the headache of writing the same bit of code over and over.

130 of 290

What is a List

  • A Collection of data. (Think Array in JavaScript)
  • It is one of the many built-in data structures that allows us to work with a collection of data in sequential order.
  • Student Heights
    • Noelle is 61 inches tall
    • Ava is 70 inches tall
    • Sam is 67 inches tall
    • Mia is 64 inches tall

heights = [61, 70, 67, 64]

131 of 290

What is a list?

heights = [61, 70, 67, 64]

Notice that:

  • A list begins and ends with square brackets ([ and ]).
  • Each item (i.e., 67 or 70) is separated by a comma (,)
  • It’s considered good practice to insert a space () after each comma, but your code will run just fine if you forget the space.

132 of 290

What Can A List Contain?

  • More than just numbers.
  • Pretty much any data type: Numbers, Strings, Booleans

133 of 290

Empty List

  • Create Now, Use Later.

134 of 290

List Methods (Built-In Functions)

  • Let’s talk about methods. Methods are functions, just inside of a class object. Functions are the same, mini blocks of code that can be called anywhere, but they happen to be outside a class object.
  • Also remember in Python, for any specific data-type ( strings, booleans, lists, etc. ) there is built-in functionality that we can use to create, manipulate, and even delete our data. We call this built-in functionality a method.

135 of 290

List Methods (Built-In Functions)

  • For lists, methods will follow the form of list_name.method(). Some methods will require an input value that will go between the parenthesis of the method ( ).
  • Example: A popular list method is .append(), which allows us to add an element to the end of a list.

136 of 290

Append Sample

137 of 290

Growing a List: Plus (+)

  • When we want to add multiple items to a list, we can use + to combine two lists (this is also known as concatenation).

138 of 290

Append Multiple Items?

Let’s look at some documentation:�Extend?�https://www.delftstack.com/howto/python/append-multiple-elements-python/

139 of 290

Accessing List Elements

  • Zero-Index 0… [0, 1, 2, 3, 4, …]

140 of 290

Accessing List Elements: Negative Index

  • Start from the back… [-1]

141 of 290

Modifying List Elements

  • To change a value in a list, reassign the value using the specific index.

142 of 290

Shrinking a List: Remove

  • We can remove elements in a list using the .remove() Python method.

143 of 290

Two-Dimensional (2D) Lists

  • Lists inside of lists!
  • Lists can contain other lists! We will commonly refer to these as two-dimensional (2D) lists.

144 of 290

Accessing 2D Lists

  • Two-dimensional lists can be accessed similar to their one-dimensional counterpart. Instead of providing a single pair of brackets [ ] we will use an additional set for each dimension past the first.

145 of 290

Modifying 2D Lists

146 of 290

Review

  • How to create a list
  • How to access, add, remove, and modify list elements
  • How to create a two-dimensional list
  • How to access and modify two-dimensional list elements

147 of 290

WHY STARBUCKS IS BETTER THAN DUNKIN…

148 of 290

Dictionaries (Data Structures)

149 of 290

What is a Dictionary (Data Structure)

  • A dictionary is a data structure in Python.
  • It stores data as key-value pairs.
  • Keys: Used to label and identify data.
  • Values: The actual data associated with a key.

150 of 290

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.

151 of 290

Real-Life Analogy

  • Think of a dictionary like a contact list on your phone.
  • The name is the key, and the phone number is the value.
  • Example:
    • Name (key): "John"
    • Phone Number (value): "555-1234"

152 of 290

Dictionary Syntax

KEY

VALUE

KEY

VALUE

153 of 290

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).

154 of 290

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

155 of 290

Accessing Values in a Dictionary

Utilizing keys to retrieve values using get() method.

156 of 290

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}

157 of 290

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}

158 of 290

Checking for a Key

  • Use the in keyword to check if a key exists in the dictionary.

student_grades = {

"Alice": 90,

"Bob": 85,

"Charlie": 92

}

if "Alice" in student_grades:

print("Alice's grade is", student_grades["Alice"])

159 of 290

Looping Through a Dictionary

  • You can iterate over a dictionary to get all keys and values.

student_grades = {

"Alice": 90,

"Bob": 85,

"Charlie": 92

}

for name, grade in student_grades.items():

print(name, "has a grade of", grade)

160 of 290

Key Characteristics

  • Keys must be unique and immutable (e.g., strings, numbers, tuples).
  • Values can be any data type (numbers, strings, lists, other dictionaries).
  • Dictionaries are unordered (order is not guaranteed in older Python versions).

161 of 290

Use Cases

  • Ideal for situations where you need to map a key to a value.
  • Example use cases:
    • Storing user information (e.g., username as the key, profile data as the value).
    • Counting occurrences of items (e.g., counting how many times a word appears in a text).

162 of 290

Adding and Modifying Dictionary Entries

  • New entries are added/modified using: dict_name[key] = value.

163 of 290

Removing Entries and Clearing the Dictionary

  • Using pop() and del for item removal.
  • Clearing all entries using clear().
  • pop(key) removes the item with the specified key, del dict_name[key] deletes the specified item, and clear() removes all items.

164 of 290

Iterating through Dictionaries

  • Using loops to iterate through keys, values, and items.
  • Dictionaries can be looped through using keys, values, and items using respective methods: keys(), values(), and items().

165 of 290

Nested Dictionaries

  • Concept and utility of dictionaries within dictionaries.
  • Real-world scenarios where nested dictionaries can be applicable.
  • Nested dictionaries can be utilized to store hierarchical or multi-dimensional data.

166 of 290

Loops

While & For

167 of 290

While Loop

Checks to see if a condition is true. If it is, it runs the code within the loop.

168 of 290

While Loops

169 of 290

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.

170 of 290

For Loops

171 of 290

Built-In Libraries (Python Standard Libraries

172 of 290

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).

173 of 290

Class = Blue Print

174 of 290

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.

175 of 290

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?

  • Analogy: The "Character Creation" screen in a video game. Think of a character in a game like World of Codecraft. Every character has data (name, health, level, inventory) and can perform actions (attack, heal, jump).
  • The Problem: In procedural programming, we'd have loose variables (player1_name, player1_health) and separate functions (attack(player), heal(player)). This gets messy fast, especially with multiple players.
  • The Solution: Object-Oriented Programming (OOP) lets us bundle that data and those actions together into a single, reusable blueprint. That blueprint is a class.

176 of 290

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.

177 of 290

The class Keyword

Definition: A class is a template or blueprint for creating objects.

178 of 290

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.

  • Definition: The __init__ method initializes a new object (an instance) of the class, setting its starting attributes.

179 of 290

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.

  • Definition: self represents the specific instance of the class. It allows an object to access its own attributes and methods.
  • Analogy: When you say "my name" or "my health," the "my" is self. It distinguishes your health from someone else's.

180 of 290

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.

  • Definition: An attribute is a variable associated with an instance of a class, storing its state.
  • Example: Let's give our player a name and level.

181 of 290

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.

  • Definition: An object (or instance) is a specific entity created from a class, with its own set of attributes.

182 of 290

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.

  • Definition: A method is a function defined inside a class that performs an action related to the object.
  • Example: Let's add attack and take_damage methods.
    • next slide…

183 of 290

Methods Continued

184 of 290

Pothole Alert & Best Practices

  • Forgetting self: Many frequently forget to add self as the first parameter to their methods, including __init__. This will cause a TypeError. Python passes the object itself as that first argument automatically.
  • Class vs. Object Confusion: You might try to call a method on the class itself (Player.take_damage(10)) instead of on an instance (player1.take_damage(10)). Remember the "blueprint vs. the building" analogy. The blueprint doesn't have health, but the building does.
  • __init__ is i-n-i-t: The double underscores (__) indicate a special "magic" method to Python. This is often mistyped.

185 of 290

Three Pillars of Object Oriented Programming

  • Inheritance
  • Encapsulation
  • Polymorphism

186 of 290

Inheritance: "Don't Reinvent the Wheel"

  • Definition: Inheritance is a mechanism where a new class (the "child" or "subclass") acquires the properties and behaviors (attributes and methods) of an existing class (the "parent" or "superclass"). This creates an "is-a" relationship.

187 of 290

Encapsulation: "A Protective Barrier"

  • Definition: Encapsulation is the bundling of data (attributes) and the methods that operate on that data into a single unit (the class). Crucially, it also involves restricting direct access to an object's internal state, a concept known as "data hiding."

188 of 290

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.

189 of 290

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.

190 of 290

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!

191 of 290

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.

192 of 290

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.

193 of 290

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.

194 of 290

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."

195 of 290

Decorators

196 of 290

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)

197 of 290

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?

198 of 290

Example of a Class

Output

199 of 290

What are Classes and Object

200 of 290

Classes Quick Summary

201 of 290

Modules, Packages, Libraries & Frameworks

Think of adding coding cheats and pre-written blocks of code that upgrades your coding power.

202 of 290

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.

  • Think of a module as a single LEGO piece. Each piece has its own shape and purpose. In the same way, a module is a piece of code that does a specific thing.

203 of 290

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.

204 of 290

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.

  • Now, imagine you have a box of specific LEGO pieces that are all related, like all the pieces to make trees or flags. This box is like a library in coding. It's a collection of code that helps you do certain things without having to make those pieces yourself.

205 of 290

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”

206 of 290

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.

  • Let's say you have several boxes of LEGO pieces, each for a different part of your castle (trees, flags, walls, etc.). If you put all these boxes inside a big box to keep them organized, that big box is like a package in coding. It's a way to keep related code organized.

207 of 290

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.

208 of 290

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.

  • Now, imagine you got a LEGO castle set with an instruction manual. The manual tells you how to build the castle step by step, and where each piece should go. A framework in coding is like that manual. It gives you a structure and set of rules to build your application.

209 of 290

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.

210 of 290

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:

  • Automating repetitive tasks on your computer.
  • GUI testing for applications.
  • Taking screenshots and locating where certain images appear on the screen.
  • Simulating mouse movements, clicks, and keyboard key presses.
  • AutoPyGUI Cheatsheet

211 of 290

What is Automation?

  • Automation is the process of making tasks occur automatically, without human intervention.
  • In software development, automation is often used to simulate user actions (e.g., clicking a button or typing text) or to perform repetitive tasks such as file handling, testing, and scheduling actions.

212 of 290

Why Use Automation?

  • Automation can increase productivity by reducing the need for manual intervention.
  • It is commonly used for tasks like:
    • GUI (Graphical User Interface) testing.
    • Automating repetitive data entry tasks.
    • Automating file organization and management.
    • Web scraping and browser automation.

213 of 290

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.

214 of 290

PIP - Install

215 of 290

Example pyautogui

Remember to install the module using pip first, in the terminal.

216 of 290

Moving the Mouse

The moveTo(x, y, duration) function moves the mouse to the specified coordinates on the screen.

217 of 290

Clicking

Use the click() function to simulate mouse clicks.

218 of 290

Mouse Dragging

You can simulate mouse dragging using the dragTo() function.

219 of 290

Keyboard Automation

Typing

Pressing Keys

Hotkeys:

220 of 290

Screenshots

Taking a Screenshot:

�Locating an Image on Screen:

221 of 290

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.

222 of 290

Youtube Algorithms.

223 of 290

���I/O

224 of 290

I/O in Python: Reading and Writing to Text Files

Input / Output = I/O

Understanding File Handling

  • open()
  • read()
  • write()
  • close()

225 of 290

What is Input/Output (I/O)?

  • Input (I): Reading data from an external source, like a file.
  • Output (O): Writing data to an external source, like a file.
  • I/O allows programs to persist data beyond their execution.
  • Real-world applications (e.g., storing user data, configuration settings, logs).

226 of 290

Basic File Handling in Python

  • open(): Opens a file.
  • read(): Reads data from a file.
  • write(): Writes data to a file.
  • close(): Closes a file.

These are the basic operations are fundamental to interacting with files.

227 of 290

Modes you’ll actually use

  • "r" read existing; "w" write (overwrite or create); "a" append; "r+" read/write.
  • Mental model: w = wipe, a = add.

228 of 290

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+".

229 of 290

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.

230 of 290

Writing to a Text File

  • Creates the file if it doesn’t exist.
  • Overwrites if it already exists. Talking Points:
  • Use "w" mode to create or overwrite a file.
  • The with statement ensures the file is closed after writing, even if an error occurs.

231 of 290

Appending Data to a File

  • "a" mode: Appends data without overwriting.

232 of 290

Reading from a File

  • Reads the entire content of a file.
  • The read() method retrieves all the file's contents at once.
  • There are other methods like readline() and readlines() allow for more control when reading files.

233 of 290

Handling File Not Found Errors

  • What happens when a file is missing?
  • Use try-except blocks to catch and manage errors like FileNotFoundError.

234 of 290

File Context Managers (with open)

  • The with statement is a context manager that simplifies file handling.
  • Files are automatically closed when using with, even if an error occurs.

235 of 290

Looping Through File Contents

  • Read a file line by line using a for loop.
  • Use strip() to remove extra newlines and whitespace from each line.

236 of 290

Questions

  1. Predict the result: a student changes the mode to "w" or "a" and then tries to read. What happens and why?�
  2. What does with open("haiku.txt", "r") as f: guarantee for us, even if an error happens mid-loop?�
  3. When do you get FileNotFoundError, and how can you fix it?

237 of 290

APIs and Python

API stands for application programming interface, which is a set of definitions and protocols for building and integrating application software.

  • Communicate with other Apps, without knowing how the other app is implemented.
  • Contract between two parties.

238 of 290

APIs and Python

239 of 290

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?

240 of 290

Thinking Algorithmically (Data Structures Main Course)

241 of 290

Thinking Algorithmically (Data Structures Main Course)

  • You have your list. Does it matter how you sift through the data?
  • Does it change if you have a list of 10 names vs 10,000 names?
  • What if you have 10 separate lists vs. just 1?
  • Big Data… Millions of users or data points.
  • Mapping & Uber

242 of 290

Thinking Algorithmically (and Data Structures)

  • Exercise: List of numbers… Which numbers are divisible by 3?
  • Discussion: Probability of heads vs. tail (red or black roulette?)
  • Discussion: Guess My Number
  • Exercise: Penny Flipping… Is there a pattern?
    • After 100 Flips
    • Patterns of 3? HHH, HHT, HTH, THH, HTT, TTH, TTT
    • Patterns of 4? HHHH, HHHT, HHTH, HTHH, THHH, HHTT, HTHT, THHT, HTTT, THTT, TTHT, TTTT
  • Cahoot… Can you find the pattern?

243 of 290

Divisible by 3 Exercise

  • Pick random numbers between 5,000 - 10,000,000,000 and determine if they are divisible by 3.
  • Challenge: Of the ones divisible by 3, which are divisible by 9?

244 of 290

Divisible by 3 Solution

  • Sum the individual integers of any number.
  • If the sum of all the numbers are divisible by 3 the whole number is as well.
  • 7,581,627 = 7+5+8+1+6+2+7 → 36 → 3+6 = 9
  • 342,098 = 3+4+2+0+9+8 → 26 → 2+6 = 8 → not divisible by 3
  • 364,521 = 21 → 2+1 → 3

7,581,627 is divisible by 9, but 364,521 is not. Why?

245 of 290

246 of 290

247 of 290

Thinking Algorithmically (and Data Structures)

  • Exercise: List of numbers… Which numbers are divisible by 3?
  • Discussion: Probability of heads vs. tail (red or black roulette?)
  • Discussion: Guess My Number
  • Exercise: Penny Flipping… Is there a pattern?
    • After 100 Flips
    • Patterns of 3? HHH, HHT, HTH, THH, HTT, TTH, TTT
    • Patterns of 4? HHHH, HHHT, HHTH, HTHH, THHH, HHTT, HTHT, THHT, HTTT, THTT, TTHT, TTTT
  • Cahoot… Can you find the pattern?

248 of 290

Coins and Probabilities Exercise

  • VERY IMPORTANT: Record all your data accurately.
  • In a text document, just type lowercase “h” or “t” (but without quotes. Should look like the following: thtthththhthththhhttthhthhthhthhththhhhthththththhthht
  • Email to michael.sekol@mahoningctc.com when completed.
  • Again, record every flip.��
  • Data Sheet: Google Doc

249 of 290

Can you think of anything that doesn’t use an algorithm?

250 of 290

Long Division

251 of 290

Components Of Division

252 of 290

Today’s Hackathon - Algorithmic Games

Group up in a teams of 3-4 people and create the following algorithmic applications:

  • An app that will determine if a number is prime or not up to 1 million.
    1. Confirm the output is accurate. Check your results here
  • An app that will complete the division of two numbers and provide the remainder rather than a decimal number.
    • On Paper Complete the Long Division to confirm the answers are correct.
  • An app that will determine if a number is divisible by:
    1. 3
    2. 4
    3. 11
    4. 17
  • A number guessing game app.
    • Generate a random number between 1 and 100.
    • The user has to guess that number.
    • Create a variable with a score of 10 points and for every wrong guess the game takes 1 point away.
    • If the score reaches 0, the player loses.

253 of 290

Encryption

254 of 290

Code Testing (AKA QA, AKA Continuous Testing)

Why Testing is Essential and How it Fits into Software Development?

255 of 290

What is Code Testing?

Code testing is like a “safety check” for your code

256 of 290

Why Code Testing is Important?

  • Find Errors Early: Catch mistakes while they’re easy to fix.
  • Improve Code Quality: Helps ensure your code does what it’s supposed to.
  • Make Changes Confidently: Testing means you can update code without breaking other parts.

Imagine making a game – you wouldn’t want players to fall through the floor because of a bug!

257 of 290

Types of Code Testing in Software Development

  • Unit Testing
  • Integration Testing
  • Automated Testing
  • Acceptance Testing

258 of 290

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.

259 of 290

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.

260 of 290

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:

  • n (next): Move to the next line within the same function. It runs the current line of code and then pauses at the next line, helping you move through each step of the function.
  • s (step): Step into any function calls on the current line. This allows you to enter and debug functions line by line, even nested functions.
  • c (continue): Continue execution until the next breakpoint. If there are no further breakpoints, the program will run to completion.
  • q (quit): Exit the debugger and stop the program.

261 of 290

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:

  • Type a to see the value of a (outputs 3).
  • Type b to see the value of b (outputs 4).
  • Type result to check if result has been set yet (at this point, it hasn’t, so it would return an error or None).

262 of 290

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.

263 of 290

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.

264 of 290

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

265 of 290

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.

266 of 290

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.

267 of 290

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.

  • Improves Error Understanding: Instead of trying to guess where something went wrong, pdb lets them verify the flow and values at each step.
  • Encourages Experimentation: Students can change variable values or add code on the fly, which deepens their understanding of code behavior.
  • Promotes Systematic Debugging: pdb teaches students to systematically go through code, which is a valuable skill for handling more complex debugging scenarios.

Using pdb takes some practice, but it’s a powerful skill to add to any programmer’s toolkit!

268 of 290

SDLC - Software Development Lifecycle

269 of 290

Overview

The SDLC is a structured approach to software development, ensuring quality and efficiency.

270 of 290

The SDLC Models

  1. Waterfall
  2. Agile
  3. Spiral
  4. V-Shape
  5. Iterative
  6. Lean

271 of 290

Planning Phase

  • The Planning stage is the foundation of the SDLC, laying out the groundwork for the entire project. It sets the direction and ensures all stakeholders have a shared understanding of the project's goals and constraints.�
  • Who are the stakeholders?

272 of 290

Planning Phase - Scope

  • The project scope defines the boundaries and objectives of the software project. It outlines what will be delivered, what features and functionalities are included, and what is excluded.�
  • A clear scope prevents scope creep, where unplanned features or changes could derail the project's progress. It guides the design, development, and testing phases, ensuring that each stage remains aligned with the overall goals.

273 of 290

Planning Phase - Timeline

  • Timelines outline the project's milestones and deadlines for each stage of development. This includes key dates for completing design, development, testing, and deployment tasks.�
  • Timelines ensure the project stays on track and helps prevent delays. They provide benchmarks for progress and allow stakeholders to measure the project's advancement, guiding each SDLC stage.

274 of 290

Planning Phase - Resources

  • Resources encompass the manpower, tools, software, and budget allocated to the project. This includes assigning team members to specific tasks, selecting development tools, and ensuring sufficient funding.�
  • Resources ensure that each SDLC stage has the necessary inputs to function smoothly. Proper resource allocation minimizes bottlenecks and allows each phase to proceed efficiently.

275 of 290

Planning Phase - Risk Management

  • Risk management identifies potential risks to the project, evaluates their impact, and develops mitigation strategies. This includes technical risks, budgetary concerns, and timeline risks.�
  • Proactively addressing risks prevents project failures and helps maintain progress through each SDLC stage. Risk management guides the team in making informed decisions, ensuring project stability.

276 of 290

Planning Phase - Stakeholder Engagement

  • Stakeholder engagement involves communicating with and gathering input from key stakeholders, including customers, management, and project teams. This ensures their needs and expectations are met.�
  • Engaging stakeholders early and throughout the project ensures their feedback informs each SDLC stage. This enhances the quality and relevance of the final product, ensuring it aligns with users' needs.

277 of 290

Planning Phase - Project Documentation

  • Project documentation captures the project's plan, scope, timelines, resources, and risk management strategies. This provides a reference for the team and stakeholders, outlining the project's structure.�
  • Documentation serves as a blueprint for each SDLC stage, ensuring all phases are aligned with the project's objectives. It provides a reference to revisit and update as needed, guiding the project's progression.

278 of 290

Planning Phase - Summary

  • The Planning stage provides a comprehensive roadmap for the entire SDLC, ensuring each stage is well-structured and aligned with the project's goals. By defining the scope, timelines, resources, risks, stakeholders, and documentation, the Planning stage sets the foundation for a successful software project. Each subsequent SDLC stage relies on this foundation to progress smoothly, making Planning a crucial part of the development process.

279 of 290

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.

280 of 290

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

281 of 290

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.

282 of 290

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.

283 of 290

Requirements - Documentation

Documenting the gathered requirements in a clear, organized manner.

284 of 290

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.

285 of 290

Requirements - Analysis

Analyzing the documented requirements to evaluate their feasibility, prioritize them, and identify potential gaps or conflicts.

286 of 290

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.

287 of 290

Requirements - Stakeholder Review

  • Presenting the documented and analyzed requirements to stakeholders for feedback and approval.�
  • Engaging stakeholders early ensures their needs are accurately captured and addressed. It reduces the likelihood of costly changes in later stages, helping maintain the project's alignment with stakeholders' goals.

288 of 290

Requirements - Change Management

  • Establishing a process for handling changes to the requirements throughout the project's lifecycle.�
  • Changes are inevitable, and a structured change management process ensures they're handled effectively, minimizing disruption to the SDLC. This helps maintain consistency and alignment across all stages.

289 of 290

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.

290 of 290

See the next Slide Deck