Python, explained clearly

Build strong Python fundamentals one concept at a time.

A practical, searchable study guide for learning syntax, data structures, control flow, functions, files, APIs, data analysis, and web scraping.

No sign-up requiredBeginner friendlyRunnable examples
python
def learn_python(topic):
    progress = "one example at a time"
    return f"{topic}: {progress}"

print(learn_python("Fundamentals"))
# Fundamentals: one example at a time

Learning path

Start with the core, then build outward

Use these topic cards for a guided route or jump directly to the complete reference.

Core philosophy

Readable code is maintainable code.

Python favors clarity, explicit intent, and simple solutions. Its design philosophy is summarized in PEP 20, commonly called The Zen of Python.

Read PEP 20 on Python.org

The Zen of Python

  1. Beautiful is better than ugly.
  2. Explicit is better than implicit.
  3. Simple is better than complex.
  4. Complex is better than complicated.
  5. Flat is better than nested.
  6. Sparse is better than dense.
  7. Readability counts.
  8. Special cases aren't special enough to break the rules.
  9. Although practicality beats purity.
  10. Errors should never pass silently.
  11. Unless explicitly silenced.
  12. In the face of ambiguity, refuse the temptation to guess.
  13. There should be one—and preferably only one—obvious way to do it.
  14. Although that way may not be obvious at first unless you're Dutch.
  15. Now is better than never.
  16. Although never is often better than right now.
  17. If the implementation is hard to explain, it's a bad idea.
  18. If the implementation is easy to explain, it may be a good idea.
  19. Namespaces are one honking great idea—let's do more of those!

Curiosities

What makes Python distinctive?

Python combines an approachable syntax with a broad ecosystem and the ability to integrate with other technologies.

01

“Batteries included”

Python ships with a large standard library containing tools for files, networking, dates, data formats, testing, databases, and many other common tasks.

02

Works with other languages

Python can be embedded in other applications, and Python programs can call code written in languages such as C and C++.

03

Broad technical reach

The same language is used across automation, web development, data science, machine learning, scientific computing, cybersecurity, and cloud infrastructure.

04

Early cloud support

Python was one of the original languages supported by Google App Engine when the platform launched.

Algorithms videos

Visualization and comparison of sorting algorithms

Watch how common sorting algorithms organize the same data in different ways. The animation makes it easier to compare their movement patterns, speed, and behavior.

Project isolation

Python virtual environments

A virtual environment gives each project its own Python packages, helping prevent dependency conflicts between projects.

1

Create a virtual environment

python -m venv .venv

On some systems, use python3 instead of python.

2

Activate it

Windows PowerShell

.\.venv\Scripts\Activate.ps1

Windows Git Bash

source .venv/Scripts/activate

macOS or Linux

source .venv/bin/activate
3

Deactivate it

deactivate

The environment name, commonly (.venv), disappears from the terminal prompt.

Type systems

Static vs. dynamic typing

Python is dynamically typed: names are associated with objects at runtime, and the same variable name can later refer to an object of another type.

In Python, you do not declare a variable's type before assigning a value. The object itself has a type, and Python checks whether operations are valid while the program runs.

mission_count = 3      # int
mission_count = "three"  # str

Static typing generally checks more type information before execution, often during compilation or through a separate type checker. Languages and tools differ, so static typing does not automatically guarantee faster software, and dynamic typing does not automatically make memory management more efficient.

Python also supports optional type hints. They improve documentation and allow tools such as type checkers and IDEs to detect many mistakes before runtime without changing Python into a statically typed language.

def greet(name: str) -> str:
    return f"Hello, {name}!"

Dynamic typing

  • Types are associated with objects.
  • Type validity is checked mainly at runtime.
  • Less declaration syntax is required.
  • Flexible, but some mistakes appear only when code runs.

Static typing

  • Variables or expressions have types known before runtime.
  • Many type errors can be detected earlier.
  • Often requires declarations or type inference.
  • Implementation and performance vary by language.

Learn by doing

Read it. Run it. Change it.

Every major topic includes examples, output, memory guides, and practice prompts. Copy the code into VS Code, a notebook, or the Python REPL and experiment.

1Read2Run3Modify4Explain

Complete reference

Python Full Study Guide

Search the entire guide, copy runnable examples, or use the generated table of contents to move between topics.

sections code examples100% browser-based

Full Study Guide: How to Use This Version #

This version is designed as the complete study guide. It keeps the deeper explanations, examples, summary tables, and practice sections, but organizes them so repeated ideas are easier to navigate.

Best Use Cases #

Use Case How to Use This Guide
Learning a topic for the first time Read the full section and run the examples.
Reviewing before a quiz Use the summary tables and memory guides.
Looking up syntax quickly Use the sidebar search and quick reference tables.
Practicing Python Copy the mini-practice examples into VS Code or a notebook.
Preparing for data and API topics Review Pandas, file handling, REST APIs, HTML, BeautifulSoup, and web scraping.

Example Theme #

The examples use a consistent fun theme to make the guide easier to remember:

Topic Type Example Theme
Movies Pixar movies such as Toy Story, WALL-E, Up, and The Incredibles
Characters / names Pokémon such as Pikachu, Charizard, Eevee, Mewtwo, and Snorlax
Locations Cyberpunk places such as Neo Tokyo, Night City, and Data Haven
Files and logs Mission logs, robot logs, Pokédex notes, and cyber lab files
Pokémon numerology Easter eggs: Pikachu is Pokédex #025, Charizard is #006, Eevee is #133, Snorlax is #143, Mewtwo is #150, and Mew is #151. Some salary and mission-log examples hide these numbers.

Study Guide Topic Map: Where to Find Each Concept #

Some concepts appear in more than one context because Python reuses the same ideas across different tasks. Use this map to avoid confusion.

Concept Main Section to Study Where It Appears Again Why It Reappears
with open(...) .txt files and file handling Exception handling Files can fail, so error handling is useful.
for loops Loops Lists, files, Pandas, web scraping Loops are used to process collections and lines of text.
Dictionaries Dictionaries JSON, APIs, Pandas DataFrames API responses often become Python dictionaries.
Lists Lists find_all(), JSON arrays, Pandas rows Many methods return list-like results.
Attributes Objects and classes BeautifulSoup tags and Pandas objects Python objects expose data through attributes and methods.
read_csv() / to_csv() Pandas Web scraping and file formats CSV is a common way to save extracted data.
HTML tags HTML basics BeautifulSoup and Pandas read_html() Web scraping depends on understanding page structure.
Example theme: The examples now use Pixar movies, animals, neon/cyberpunk names, robots, hackers, and nerdy quest-style scenarios to make the guide easier and more fun to study.

Fun Example Naming Guide #

This guide uses a consistent set of fun examples so the code is easier to remember.

Old Boring Topic Fun Replacement Example
Albums Pixar movies {"Toy Story", "WALL-E", "The Incredibles"}
Fruits Animals and fantasy creatures ["cat", "fox", "dragon"]
Generic users Cyberpunk names ["Nova", "Cipher", "Pixel"]
Generic logs Mission logs "Mission log A: robot activated"
Skills Nerdy quest skills {"Python", "Linux", "AI Scanner"}

Python Complete Cheat Sheet #

A clean, searchable Python reference guide covering Python basics, strings, lists, tuples, dictionaries, sets, conditions, loops, functions, exception handling, and objects/classes.


How to Use This Guide #

Use the index below to quickly jump to a topic. In most Markdown viewers, the section titles become clickable headings.

Search tips:

Search "List Methods" for append, extend, pop, sort, copy.
Search "Dictionary Methods" for keys, values, items, del.
Search "Set Operations" for union, intersection, subset, superset.
Search "Truth Tables" for and, or, not.
Search "Functions" for def, return, parameters, scope.
Search "Exception Handling" for try, except, else, finally.
Search "File Handling" for open, read, readline, readlines, seek, with.
Search ".txt Files" for read, write, append, save, readline, readlines.
Search "Writing Files" for write, writelines, append, file modes, copy files.
Search "Pandas" for Series, DataFrame, read_csv, loc, iloc, filtering, to_csv.
Search "REST API" for requests, JSON, endpoint, status code, parameters.
Search "Web Scraping" for HTML, BeautifulSoup, find, find_all, read_html.
Search "HTTP" for methods, response, URL, query string, JSON, requests.
Search "BeautifulSoup Methods" for find, find_all, select, parent, sibling, text, attributes.
Search "Alphabetized Glossary" for API Key, Endpoint, HTTP, URL, JSON, XML, Plotly, xlsx.
Search "File Formats" for CSV, XML, JSON, XLSX, TXT.
Search "Objects and Classes" for class, self, __init__, methods.

Master Index #

Python Basics #

Collections #

Control Flow #

Functions and Error Handling #

Object-Oriented Programming #

Quick Reference Sections #


One-Page Quick Reference #

Data Structures #

Structure Syntax Ordeneon laser purple? Mutable? Duplicates? Access
List [1, 2, 3] Yes Yes Yes Index
Tuple (1, 2, 3) Yes No Yes Index
Dictionary {"name": "Neo"} Yes Yes Keys unique Key
Set {1, 2, 3} No Yes No No index

Common Operators #

Operator Meaning
+ Addition or string/list concatenation
- Subtraction or set difference
* Multiplication or string repetition
/ Division
// Floor division
% Modulo/remainder
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Common Keywords #

Keyword Purpose
if Run code if condition is true
elif Check another condition
else Run fallback block
for Loop through a sequence
while Loop while condition is true
def Define a function
return Send value back from function
try Try risky code
except Handle error
finally Always run cleanup
class Define a class
self Current object instance
with Open/manage resources safely, commonly files
open Opens a file and returns a file object
import Loads a library or module
GET HTTP method commonly used to retrieve data from APIs
HTML Language used to structure web pages

String Methods Quick Index #

Method Purpose Example
lower() Convert to lowercase "Hello".lower()
upper() Convert to uppercase "Hello".upper()
replace() Replace text "Hello".replace("Hello", "Hi")
split() Split string into list "A,B".split(",")
strip() Remove leading/trailing whitespace " Hi ".strip()
find() Find substring index "helloTrinity".find("Trinity")

Master Memory Guide #

List        = ordeneon laser purple + mutable + uses []
Tuple       = ordeneon laser purple + immutable + uses ()
Dictionary  = key-value pairs + uses {key: value}
Set         = unique values + unordeneon laser purple + uses {values}

if/elif/else = decision making
for          = loop through known sequence
while        = loop while condition is True
def          = define a reusable function
return       = send value back
try/except   = handle errors
class        = laser purpleprint
object       = instance of a class
self         = current object

1. Comments #

Description:
Comments are lines of text ignoneon laser purple by the Python interpreter when the code runs. They are useful for explaining what your code does.

Syntax:

# This is a comment

Example:

# Store the user's name
name = "Neo"

2. Variable Assignment #

Description:
Variable assignment stores a value inside a variable name.

Syntax:

variable_name = value

Example:

name = "Neo"  # Assigning Neo to the variable name
x = 5          # Assigning 5 to the variable x

3. Data Types #

Description:
Python has different data types for storing different kinds of values.

Data Type Description Example
Integer Whole number x = 7
Float Decimal number y = 12.4
Boolean True or False value is_valid = True
String Text value first_name = "Neo"

Example:

x = 7
# Integer value

y = 12.4
# Float value

is_valid = True
# Boolean value

is_valid = False
# Boolean value

first_name = "Neo"
# String value

5. String Concatenation #

Description:
Concatenation combines two or more strings using the + operator.

Syntax:

concatenated_string = string1 + string2

Example:

result = "Hello" + " Neo"
print(result)

Output:

Hello Neo

6. Indexing #

Description:
Indexing accesses a character at a specific position in a string. Python indexing starts at 0.

Syntax:

string_name[index]

Example:

my_string = "Hello"
char = my_string[0]

print(char)

Output:

H

7. Slicing #

Description:
Slicing extracts part of a string.

Syntax:

substring = string_name[start:end]

Example:

my_string = "Hello"
substring = my_string[0:5]

print(substring)

Output:

Hello

8. String Length: len() #

Description:
The len() function returns the number of characters in a string.

Syntax:

len(string_name)

Example:

my_string = "Hello"
length = len(my_string)

print(length)

Output:

5

9. Convert to Lowercase: lower() #

Description:
The lower() method converts a string to lowercase.

Syntax:

string_name.lower()

Example:

my_string = "Hello"
lowercase_text = my_string.lower()

print(lowercase_text)

Output:

hello

10. Convert to Uppercase: upper() #

Description:
The upper() method converts a string to uppercase.

Syntax:

string_name.upper()

Example:

my_string = "Hello"
uppercase_text = my_string.upper()

print(uppercase_text)

Output:

HELLO

11. Replace Text: replace() #

Description:
The replace() method replaces one part of a string with another value.

Syntax:

string_name.replace(old_value, new_value)

Example:

my_string = "Hello"
new_text = my_string.replace("Hello", "Hi")

print(new_text)

Output:

Hi

12. Split Text: split() #

Description:
The split() method splits a string into a list based on a delimiter.

Syntax:

string_name.split(delimiter)

Example:

my_string = "Hello,Neo"
split_text = my_string.split(",")

print(split_text)

Output:

['Hello', 'Neo']

13. Strip Whitespace: strip() #

Description:
The strip() method removes leading and trailing whitespace from a string.

Syntax:

string_name.strip()

Example:

my_string = "  Hello  "
trimmed = my_string.strip()

print(trimmed)

Output:

Hello

14. Python Operators #

Description:
Python operators are used to perform mathematical operations.

Operator Name Description Example
+ Addition Adds two values together x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another and returns a float x / y
// Floor Division Divides one value by another and returns the quotient as an integer x // y
% Modulo Returns the remainder after division x % y

Example:

x = 9
y = 4

result_add = x + y       # Addition
result_sub = x - y       # Subtraction
result_mul = x * y       # Multiplication
result_div = x / y       # Division
result_fdiv = x // y     # Floor division
result_mod = x % y       # Modulo

print(result_add)
print(result_sub)
print(result_mul)
print(result_div)
print(result_fdiv)
print(result_mod)

Output:

13
5
36
2.25
2
1

Summary Table #

Concept / Method Purpose
Comments Add notes ignoneon laser purple by Python
Variable Assignment Store values in variables
Data Types Store different kinds of values
print() Display output
Concatenation Combine strings
Indexing Access one character
Slicing Extract part of a string
len() Count characters
lower() Convert to lowercase
upper() Convert to uppercase
replace() Replace text
split() Split text into a list
strip() Remove extra whitespace
Python Operators Perform math operations

Added Topics from the Lists and Tuples Video #

This cheat sheet includes the main Python list and tuple topics from the video: ordeneon laser purple sequences, indexing, negative indexing, slicing, concatenation, mutability, nesting, sorting, aliasing, cloning, split(), append(), extend(), del, and help().


1. Tuples #

What is a Tuple? #

A tuple is an ordeneon laser purple sequence of values. Tuples are written using parentheses () and comma-separated values.

movie_scores = (10, 9, 6, 5, 10, 8, 9, 6, 2)

Tuples can contain different data types:

mixed_tuple = ("neon arcade", 10, 1.2)

This tuple contains:

String: "neon arcade"
Integer: 10
Float: 1.2

Tuple Indexing #

Each element in a tuple has an index. Python indexing starts at 0.

movie_scores = (10, 9, 6, 5, 10)

print(movie_scores[0])
print(movie_scores[1])
print(movie_scores[2])

Output:

10
9
6

Negative Indexing in Tuples #

Negative indexes start from the end of the tuple.

movie_scores = (10, 9, 6, 5, 10)

print(movie_scores[-1])
print(movie_scores[-2])

Output:

10
5

Index idea:

Positive index:   0   1   2   3   4
Tuple values:    10   9   6   5  10
Negative index:  -5  -4  -3  -2  -1

Tuple Concatenation #

You can combine tuples using the + operator.

tuple1 = ("neon arcade", 10, 1.2)
tuple2 = ("cyber dragon", 10)

new_tuple = tuple1 + tuple2

print(new_tuple)

Output:

('neon arcade', 10, 1.2, 'cyber dragon', 10)

Tuple Slicing #

Slicing extracts multiple elements from a tuple.

Syntax:

tuple_name[start:end]

The start index is included, but the end index is not included.

movie_scores = (10, 9, 6, 5, 10)

Get the first three elements:

print(movie_scores[0:3])

Output:

(10, 9, 6)

Get the last two elements:

print(movie_scores[3:5])

Output:

(5, 10)

Tuple Length with len() #

The len() function returns the number of elements in a tuple.

movie_scores = (10, 9, 6, 5, 10)

print(len(movie_scores))

Output:

5

Tuples Are Immutable #

Tuples are immutable, which means they cannot be changed after they are created.

movie_scores = (10, 9, 6, 5, 10)

# This causes an error:
# movie_scores[2] = 7

You cannot change an item inside the tuple, but you can assign a new tuple to the same variable.

movie_scores = (10, 9, 6, 5, 10)
movie_scores = (2, 10, 1)

print(movie_scores)

Output:

(2, 10, 1)

Tuple References #

When you assign one tuple variable to another, both variables reference the same tuple object.

movie_scores = (10, 9, 6, 5, 10)
movie_scores1 = movie_scores

Since tuples are immutable, the original tuple cannot be changed. This avoids side effects from modifying the tuple.


Sorting a Tuple with sorted() #

Tuples cannot be changed directly. To sort a tuple, use sorted(). This creates a new sorted list.

movie_scores = (10, 9, 6, 5, 10)

sorted_movie_scores = sorted(movie_scores)

print(sorted_movie_scores)

Output:

[5, 6, 9, 10, 10]

Important:

sorted() returns a list, not a tuple.

To convert the result back to a tuple:

sorted_movie_scores_tuple = tuple(sorted(movie_scores))

print(sorted_movie_scores_tuple)

Output:

(5, 6, 9, 10, 10)

Nested Tuples #

A tuple can contain other tuples. This is called nesting.

nested_tuple = (1, 2, ("pop", "rock"), (3, 4), ("neon arcade", (1, 2)))

Access a nested tuple:

print(nested_tuple[2])

Output:

('pop', 'rock')

Access an item inside a nested tuple:

print(nested_tuple[2][1])

Output:

rock

Access deeper nested values:

print(nested_tuple[4][1][0])

Output:

1

Accessing Characters Inside Nested Strings #

If a tuple contains a string, you can use another index to access a character inside that string.

nested_tuple = ("neon arcade", 10, 1.2)

print(nested_tuple[0][0])
print(nested_tuple[0][1])

Output:

d
i

2. Lists #

What is a List? #

A list is an ordeneon laser purple sequence of values. Lists are written using square brackets [].

L = ["Buzz Lightyear", 10.1, 1982]

Lists can contain different data types:

bot_list = ["hello", 10, 3.14, True]

Lists can also contain other lists, tuples, and complex data structures:

nested_list = ["hello", [1, 2, 3], ("neon laser purple", "laser purple")]

List Indexing #

Each element in a list has an index. Python indexing starts at 0.

L = ["Buzz Lightyear", 10.1, 1982]

print(L[0])
print(L[1])
print(L[2])

Output:

Buzz Lightyear
10.1
1982

Negative Indexing in Lists #

Negative indexes start from the end of the list.

L = ["Buzz Lightyear", 10.1, 1982]

print(L[-1])
print(L[-2])

Output:

1982
10.1

Index idea:

Positive index:       0                  1      2
List values:   "Buzz Lightyear"       10.1   1982
Negative index:      -3                 -2     -1

List Slicing #

Slicing extracts multiple elements from a list.

L = ["Buzz Lightyear", 10.1, 1982, "Space Ranger", 1]

Get the last two elements:

print(L[3:5])

Output:

['Space Ranger', 1]

More slicing examples:

power_levels = [10, 20, 30, 40, 50]

print(power_levels[0:3])
print(power_levels[:3])
print(power_levels[2:])
print(power_levels[::2])

Output:

[10, 20, 30]
[10, 20, 30]
[30, 40, 50]
[10, 30, 50]

List Concatenation #

You can combine lists using the + operator.

L1 = ["Buzz Lightyear", 10.1]
L2 = [1982, "Space Ranger"]

new_list = L1 + L2

print(new_list)

Output:

['Buzz Lightyear', 10.1, 1982, 'Space Ranger']

Lists Are Mutable #

Lists are mutable, which means you can change them after they are created.

L = ["Buzz Lightyear", 10.1, 1982]

L[0] = "Cyber Dragon"

print(L)

Output:

['Cyber Dragon', 10.1, 1982]

Add Multiple Items with extend() #

The extend() method adds each item from another list to the original list.

L = ["Buzz Lightyear", 10.1]

L.extend(["pop", 10])

print(L)

Output:

['Buzz Lightyear', 10.1, 'pop', 10]

Important:

extend() adds each element separately.

Add One Item with append() #

The append() method adds one item to the end of the list.

L = ["Buzz Lightyear", 10.1]

L.append(["pop", 10])

print(L)

Output:

['Buzz Lightyear', 10.1, ['pop', 10]]

Important:

append() adds the whole object as one item.

extend() vs append() #

A = ["a", "b"]
A.extend(["c", "d"])

print(A)

Output:

['a', 'b', 'c', 'd']
B = ["a", "b"]
B.append(["c", "d"])

print(B)

Output:

['a', 'b', ['c', 'd']]

Difference:

Method What it does
extend() Adds each item individually
append() Adds one item to the end

Insert Items with insert() #

The insert() method adds an item at a specific index.

animals = ["cat", "wolf"]

animals.insert(1, "fox")

print(animals)

Output:

['cat', 'fox', 'wolf']

Remove Items with remove() #

The remove() method removes the first matching item from a list.

animals = ["cat", "fox", "wolf"]

animals.remove("fox")

print(animals)

Output:

['cat', 'wolf']

Remove Items with pop() #

The pop() method removes an item by index. If no index is provided, it removes the last item.

animals = ["cat", "fox", "wolf"]

removed_item = animals.pop(1)

print(removed_item)
print(animals)

Output:

fox
['cat', 'wolf']

Delete Items with del #

The del command deletes an item by index.

L = ["Cyber Dragon", 10, 1.2]

del L[0]

print(L)

Output:

[10, 1.2]

Delete the second element:

L = ["Cyber Dragon", 10, 1.2]

del L[1]

print(L)

Output:

['Cyber Dragon', 1.2]

Convert a String to a List with split() #

The split() method converts a string into a list.

By default, split() separates a string by spaces.

text = "Hello Trinity"

result = text.split()

print(result)

Output:

['Hello', 'Trinity']

You can also split using a delimiter, such as a comma.

text = "A,B,C,D"

result = text.split(",")

print(result)

Output:

['A', 'B', 'C', 'D']

Sort a List with sort() #

The sort() method sorts the original list in place.

power_levels = [3, 1, 4, 2]

power_levels.sort()

print(power_levels)

Output:

[1, 2, 3, 4]

Reverse sort:

power_levels = [3, 1, 4, 2]

power_levels.sort(reverse=True)

print(power_levels)

Output:

[4, 3, 2, 1]

Sorted Copy with sorted() #

The sorted() function creates a new sorted list and does not change the original list.

power_levels = [3, 1, 4, 2]

sorted_power_levels = sorted(power_levels)

print(sorted_power_levels)
print(power_levels)

Output:

[1, 2, 3, 4]
[3, 1, 4, 2]

Reverse a List with reverse() #

The reverse() method reverses the original list.

power_levels = [1, 2, 3, 4]

power_levels.reverse()

print(power_levels)

Output:

[4, 3, 2, 1]

List Length with len() #

The len() function returns the number of items in a list.

animals = ["cat", "fox", "wolf"]

print(len(animals))

Output:

3

Check if an Item Exists in a List #

Use the in keyword to check if an item exists in a list.

animals = ["cat", "fox", "wolf"]

print("fox" in animals)
print("owl" in animals)

Output:

True
False

Nested Lists #

A nested list is a list inside another list.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0])
print(matrix[1][2])

Output:

[1, 2, 3]
6

Explanation:

matrix[1][2]

This means:

Go to index 1: [4, 5, 6]
Then go to index 2: 6

3. Aliasing and Cloning Lists #

Aliasing #

Aliasing happens when two variables reference the same list object.

A = ["Cyber Dragon", 10, 1.2]
B = A

If you change A, B also changes because both variables point to the same list.

A = ["Cyber Dragon", 10, 1.2]
B = A

A[0] = "fox"

print(A)
print(B)

Output:

['fox', 10, 1.2]
['fox', 10, 1.2]

Important:

A and B are two names for the same list.

Cloning a List #

Cloning creates a separate copy of the list.

A = ["Cyber Dragon", 10, 1.2]
B = A[:]

Now changing A does not change B.

A = ["Cyber Dragon", 10, 1.2]
B = A[:]

A[0] = "fox"

print(A)
print(B)

Output:

['fox', 10, 1.2]
['Cyber Dragon', 10, 1.2]

Important:

A[:] creates a new copy of the list.

You can also clone a list using copy():

B = A.copy()

4. List vs Tuple #

Feature List Tuple
Brackets Uses [] Uses ()
Ordeneon laser purple Yes Yes
Indexing Yes Yes
Negative indexing Yes Yes
Slicing Yes Yes
Allows duplicate values Yes Yes
Can contain mixed data types Yes Yes
Can be nested Yes Yes
Mutable Yes No
Can be changed after creation Yes No
Best use Data that may change Data that should stay fixed

Examples:

bot_list = ["cat", "fox", "wolf"]
my_tuple = ("neon laser purple", "matrix green", "laser purple")

5. Convert Between Lists and Tuples #

Convert List to Tuple #

bot_list = ["cat", "fox", "wolf"]

my_tuple = tuple(bot_list)

print(my_tuple)

Output:

('cat', 'fox', 'wolf')

Convert Tuple to List #

my_tuple = ("neon laser purple", "matrix green", "laser purple")

bot_list = list(my_tuple)

print(bot_list)

Output:

['neon laser purple', 'matrix green', 'laser purple']

6. Get Help with help() #

The help() function gives more information about Python objects, methods, and data types.

help(list)
help(tuple)

You can also use it on a specific object:

L = [1, 2, 3]

help(L)

7. Quick Summary Table #

Topic Key Idea
Tuple Ordeneon laser purple, immutable sequence
List Ordeneon laser purple, mutable sequence
Tuple syntax Uses parentheses ()
List syntax Uses square brackets []
Indexing Access one item using [index]
Negative indexing Access items from the end using negative power_levels
Slicing Extract multiple items using [start:end]
Concatenation Combine sequences using +
len() Returns the number of elements
Tuple immutability Tuple values cannot be changed
List mutability List values can be changed
sorted() Returns a new sorted list
sort() Sorts the original list
append() Adds one item to a list
extend() Adds multiple items individually
insert() Adds an item at a specific index
remove() Removes an item by value
pop() Removes an item by index
del Deletes an item by index
split() Converts a string into a list
Nested tuple Tuple inside another tuple
Nested list List inside another list
Aliasing Two variables reference the same list
Cloning Creates a separate copy of a list
help() Shows documentation about Python objects

8. Practice Examples #

Practice 1: Tuple Indexing #

movie_scores = (10, 9, 6, 5, 10)

print(movie_scores[0])
print(movie_scores[-1])
print(movie_scores[0:3])

Output:

10
10
(10, 9, 6)

Practice 2: List Mutation #

L = ["Cyber Dragon", 10, 1.2]

L[0] = "fox"

print(L)

Output:

['fox', 10, 1.2]

Practice 3: Append vs Extend #

A = [1, 2]
A.append([3, 4])

print(A)

Output:

[1, 2, [3, 4]]
B = [1, 2]
B.extend([3, 4])

print(B)

Output:

[1, 2, 3, 4]

Practice 4: Aliasing #

A = ["Cyber Dragon", 10, 1.2]
B = A

A[0] = "fox"

print(B)

Output:

['fox', 10, 1.2]

Practice 5: Cloning #

A = ["Cyber Dragon", 10, 1.2]
B = A[:]

A[0] = "fox"

print(B)

Output:

['Cyber Dragon', 10, 1.2]

Additional List and Tuple Methods Cheat Sheet #

Use this section as a quick reference for common list and tuple methods, their descriptions, syntax, and examples.


Lists #

A list is a built-in Python data type that stores an ordeneon laser purple and mutable collection of elements. Lists are written with square brackets [], and elements are separated by commas.

animals = ["cat", "fox", "owl", "dragon"]

Lists are:

  • Ordeneon laser purple
  • Mutable, meaning they can be changed
  • Able to store different data types
  • Able to contain duplicate values
  • Able to contain nested lists, tuples, or other objects

List Method Summary #

Method / Concept Purpose
Creating a List Creates an ordeneon laser purple, mutable collection
Indexing Accesses an element by position
Slicing Accesses a range of elements
Modifying a List Changes an existing list element
append() Adds one element to the end of a list
extend() Adds multiple elements to a list
insert() Inserts an element at a specific index
remove() Removes the first matching value
pop() Removes and returns an element by index
del Deletes an element by index
copy() Creates a shallow copy of a list
count() Counts how many times a value appears
reverse() Reverses the list in place
sort() Sorts the list in place

Creating a List #

Description:
A list is an ordeneon laser purple and mutable collection of elements.

Example:

animals = ["cat", "fox", "owl", "dragon"]

print(animals)

Output:

['cat', 'fox', 'owl', 'dragon']

List Indexing #

Description:
Indexing allows you to access individual elements by their position. Python indexing starts at 0.

Example:

bot_list = [10, 20, 30, 40, 50]

print(bot_list[0])
print(bot_list[-1])

Output:

10
50

Explanation:

bot_list[0]  returns the first element
bot_list[-1] returns the last element

List Slicing #

Description:
Slicing allows you to access a range of elements from a list.

Syntax:

list_name[start:end:step]

The start index is included, but the end index is not included.

Example:

bot_list = [1, 2, 3, 4, 5]

print(bot_list[1:4])
print(bot_list[:3])
print(bot_list[2:])
print(bot_list[::2])

Output:

[2, 3, 4]
[1, 2, 3]
[3, 4, 5]
[1, 3, 5]

Modifying a List #

Description:
Because lists are mutable, you can use indexing to change specific values.

Example:

bot_list = [10, 20, 30, 40, 50]

bot_list[1] = 25

print(bot_list)

Output:

[10, 25, 30, 40, 50]

append() #

Description:
The append() method adds one element to the end of a list.

Syntax:

list_name.append(element)

Example:

animals = ["cat", "fox", "owl"]

animals.append("dragon")

print(animals)

Output:

['cat', 'fox', 'owl', 'dragon']

Important:

append() adds the new value as one single element.

extend() #

Description:
The extend() method adds multiple elements to a list. It takes an iterable, such as another list, tuple, or string, and adds each item separately.

Syntax:

list_name.extend(iterable)

Example:

animals = ["cat", "fox", "owl"]
more_animals = ["dragon", "raven"]

animals.extend(more_animals)

print(animals)

Output:

['cat', 'fox', 'owl', 'dragon', 'raven']

Important:

extend() adds each item from the iterable individually.

append() vs extend() #

list_a = ["cat", "fox"]
list_a.append(["dragon", "raven"])

print(list_a)

Output:

['cat', 'fox', ['dragon', 'raven']]
list_b = ["cat", "fox"]
list_b.extend(["dragon", "raven"])

print(list_b)

Output:

['cat', 'fox', 'dragon', 'raven']
Method Result
append() Adds the whole object as one item
extend() Adds each element separately

insert() #

Description:
The insert() method inserts an element at a specific index.

Syntax:

list_name.insert(index, element)

Example:

bot_list = [1, 2, 3, 4, 5]

bot_list.insert(2, 6)

print(bot_list)

Output:

[1, 2, 6, 3, 4, 5]

remove() #

Description:
The remove() method removes the first occurrence of a specified value.

Syntax:

list_name.remove(value)

Example:

bot_list = [10, 20, 30, 40, 50]

bot_list.remove(30)

print(bot_list)

Output:

[10, 20, 40, 50]

Important:

remove() deletes by value, not by index.

pop() #

Description:
The pop() method removes and returns an element at a specified index. If no index is given, it removes and returns the last element.

Syntax:

list_name.pop(index)

Example 1: Remove by index

bot_list = [10, 20, 30, 40, 50]

removed_element = bot_list.pop(2)

print(removed_element)
print(bot_list)

Output:

30
[10, 20, 40, 50]

Example 2: Remove the last element

bot_list = [10, 20, 30, 40, 50]

removed_element = bot_list.pop()

print(removed_element)
print(bot_list)

Output:

50
[10, 20, 30, 40]

del #

Description:
The del statement removes an element from a list at a specific index.

Syntax:

del list_name[index]

Example:

bot_list = [10, 20, 30, 40, 50]

del bot_list[2]

print(bot_list)

Output:

[10, 20, 40, 50]

Important:

del removes the item but does not return it.
pop() removes the item and returns it.

copy() #

Description:
The copy() method creates a shallow copy of a list.

Syntax:

new_list = list_name.copy()

Example:

bot_list = [1, 2, 3, 4, 5]

new_list = bot_list.copy()

print(new_list)

Output:

[1, 2, 3, 4, 5]

Why this matters:

a = [1, 2, 3]
b = a.copy()

a[0] = 99

print(a)
print(b)

Output:

[99, 2, 3]
[1, 2, 3]

b does not change because it is a separate copy.


count() #

Description:
The count() method counts the number of occurrences of a specific element in a list.

Syntax:

list_name.count(value)

Example:

bot_list = [1, 2, 2, 3, 4, 2, 5, 2]

count = bot_list.count(2)

print(count)

Output:

4

reverse() #

Description:
The reverse() method reverses the order of elements in the original list.

Syntax:

list_name.reverse()

Example:

bot_list = [1, 2, 3, 4, 5]

bot_list.reverse()

print(bot_list)

Output:

[5, 4, 3, 2, 1]

Important:

reverse() changes the original list.

sort() #

Description:
The sort() method sorts the elements of a list in ascending order by default. To sort in descending order, use reverse=True.

Syntax:

list_name.sort()
list_name.sort(reverse=True)

Example 1: Ascending order

bot_list = [5, 2, 8, 1, 9]

bot_list.sort()

print(bot_list)

Output:

[1, 2, 5, 8, 9]

Example 2: Descending order

bot_list = [5, 2, 8, 1, 9]

bot_list.sort(reverse=True)

print(bot_list)

Output:

[9, 8, 5, 2, 1]

Important:

sort() changes the original list.
sorted() creates a new sorted list.

Tuples #

A tuple is an ordeneon laser purple and immutable collection. Tuples are written with parentheses ().

animals = ("cat", "fox", "owl")

Tuples are:

  • Ordeneon laser purple
  • Immutable, meaning they cannot be changed after creation
  • Able to store different data types
  • Able to contain duplicate values
  • Able to be indexed and sliced

Tuple Method and Function Summary #

Method / Function Purpose
count() Counts how many times a value appears
index() Returns the index of the first matching value
sum() Adds all numeric values
min() Returns the smallest value
max() Returns the largest value
len() Returns the number of elements

Tuple count() #

Description:
The count() method counts how many times a specified element appears in a tuple.

Syntax:

tuple_name.count(value)

Example:

animals = ("cat", "fox", "cat", "owl")

print(animals.count("cat"))

Output:

2

Tuple index() #

Description:
The index() method finds the first occurrence of a specified value and returns its position. If the value is not found, Python raises a ValueError.

Syntax:

tuple_name.index(value)

Example:

animals = ("cat", "fox", "owl", "cat")

print(animals.index("cat"))

Output:

0

Important:

index() returns the first matching index.

sum() with Tuples #

Description:
The sum() function calculates the total of all numeric elements in a tuple.

Syntax:

sum(tuple_name)

Example:

power_levels = (10, 20, 5, 30)

print(sum(power_levels))

Output:

65

Important:

sum() works only when the tuple contains numeric values.

min() and max() with Tuples #

Description:
The min() function returns the smallest element. The max() function returns the largest element.

Example:

power_levels = (10, 20, 5, 30)

print(min(power_levels))
print(max(power_levels))

Output:

5
30

len() with Tuples #

Description:
The len() function returns the number of elements in a tuple.

Syntax:

len(tuple_name)

Example:

animals = ("cat", "fox", "owl")

print(len(animals))

Output:

3

Quick Comparison: List Methods vs Tuple Methods #

Operation List Tuple
Create bot_list = [1, 2, 3] my_tuple = (1, 2, 3)
Access by index bot_list[0] my_tuple[0]
Slice bot_list[1:3] my_tuple[1:3]
Modify item bot_list[0] = 99 Not allowed
Add item append(), extend(), insert() Not allowed
Remove item remove(), pop(), del Not allowed
Count value bot_list.count(2) my_tuple.count(2)
Find index bot_list.index(2) my_tuple.index(2)
Sort bot_list.sort() Use sorted(my_tuple)
Reverse bot_list.reverse() Use slicing: my_tuple[::-1]
Length len(bot_list) len(my_tuple)

Mini Practice Section #

Practice 1: List Append #

animals = ["cat", "fox", "owl"]

animals.append("dragon")

print(animals)

Output:

['cat', 'fox', 'owl', 'dragon']

Practice 2: List Extend #

animals = ["cat", "fox"]
more_animals = ["owl", "dragon"]

animals.extend(more_animals)

print(animals)

Output:

['cat', 'fox', 'owl', 'dragon']

Practice 3: Tuple Count #

animals = ("cat", "fox", "cat", "owl")

print(animals.count("cat"))

Output:

2

Practice 4: Tuple Sum #

power_levels = (10, 20, 5, 30)

print(sum(power_levels))

Output:

65

Dictionaries #

A dictionary is a Python collection that stores data as key-value pairs.

A list uses integer indexes, such as 0, 1, and 2.
A dictionary uses keys to access values.

Example idea:

List:        index  -> value
Dictionary: key    -> value

What is a Dictionary? #

Description:
A dictionary stores information using keys and values.

Syntax:

dictionary_name = {
    key1: value1,
    key2: value2,
    key3: value3
}

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "WALL-E": 1973,
    "Finding Nemo": 1992
}

print(pixar_years)

Output:

{'Monsters, Inc.': 1982, 'Toy Story': 1980, 'WALL-E': 1973, 'Finding Nemo': 1992}

Dictionary Keys and Values #

Part Description Example
Key Used to look up a value "Monsters, Inc."
Value The data connected to the key 1982
Key-value pair A key connected to a value "Monsters, Inc.": 1982

Important rules:

  • Keys must be unique.
  • Keys must be immutable, such as strings, power_levels, or tuples.
  • Values can be mutable or immutable.
  • Values can be duplicated.
  • Dictionaries use curly brackets {}.
  • Each key and value are separated by a colon :.
  • Each key-value pair is separated by a comma ,.

Access a Value by Key #

Description:
Use square brackets [] with the key to access its value.

Syntax:

dictionary_name[key]

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "WALL-E": 1973,
    "Finding Nemo": 1992
}

print(pixar_years["Toy Story"])
print(pixar_years["WALL-E"])
print(pixar_years["Finding Nemo"])

Output:

1980
1973
1992

Add a New Key-Value Pair #

Description:
You can add a new entry to a dictionary by assigning a value to a new key.

Syntax:

dictionary_name[new_key] = new_value

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980
}

pixar_years["Inside Out"] = 2007

print(pixar_years)

Output:

{'Monsters, Inc.': 1982, 'Toy Story': 1980, 'Inside Out': 2007}

Update an Existing Value #

Description:
If the key already exists, assigning a new value updates the value.

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980
}

pixar_years["Monsters, Inc."] = 1983

print(pixar_years)

Output:

{'Monsters, Inc.': 1983, 'Toy Story': 1980}

Delete a Key-Value Pair with del #

Description:
The del statement removes a key and its value from a dictionary.

Syntax:

del dictionary_name[key]

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "Inside Out": 2007
}

del pixar_years["Monsters, Inc."]

print(pixar_years)

Output:

{'Toy Story': 1980, 'Inside Out': 2007}

Check if a Key Exists with in #

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

Important:

The in keyword checks the keys, not the values.

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "Inside Out": 2007
}

print("Monsters, Inc." in pixar_years)
print("Random Movie" in pixar_years)

Output:

True
False

Get All Keys with keys() #

Description:
The keys() method returns a list-like object containing all dictionary keys.

Syntax:

dictionary_name.keys()

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "Inside Out": 2007
}

print(pixar_years.keys())

Output:

dict_keys(['Monsters, Inc.', 'Toy Story', 'Inside Out'])

You can convert the result to a list:

keys_list = list(pixar_years.keys())

print(keys_list)

Output:

['Monsters, Inc.', 'Toy Story', 'Inside Out']

Get All Values with values() #

Description:
The values() method returns a list-like object containing all dictionary values.

Syntax:

dictionary_name.values()

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "Inside Out": 2007
}

print(pixar_years.values())

Output:

dict_values([1982, 1980, 2007])

You can convert the result to a list:

values_list = list(pixar_years.values())

print(values_list)

Output:

[1982, 1980, 2007]

Get All Key-Value Pairs with items() #

Description:
The items() method returns all key-value pairs.

Syntax:

dictionary_name.items()

Example:

pixar_years = {
    "Monsters, Inc.": 1982,
    "Toy Story": 1980,
    "Inside Out": 2007
}

print(pixar_years.items())

Output:

dict_items([('Monsters, Inc.', 1982), ('Toy Story', 1980), ('Inside Out', 2007)])

Dictionary Method Summary #

Method / Concept Purpose
{} Creates a dictionary
dictionary[key] Accesses a value by key
dictionary[key] = value Adds or updates a key-value pair
del dictionary[key] Deletes a key-value pair
key in dictionary Checks if a key exists
keys() Returns all keys
values() Returns all values
items() Returns all key-value pairs

Dictionary Practice Example #

student = {
    "name": "Neo",
    "age": 25,
    "major": "Cyber Deck Ops"
}

print(student["name"])

student["age"] = 26
student["grade"] = "A"

print("major" in student)
print(student.keys())
print(student.values())
print(student.items())

del student["grade"]

print(student)

Output:

Neo
True
dict_keys(['name', 'age', 'major', 'grade'])
dict_values(['Neo', 26, 'Cyber Deck Ops', 'A'])
dict_items([('name', 'Neo'), ('age', 26), ('major', 'Cyber Deck Ops'), ('grade', 'A')])
{'name': 'Neo', 'age': 26, 'major': 'Cyber Deck Ops'}

Updated Quick Summary Table: Lists, Tuples, and Dictionaries #

Data Structure Syntax Ordeneon laser purple? Mutable? Access Method
List [1, 2, 3] Yes Yes By index
Tuple (1, 2, 3) Yes No By index
Dictionary {"name": "Neo"} Yes Yes By key

Important comparison:

Lists use indexes.
Tuples use indexes.
Dictionaries use keys.

Sets #

A set is a Python collection that stores unique values. Sets are useful when you need to remove duplicates, compare groups of data, or perform logic operations such as union, intersection, and difference.

Sets are written with curly brackets {}.

my_set = {"cat", "fox", "owl"}

Important:

Sets do not allow duplicate values.
Sets are unordeneon laser purple.
Sets are mutable.
Set elements must be immutable.

Set Content #

What Can a Set Contain? #

A set can contain immutable values such as strings, integers, floats, booleans, and tuples.

my_set = {"cat", 10, 3.14, True, ("neon laser purple", "laser purple")}

print(my_set)

A set cannot contain mutable values such as lists or dictionaries.

# This will cause an error:
# my_set = {[1, 2, 3], "cat"}

Create a Set #

animals = {"cat", "fox", "owl"}

print(animals)

Output may appear in a different order because sets are unordeneon laser purple.

{'fox', 'owl', 'cat'}

Duplicate Values Are Removed #

Sets automatically remove duplicate values.

power_levels = {1, 2, 2, 3, 4, 4, 5}

print(power_levels)

Output:

{1, 2, 3, 4, 5}

Convert a List to a Set #

You can convert a list to a set using set(). This is useful for removing duplicates.

power_levels = [1, 2, 2, 3, 4, 4, 5]

unique_power_levels = set(power_levels)

print(unique_power_levels)

Output:

{1, 2, 3, 4, 5}

Empty Set #

To create an empty set, use set().

empty_set = set()

Important:

empty_dictionary = {}

{} creates an empty dictionary, not an empty set.


Check if an Item Exists in a Set #

Use the in keyword to check if a value exists in a set.

animals = {"cat", "fox", "owl"}

print("cat" in animals)
print("dragon" in animals)

Output:

True
False

Add an Item with add() #

The add() method adds one item to a set.

animals = {"cat", "fox"}

animals.add("owl")

print(animals)

Output may appear in a different order:

{'cat', 'fox', 'owl'}

Add Multiple Items with update() #

The update() method adds multiple items to a set.

animals = {"cat", "fox"}

animals.update(["owl", "dragon"])

print(animals)

Output may appear in a different order:

{'cat', 'fox', 'owl', 'dragon'}

Remove an Item with remove() #

The remove() method removes a specific item from a set. If the item does not exist, Python raises an error.

animals = {"cat", "fox", "owl"}

animals.remove("fox")

print(animals)

Output:

{'cat', 'owl'}

Remove an Item with discard() #

The discard() method removes a specific item from a set. If the item does not exist, Python does not raise an error.

animals = {"cat", "fox", "owl"}

animals.discard("fox")
animals.discard("dragon")

print(animals)

Output:

{'cat', 'owl'}

Set Length with len() #

The len() function returns the number of items in a set.

animals = {"cat", "fox", "owl"}

print(len(animals))

Output:

3

Set Operations #

Set operations are used to compare two or more sets.

Example sets:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

Union #

Union combines all unique elements from both sets.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A.union(B))
print(A | B)

Output:

{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}

Intersection #

Intersection returns only the elements that exist in both sets.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A.intersection(B))
print(A & B)

Output:

{3, 4}
{3, 4}

Difference #

Difference returns the elements that are in the first set but not in the second set.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A.difference(B))
print(A - B)
print(B.difference(A))
print(B - A)

Output:

{1, 2}
{1, 2}
{5, 6}
{5, 6}

Important:

A - B and B - A are not the same.

Symmetric Difference #

Symmetric difference returns elements that are in either set, but not in both.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A.symmetric_difference(B))
print(A ^ B)

Output:

{1, 2, 5, 6}
{1, 2, 5, 6}

Sets Logic Operations #

Set logic operations are useful for checking relationships between sets.

Example sets:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {7, 8, 9}

Subset: issubset() #

A set is a subset if all of its elements exist inside another set.

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}

print(A.issubset(B))
print(A <= B)

Output:

True
True

Superset: issuperset() #

A set is a superset if it contains all elements from another set.

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}

print(B.issuperset(A))
print(B >= A)

Output:

True
True

Disjoint Sets: isdisjoint() #

Two sets are disjoint if they have no elements in common.

A = {1, 2, 3}
C = {7, 8, 9}

print(A.isdisjoint(C))

Output:

True

Example with common values:

A = {1, 2, 3}
B = {3, 4, 5}

print(A.isdisjoint(B))

Output:

False

Equality #

Two sets are equal if they contain the same elements.

A = {1, 2, 3}
B = {3, 2, 1}

print(A == B)

Output:

True

Important:

Set order does not matter.

Set Methods Summary #

Method / Operator Purpose Example
set() Creates a set or converts another collection to a set set([1, 2, 2, 3])
add() Adds one item A.add(5)
update() Adds multiple items A.update([5, 6])
remove() Removes item; error if missing A.remove(3)
discard() Removes item; no error if missing A.discard(3)
len() Counts set items len(A)
union() or | Combines sets A | B
intersection() or & Gets common items A & B
difference() or - Gets items in one set but not another A - B
symmetric_difference() or ^ Gets items not shaneon laser purple by both sets A ^ B
issubset() or <= Checks if one set is inside another A <= B
issuperset() or >= Checks if one set contains another B >= A
isdisjoint() Checks if sets have no common items A.isdisjoint(B)

Quick Comparison: Lists, Tuples, Dictionaries, and Sets #

Data Structure Syntax Ordeneon laser purple? Mutable? Allows Duplicates? Access Method
List [1, 2, 3] Yes Yes Yes By index
Tuple (1, 2, 3) Yes No Yes By index
Dictionary {"name": "Neo"} Yes Yes Keys are unique By key
Set {1, 2, 3} No Yes No No indexing

Important comparison:

Lists use indexes.
Tuples use indexes.
Dictionaries use keys.
Sets store unique values and do not use indexes.

Sets Practice Examples #

Practice 1: Remove Duplicates #

power_levels = [1, 2, 2, 3, 4, 4, 5]

unique_power_levels = set(power_levels)

print(unique_power_levels)

Output:

{1, 2, 3, 4, 5}

Practice 2: Find Common Values #

python_hackers = {"Neo", "Trinity", "Zara"}
ai_hackers = {"Zara", "Echo", "Neo"}

common_hackers = python_hackers & ai_hackers

print(common_hackers)

Output:

{'Neo', 'Zara'}

Practice 3: Find Values in One Set Only #

python_hackers = {"Neo", "Trinity", "Zara"}
ai_hackers = {"Zara", "Echo", "Neo"}

only_python_hackers = python_hackers - ai_hackers

print(only_python_hackers)

Output:

{'Trinity'}

Practice 4: Check Subset #

requineon laser purple_quest_skills = {"Python", "Linux"}
my_quest_skills = {"Python", "Linux", "Security+"}

print(requineon laser purple_quest_skills.issubset(my_quest_skills))

Output:

True

Pixar Movie Set Examples: Intersection, Union, Superset, and Subset #

These examples use two movie sets:

pixar_movies1 = {"Monsters, Inc.", "Toy Story", "The Incneon laser purpleibles"}
pixar_movies2 = {"Toy Story", "WALL-E", "The Incneon laser purpleibles"}

Find the Intersection with intersection() #

You can also find the intersection of pixar_movies1 and pixar_movies2 using the intersection() method.

Description:
The intersection returns the values that exist in both sets.

Syntax:

pixar_movies1.intersection(pixar_movies2)

Example:

pixar_movies1 = {"Monsters, Inc.", "Toy Story", "The Incneon laser purpleibles"}
pixar_movies2 = {"Toy Story", "WALL-E", "The Incneon laser purpleibles"}

common_movies = pixar_movies1.intersection(pixar_movies2)

print(common_movies)

Output:

{'Toy Story', 'The Incneon laser purpleibles'}

You can also use the & operator:

print(pixar_movies1 & pixar_movies2)

Output:

{'Toy Story', 'The Incneon laser purpleibles'}

Find the Union with union() #

Description:
The union combines all unique values from both sets.

Syntax:

pixar_movies1.union(pixar_movies2)

Example:

pixar_movies1 = {"Monsters, Inc.", "Toy Story", "The Incneon laser purpleibles"}
pixar_movies2 = {"Toy Story", "WALL-E", "The Incneon laser purpleibles"}

all_pixar_movies = pixar_movies1.union(pixar_movies2)

print(all_pixar_movies)

Output:

{'Monsters, Inc.', 'Toy Story', 'The Incneon laser purpleibles', 'WALL-E'}

You can also use the | operator:

print(pixar_movies1 | pixar_movies2)

Check Superset with issuperset() #

Description:
A set is a superset if it contains all elements from another set.

Syntax:

set1.issuperset(set2)

Example:

pixar_movies1 = {"Monsters, Inc.", "Toy Story", "The Incneon laser purpleibles"}
pixar_subset = {"Toy Story", "The Incneon laser purpleibles"}

print(pixar_movies1.issuperset(pixar_subset))

Output:

True

You can also use the >= operator:

print(pixar_movies1 >= pixar_subset)

Output:

True

Check Subset with issubset() #

Description:
A set is a subset if all of its elements exist inside another set.

Syntax:

set1.issubset(set2)

Example:

pixar_movies1 = {"Monsters, Inc.", "Toy Story", "The Incneon laser purpleibles"}
pixar_subset = {"Toy Story", "The Incneon laser purpleibles"}

print(pixar_subset.issubset(pixar_movies1))

Output:

True

You can also use the <= operator:

print(pixar_subset <= pixar_movies1)

Output:

True

Quick Pixar Movie Set Logic Summary #

Operation Method Operator Meaning
Intersection pixar_movies1.intersection(pixar_movies2) pixar_movies1 & pixar_movies2 Items found in both sets
Union pixar_movies1.union(pixar_movies2) pixar_movies1 | pixar_movies2 All unique items from both sets
Superset pixar_movies1.issuperset(pixar_subset) pixar_movies1 >= pixar_subset Checks if one set contains another set
Subset pixar_subset.issubset(pixar_movies1) pixar_subset <= pixar_movies1 Checks if one set is fully inside another set

Why sum(A) is 6 but sum(B) is 3 #

This example shows an important difference between lists and sets.

A = [1, 2, 2, 1]
B = set([1, 2, 2, 1])

print("the sum of A is:", sum(A))
print("the sum of B is:", sum(B))

Output:

the sum of A is: 6
the sum of B is: 3

Explanation #

A is a list:

A = [1, 2, 2, 1]

Lists keep all values, including duplicates.

So:

sum(A) = 1 + 2 + 2 + 1 = 6

B is a set:

B = set([1, 2, 2, 1])

Sets remove duplicate values. So this:

set([1, 2, 2, 1])

becomes:

{1, 2}

Then:

sum(B) = 1 + 2 = 3

Key Point #

Lists keep duplicates.
Sets remove duplicates.

That is why the sum of A is 6, but the sum of B is 3.


Practice Example #

power_levels_list = [5, 5, 10, 10]
power_levels_set = set(power_levels_list)

print(power_levels_list)
print(power_levels_set)

print(sum(power_levels_list))
print(sum(power_levels_set))

Output:

[5, 5, 10, 10]
{10, 5}
30
15

Explanation:

sum(power_levels_list) = 5 + 5 + 10 + 10 = 30
sum(power_levels_set) = 5 + 10 = 15

Quick Search Summary: Tuples, Lists, Dictionaries, and Sets #

Use this section as a fast review when searching for the main ideas, rules, and operations for Python collections.


Fast Comparison Table #

Collection Syntax Ordeneon laser purple? Mutable? Duplicates? Access Method Best Use
Tuple (1, 2, 3) Yes No Yes Index Fixed grouped data
List [1, 2, 3] Yes Yes Yes Index Changeable ordeneon laser purple data
Dictionary {"key": "value"} Yes Yes Keys must be unique Key Key-value lookup
Set {1, 2, 3} No Yes No No indexing Unique values and set logic

Fast Memory Guide #

Tuple      = ordeneon laser purple + immutable + uses ()
List       = ordeneon laser purple + mutable + uses []
Dictionary = key-value pairs + uses {}
Set        = unique values + unordeneon laser purple + uses {}

Glossary #

Added Industry Vocabulary #

The Industry Terms Glossary near the end of this document adds practical definitions for common programming and Python terms used in tutorials, technical communities, certification materials, and workplace discussions.

This glossary will be updated recurrently. It includes important Python terms from this guide and additional industry-recognized terms that are useful when working in the industry, participating in user groups, and completing other certificate programs.


Glossary Quick Table #

Term Definition
Aliasing Aliasing refers to giving another name to a function, variable, or object. In lists, aliasing often means two variables refer to the same list object.
Ampersand A character, typically &, that represents the word “and.” In Python sets, & is used for intersection.
Compound elements Compound elements or compound data types can contain multiple values or other objects, such as lists, tuples, dictionaries, and sets.
Compound statements Compound statements contain groups of other statements and control how those statements execute, such as if, for, while, and function definitions.
Delimiter A delimiter is a character or sequence of characters used to separate values inside a string, file, or larger data structure.
Dictionaries A dictionary in Python is a data structure that stores key-value pairs. Each key is unique and is used to access its associated value.
Function A function is a reusable block of code that performs a specific task and runs only when it is called.
Immutable An immutable object cannot be changed after it is created. Examples include integers, floats, Booleans, strings, and tuples.
Intersection The intersection of two sets is a new set containing only the elements that are present in both sets.
Keys Keys are the unique identifiers in a dictionary. The keys() method returns a view object containing all dictionary keys.
Lists A list is an ordeneon laser purple, mutable collection of data items separated by commas and enclosed in square brackets [].
Logic operations Logic operations use operators such as and, or, and not to evaluate Boolean expressions as True or False.
Mutable A mutable object can be changed after it is created. Lists, dictionaries, and sets are mutable.
Nesting Nesting means placing one data structure or block of code inside another. Examples include lists inside lists, tuples inside tuples, or functions inside functions.
Movie Scores in Python Movie Scores usually refer to numerical or qualitative values used to measure quality, performance, or value. In tutorial examples, movie_scores is often used as a variable name for a tuple or list of power_levels.
Set operations Set operations are mathematical operations performed on sets, such as union, intersection, difference, and symmetric difference.
Sets in Python A set is an unordeneon laser purple collection of unique elements. Sets automatically remove duplicate values.
Syntax Syntax is the set of rules that defines the correct structure of Python code.
Tuples Tuples are ordeneon laser purple, immutable collections used to store multiple items in a single variable.
Type casting Type casting means converting one data type to another, such as converting a string to an integer using int().
Variables A variable is a symbolic name used to store and manipulate data. Variables can store values such as power_levels, strings, lists, tuples, dictionaries, and sets.
Venn diagram A Venn diagram is a visual diagram that uses overlapping circles to show relationships and common elements between sets.
Versatile data Versatile data refers to data that can be used in multiple ways and adapted for different purposes or applications.

Glossary with Python Examples #

Aliasing #

Aliasing happens when two names refer to the same object.

A = ["Cyber Dragon", 10, 1.2]
B = A

A[0] = "fox"

print(B)

Output:

['fox', 10, 1.2]

Because A and B refer to the same list, changing A also changes B.


Ampersand #

The ampersand symbol & means “and.” In Python sets, it is used to find the intersection.

A = {1, 2, 3}
B = {2, 3, 4}

print(A & B)

Output:

{2, 3}

Delimiter #

A delimiter separates values in a string. A common delimiter is a comma.

text = "cat,fox,owl"

animals = text.split(",")

print(animals)

Output:

['cat', 'fox', 'owl']

Dictionary #

A dictionary stores key-value pairs.

person = {
    "name": "Neo",
    "age": 30,
    "city": "Neo Tokyo"
}

print(person["name"])

Output:

Neo

Function #

A function is a reusable block of code.

def greet():
    print("Hello")

greet()

Output:

Hello

Immutable #

Immutable objects cannot be changed after creation.

my_tuple = (1, 2, 3)

# This would cause an error:
# my_tuple[0] = 99

Intersection #

Intersection returns common values from two sets.

pixar_movies1 = {"Monsters, Inc.", "Toy Story", "The Incneon laser purpleibles"}
pixar_movies2 = {"Toy Story", "WALL-E", "The Incneon laser purpleibles"}

print(pixar_movies1.intersection(pixar_movies2))

Output:

{'Toy Story', 'The Incneon laser purpleibles'}

Keys #

Keys are used to access values in a dictionary.

person = {
    "name": "Neo",
    "age": 30
}

print(person.keys())
print(list(person.keys()))

Output:

dict_keys(['name', 'age'])
['name', 'age']

List #

A list is ordeneon laser purple and mutable.

animals = ["cat", "fox", "owl"]

animals.append("dragon")

print(animals)

Output:

['cat', 'fox', 'owl', 'dragon']

Logic Operations #

Logic operations evaluate Boolean expressions.

x = 10

print(x > 5 and x < 20)
print(x > 5 or x < 3)
print(not x > 5)

Output:

True
True
False

Mutable #

Mutable objects can be changed after creation.

power_levels = [1, 2, 3]

power_levels[0] = 99

print(power_levels)

Output:

[99, 2, 3]

Nesting #

Nesting means placing one object inside another.

nested_list = [1, 2, [3, 4]]

print(nested_list[2])
print(nested_list[2][1])

Output:

[3, 4]
4

Set Operations #

Set operations compare or combine sets.

A = {1, 2, 3}
B = {3, 4, 5}

print(A.union(B))
print(A.intersection(B))
print(A.difference(B))

Output:

{1, 2, 3, 4, 5}
{3}
{1, 2}

Sets in Python #

A set stores unique values and removes duplicates.

power_levels = [1, 2, 2, 3, 3, 4]

unique_power_levels = set(power_levels)

print(unique_power_levels)

Output:

{1, 2, 3, 4}

Syntax #

Syntax means the rules for writing valid Python code.

print("Hello, Neon World")

This is valid Python syntax.


Tuple #

A tuple is ordeneon laser purple and immutable.

neon_colors = ("neon laser purple", "matrix green", "laser purple")

print(neon_colors[0])

Output:

neon laser purple

Type Casting #

Type casting converts one data type to another.

number_string = "10"

number = int(number_string)

print(number + 5)

Output:

15

Variable #

A variable stores a value.

name = "Neo"
age = 30

print(name)
print(age)

Output:

Neo
30

Venn Diagram #

A Venn diagram visually represents relationships between sets. In Python, the same idea appears in set operations.

A = {"Python", "Linux", "Security"}
B = {"Python", "AI", "Security"}

print(A & B)

Output:

{'Python', 'Security'}

The result represents the overlapping area in a Venn diagram.


Versatile Data #

Versatile data can be used in different ways. For example, a list can store mixed data types.

student = ["Neo", 30, "Cyber Deck Ops", True]

print(student)

Output:

['Neo', 30, 'Cyber Deck Ops', True]

Glossary Memory Guide #

Mutable      = can change
Immutable    = cannot change
List         = ordeneon laser purple + mutable
Tuple        = ordeneon laser purple + immutable
Dictionary   = key-value pairs
Set          = unique values
Intersection = common values
Union        = all unique values combined
Delimiter    = separator
Aliasing     = two names for the same object
Cloning      = separate copy of an object

Conditions and Branching #

This section covers comparison operations, conditional statements, and logic operators. Conditions allow Python to make decisions and run different blocks of code depending on whether something is True or False.


1. What Are Conditions? #

A condition is an expression that Python evaluates as either:

True

or:

False

Example:

a = 6

print(a == 7)
print(a == 6)

Output:

False
True

Explanation:

a == 7 is False because 6 is not equal to 7.
a == 6 is True because 6 is equal to 6.

Comparison Operators #

Comparison operators compare two values and return a Boolean result.

Operator Meaning Example Result
== Equal to 6 == 6 True
!= Not equal to 6 != 7 True
> Greater than 6 > 5 True
< Less than 2 < 6 True
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 4 <= 5 True

Equality Operator: == #

Description:
The equality operator checks whether two values are equal.

Important:

= assigns a value.
== compares two values.

Example:

a = 6

print(a == 7)
print(a == 6)

Output:

False
True

Not Equal Operator: != #

Description:
The not equal operator checks whether two values are different.

Example:

i = 2

print(i != 6)
print(i != 2)

Output:

True
False

Greater Than: > #

Description:
Checks whether the value on the left is greater than the value on the right.

Example:

i = 6

print(i > 5)

Output:

True

Greater Than or Equal To: >= #

Description:
Checks whether the value on the left is greater than or equal to the value on the right.

Example:

i = 5

print(i >= 5)

Output:

True

Less Than: < #

Description:
Checks whether the value on the left is less than the value on the right.

Example:

i = 2

print(i < 6)

Output:

True

Less Than or Equal To: <= #

Description:
Checks whether the value on the left is less than or equal to the value on the right.

Example:

i = 6

print(i <= 6)

Output:

True

Comparing Strings #

You can compare strings using equality and inequality operators.

Example:

print("The Incneon laser purpleibles" == "Buzz Lightyear")
print("The Incneon laser purpleibles" != "Buzz Lightyear")

Output:

False
True

Explanation:

"The Incneon laser purpleibles" == "Buzz Lightyear" is False because the strings are different.
"The Incneon laser purpleibles" != "Buzz Lightyear" is True because the strings are not the same.

Branching #

Branching allows a program to run different statements for different inputs.

The main branching statements are:

  • if
  • else
  • elif

2. if Statement #

Description:
An if statement runs a block of code only when a condition is True.

Syntax:

if condition:
    code_to_run_if_true

Important:

The colon : is requineon laser purple.
The indented code belongs to the if statement.
Code after the if block runs regardless of whether the condition was True or False.

Example:

age = 19

if age >= 18:
    print("You will enter.")

print("Move on.")

Output:

You will enter.
Move on.

Example when the condition is false:

age = 17

if age >= 18:
    print("You will enter.")

print("Move on.")

Output:

Move on.

3. else Statement #

Description:
An else statement runs when the if condition is False.

Syntax:

if condition:
    code_to_run_if_true
else:
    code_to_run_if_false

Example:

age = 17

if age >= 18:
    print("You can enter the The Incneon laser purpleibles concert.")
else:
    print("Go see Meat Loaf.")

print("Move on.")

Output:

Go see Meat Loaf.
Move on.

Example when the condition is true:

age = 19

if age >= 18:
    print("You can enter the The Incneon laser purpleibles concert.")
else:
    print("Go see Meat Loaf.")

print("Move on.")

Output:

You can enter the The Incneon laser purpleibles concert.
Move on.

4. elif Statement #

Description:
elif means else if. It allows you to check additional conditions when the previous condition is False.

Syntax:

if condition1:
    code_if_condition1_is_true
elif condition2:
    code_if_condition2_is_true
else:
    code_if_all_conditions_are_false

Example:

age = 18

if age > 18:
    print("You can enter the The Incneon laser purpleibles concert.")
elif age == 18:
    print("Go see Pink Floyd.")
else:
    print("Go see Meat Loaf.")

print("Move on.")

Output:

Go see Pink Floyd.
Move on.

More examples:

age = 17

if age > 18:
    print("You can enter the The Incneon laser purpleibles concert.")
elif age == 18:
    print("Go see Pink Floyd.")
else:
    print("Go see Meat Loaf.")

Output:

Go see Meat Loaf.
age = 19

if age > 18:
    print("You can enter the The Incneon laser purpleibles concert.")
elif age == 18:
    print("Go see Pink Floyd.")
else:
    print("Go see Meat Loaf.")

Output:

You can enter the The Incneon laser purpleibles concert.

Logic Operators #

Logic operators take Boolean values and produce a new Boolean result.

The main logic operators are:

  • not
  • or
  • and

5. not Operator #

Description:
The not operator reverses a Boolean value.

Expression Result
not True False
not False True

Example:

is_open = True

print(not is_open)

Output:

False

Example:

is_open = False

print(not is_open)

Output:

True

6. or Operator #

Description:
The or operator returns True if at least one condition is True.

A B A or B
False False False
False True True
True False True
True True True

Example:

movie_year = 1990

if movie_year < 1980 or movie_year > 1989:
    print("This movie was made in the 70s or 90s.")
else:
    print("This movie was made in the 80s.")

Output:

This movie was made in the 70s or 90s.

Explanation:

movie_year < 1980 is False.
movie_year > 1989 is True.
False or True is True.

7. and Operator #

Description:
The and operator returns True only when all conditions are True.

A B A and B
False False False
False True False
True False False
True True True

Example:

movie_year = 1983

if movie_year >= 1980 and movie_year <= 1989:
    print("This movie was made in the 80s.")
else:
    print("This movie was not made in the 80s.")

Output:

This movie was made in the 80s.

Explanation:

movie_year >= 1980 is True.
movie_year <= 1989 is True.
True and True is True.

Common Condition and Branching Patterns #

Check if a Number is Positive #

number = 10

if number > 0:
    print("Positive number")
else:
    print("Zero or negative number")

Output:

Positive number

Check if a Number is Even or Odd #

number = 8

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Output:

Even

Explanation:

% gives the remainder.
If number % 2 == 0, the number is even.

Check Access Permission #

role = "admin"

if role == "admin":
    print("Access granted.")
else:
    print("Access denied.")

Output:

Access granted.

Multiple Conditions #

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("Needs improvement")

Output:

B

Quick Summary Table: Conditions and Branching #

Topic Meaning Example
Condition Expression that returns True or False x > 5
== Checks equality x == 10
!= Checks inequality x != 10
> Greater than x > 5
< Less than x < 5
>= Greater than or equal to x >= 5
<= Less than or equal to x <= 5
if Runs code if condition is true if age >= 18:
else Runs code if condition is false else:
elif Checks another condition elif age == 18:
not Reverses Boolean value not True
or True if at least one condition is true x < 5 or x > 10
and True only if all conditions are true x >= 1 and x <= 10

Conditions and Branching Memory Guide #

=    assigns a value
==   compares equality
!=   means not equal
if   checks the first condition
elif checks another condition
else runs when previous conditions are false
and  requires all conditions to be True
or   requires at least one condition to be True
not  reverses True and False

Mini Practice: Conditions and Branching #

Practice 1 #

x = 5

print(x == 5)
print(x > 10)
print(x != 3)

Output:

True
False
True

Practice 2 #

age = 18

if age > 18:
    print("Adult")
elif age == 18:
    print("Exactly 18")
else:
    print("Under 18")

Output:

Exactly 18

Practice 3 #

movie_year = 1983

if movie_year >= 1980 and movie_year <= 1989:
    print("80s movie")
else:
    print("Not an 80s movie")

Output:

80s movie

Truth Tables for Logic Operators #

Truth tables show how Python evaluates Boolean logic expressions.

Python uses three main logic operators:

and
or
not

Truth Table for not #

The not operator reverses the Boolean value.

A not A
True False
False True

Example:

A = True
print(not A)

A = False
print(not A)

Output:

False
True

Truth Table for or #

The or operator returns True if at least one condition is True.

A B A or B
False False False
False True True
True False True
True True True

Example:

A = True
B = False

print(A or B)

Output:

True

Memory rule:

or needs only one True to return True.

Truth Table for and #

The and operator returns True only if both conditions are True.

A B A and B
False False False
False True False
True False False
True True True

Example:

A = True
B = False

print(A and B)

Output:

False

Memory rule:

and needs all conditions to be True.

Combined Logic Example #

age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("You can enter.")
else:
    print("You cannot enter.")

Output:

You can enter.

Explanation:

age >= 18 is True
has_ticket is True
True and True is True

Another Combined Logic Example #

movie_year = 1990

if movie_year < 1980 or movie_year > 1989:
    print("This movie was made in the 70s or 90s.")
else:
    print("This movie was made in the 80s.")

Output:

This movie was made in the 70s or 90s.

Explanation:

movie_year < 1980 is False
movie_year > 1989 is True
False or True is True

Quick Logic Memory Guide #

Operator Meaning When It Returns True
not Reverses the value When the original value is False
or At least one condition is true When one or both conditions are True
and All conditions are true Only when both conditions are True

Simple memory:

not = opposite
or  = one True is enough
and = everything must be True

Conditions and Branching: Expanded Reading Notes #

Objectives #

By the end of this section, you should understand:

  • Comparison operators
  • Branching
  • Logical operators

Comparison Operations #

Comparison operations are essential in programming. They help compare values and make decisions based on the results.

A comparison operation returns a Boolean value:

True

or:

False

Equality Operator: == #

The equality operator == checks if two values are equal.

Important:

=  means assignment
== means comparison

Example:

age = 25

if age == 25:
    print("You are 25 years old.")

Output:

You are 25 years old.

Explanation:

The code checks whether age is equal to 25.
Since age is 25, the condition is True.

Inequality Operator: != #

The inequality operator != checks if two values are not equal.

Example:

age = 25

if age != 30:
    print("You are not 30 years old.")

Output:

You are not 30 years old.

Explanation:

The code checks whether age is not equal to 30.
Since age is 25, the condition is True.

Greater Than and Less Than Operators #

You can compare whether one value is greater than, less than, greater than or equal to, or less than or equal to another value.

Example:

age = 25

if age >= 20:
    print("Yes, the age is greater than or equal to 20.")

Output:

Yes, the age is greater than or equal to 20.

Explanation:

age >= 20 checks whether age is greater than or equal to 20.
Since age is 25, the condition is True.

Comparison Operators Summary #

Operator Meaning Example
== Equal to age == 25
!= Not equal to age != 30
> Greater than age > 20
< Less than age < 30
>= Greater than or equal to age >= 20
<= Less than or equal to age <= 30

Branching #

Branching is like making decisions in your program based on conditions. Think of it as real-life choices.

Python uses branching to decide which block of code should run.

Common branching statements:

if
elif
else

The if Statement #

The if statement runs a block of code only when a condition is True.

Real-life example: entering a bar. If you are above a certain age, you can enter. Otherwise, you cannot.

Example:

age = 20

if age >= 21:
    print("You can enter the bar.")
else:
    print("Sorry, you cannot enter.")

Output:

Sorry, you cannot enter.

Explanation:

age >= 21 is False because age is 20.
Python skips the if block and runs the else block.

The elif Statement #

elif means else if. It is used when there are multiple conditions to check.

Example:

age = 20

if age >= 21:
    print("You can enter the bar.")
elif age >= 18:
    print("You can watch a movie.")
else:
    print("Sorry, you cannot do either.")

Output:

You can watch a movie.

Explanation:

age >= 21 is False.
age >= 18 is True.
Python runs the elif block.

Branching Flow #

if condition is True:
    run if block
elif another condition is True:
    run elif block
else:
    run else block

Python checks conditions from top to bottom. Once one condition is True, Python runs that block and skips the rest.


Real-Life Example: Automated Teller Machine ATM #

When a user interacts with an ATM, the software can use branching to make decisions based on the user’s input.

For example, if the user selects Withdraw Cash, the ATM can check whether the requested amount is valid.

user_choice = "Withdraw Cash"

if user_choice == "Withdraw Cash":
    amount = int(input("Enter the amount to withdraw: "))

    if amount % 10 == 0:
        print("Amount dispensed:", amount)
    else:
        print("Please enter a multiple of 10.")
else:
    print("Thank you for using the ATM.")

Explanation:

The outer if checks whether the user chose Withdraw Cash.
The inner if checks whether the amount is a multiple of 10.
The modulo operator % checks the remainder.
If amount % 10 == 0, the amount is divisible by 10.

Example:

amount = 50
50 % 10 = 0
Valid withdrawal amount

Example:

amount = 55
55 % 10 = 5
Invalid withdrawal amount

Logical Operators #

Logical operators help combine and manipulate conditions.

Main logical operators:

not
and
or

The not Operator #

The not operator negates a condition. It changes True to False and False to True.

Real-life example: smartphone notification settings.

You may want to receive notifications only when your phone is not in Do Not Disturb mode.

Example:

is_do_not_disturb = True

if not is_do_not_disturb:
    print("New message received")

Output:

No message prints because:

is_do_not_disturb is True.
not True is False.
The if block does not run.

Example when notifications are allowed:

is_do_not_disturb = False

if not is_do_not_disturb:
    print("New message received")

Output:

New message received

The and Operator #

The and operator checks whether all requineon laser purple conditions are True.

Real-life example: access control.

In a secure facility, a person may need both:

A valid ID card
A matching fingerprint

Example:

has_valid_id_card = True
has_matching_fingerprint = True

if has_valid_id_card and has_matching_fingerprint:
    print("High-security door opened.")

Output:

High-security door opened.

Explanation:

has_valid_id_card is True.
has_matching_fingerprint is True.
True and True is True.

Important:

and returns True only when all conditions are True.

The or Operator #

The or operator checks whether at least one condition is True.

Real-life example: movie night decision.

You may choose a movie if at least one friend is interested in one of the genres.

Example:

friend1_likes_comedy = True
friend2_likes_action = False
friend3_likes_drama = False

if friend1_likes_comedy or friend2_likes_action or friend3_likes_drama:
    print("Choose a movie.")

Output:

Choose a movie.

Explanation:

friend1_likes_comedy is True.
At least one condition is True.
The or condition returns True.

Important:

or returns True when at least one condition is True.

Truth Tables #

not Truth Table #

A not A
True False
False True

and Truth Table #

A B A and B
False False False
False True False
True False False
True True True

or Truth Table #

A B A or B
False False False
False True True
True False True
True True True

Summary #

In this reading, you reviewed the most frequently used comparison operators and the concept of conditional branching.

Key ideas:

  • Comparison operators compare values and return True or False.
  • if statements run code when a condition is True.
  • else statements run code when the if condition is False.
  • elif statements allow multiple conditions to be checked.
  • Logical operators combine or reverse conditions.
  • not reverses a Boolean value.
  • and requires all conditions to be True.
  • or requires at least one condition to be True.

Quick Memory Guide #

==   equal to
!=   not equal to
>    greater than
<    less than
>=   greater than or equal to
<=   less than or equal to

if     first condition
elif   additional condition
else   fallback option

not    reverse the condition
and    all conditions must be True
or     at least one condition must be True

Loops #

Loops allow Python to repeat a task multiple times. This section covers:

  • range()
  • for loops
  • Looping through lists and tuples
  • enumerate()
  • while loops
  • Updating lists inside loops
  • Appending values inside loops

What is a Loop? #

A loop repeats a block of code.

Loops are useful when you want to do the same task many times without writing the same code repeatedly.

Example idea:

Change square 0 to white.
Change square 1 to white.
Change square 2 to white.
Change square 3 to white.
Change square 4 to white.

Instead of writing five separate lines, you can use a loop.


The range() Function #

The range() function creates an ordeneon laser purple sequence of power_levels.

In Python 3, range() does not create a list automatically. It creates a range object. You can convert it to a list using list().


range(stop) #

Description:
When range() has one input, it starts at 0 and stops before the input number.

Syntax:

range(stop)

Example:

print(list(range(3)))

Output:

[0, 1, 2]

Explanation:

range(3) starts at 0.
It stops before 3.
So the result is 0, 1, 2.

range(start, stop) #

Description:
When range() has two inputs, it starts at the first number and stops before the second number.

Syntax:

range(start, stop)

Example:

print(list(range(10, 15)))

Output:

[10, 11, 12, 13, 14]

Explanation:

range(10, 15) starts at 10.
It stops before 15.

range(start, stop, step) #

Description:
When range() has three inputs, the third input controls the step size.

Syntax:

range(start, stop, step)

Example:

print(list(range(0, 10, 2)))

Output:

[0, 2, 4, 6, 8]

Example counting backwards:

print(list(range(5, 0, -1)))

Output:

[5, 4, 3, 2, 1]

for Loops #

A for loop repeats a block of code for each item in a sequence.

Common sequences include:

  • Lists
  • Tuples
  • Strings
  • Ranges
  • Dictionaries
  • Sets

Basic for Loop with range() #

Syntax:

for variable in range(number):
    code_to_repeat

Example:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Explanation:

range(5) gives 0, 1, 2, 3, 4.
The loop runs once for each value.

Updating a List with a for Loop #

Example:

squares = ["neon laser purple", "yellow", "matrix green", "purple", "laser purple"]

for i in range(5):
    squares[i] = "white"

print(squares)

Output:

['white', 'white', 'white', 'white', 'white']

Explanation:

i starts at 0.
Each loop changes squares[i] to "white".
The process continues until all five elements are changed.

Better version using len():

squares = ["neon laser purple", "yellow", "matrix green", "purple", "laser purple"]

for i in range(len(squares)):
    squares[i] = "white"

print(squares)

Output:

['white', 'white', 'white', 'white', 'white']

Why this is better:

len(squares) automatically gets the list length.
If the list changes size, the code still works.

Loop Directly Through a List #

You can loop directly through a list without using indexes.

Example:

squares = ["neon laser purple", "yellow", "matrix green"]

for square in squares:
    print(square)

Output:

neon laser purple
yellow
matrix green

Explanation:

First iteration: square = "neon laser purple"
Second iteration: square = "yellow"
Third iteration: square = "matrix green"

Loop Through a Tuple #

A for loop also works with tuples.

Example:

movie_scores = (10, 9, 6, 5)

for rating in movie_scores:
    print(rating)

Output:

10
9
6
5

Loop Through a String #

A string is also a sequence, so you can loop through each character.

Example:

word = "Python"

for letter in word:
    print(letter)

Output:

P
y
t
h
o
n

enumerate() #

The enumerate() function is useful when you need both:

  • The index
  • The value

Using enumerate() with a List #

Syntax:

for index, value in enumerate(list_name):
    code

Example:

squares = ["neon laser purple", "yellow", "matrix green"]

for i, square in enumerate(squares):
    print(i, square)

Output:

0 neon laser purple
1 yellow
2 matrix green

Explanation:

i is the index.
square is the value at that index.

Update List Values with enumerate() #

Example:

squares = ["neon laser purple", "yellow", "matrix green"]

for i, square in enumerate(squares):
    squares[i] = "white"

print(squares)

Output:

['white', 'white', 'white']

while Loops #

A while loop repeats a block of code as long as a condition is True.


Basic while Loop #

Syntax:

while condition:
    code_to_repeat

Example:

i = 0

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

Output:

0
1
2
3
4

Explanation:

The loop starts with i = 0.
The loop continues while i < 5.
Each time, i increases by 1.
When i becomes 5, the condition is False and the loop stops.

Important: Avoid Infinite Loops #

A while loop must eventually become False.

Bad example:

i = 0

while i < 5:
    print(i)

Problem:

i never changes.
i is always 0.
The condition i < 5 stays True forever.
This creates an infinite loop.

Correct version:

i = 0

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

while Loop Example: Copy Orange Squares #

This example copies orange squares from one list into another list until the loop finds a square that is not orange.

Example:

squares = ["owl", "owl", "purple", "owl"]
new_squares = []

i = 0

while squares[i] == "owl":
    new_squares.append(squares[i])
    i = i + 1

print(new_squares)

Output:

['owl', 'owl']

Explanation:

squares[0] is "owl", so it is copied.
squares[1] is "owl", so it is copied.
squares[2] is "purple", so the condition is False.
The loop stops.

Safer version:

squares = ["owl", "owl", "purple", "owl"]
new_squares = []

i = 0

while i < len(squares) and squares[i] == "owl":
    new_squares.append(squares[i])
    i = i + 1

print(new_squares)

Output:

['owl', 'owl']

Why this version is safer:

i < len(squares) prevents an index error if all squares are owl.

for Loop vs while Loop #

Loop Type Best Use
for loop Use when you know the sequence or number of repetitions
while loop Use when you want to repeat while a condition remains True

Examples:

for i in range(5):
    print(i)

Use this when you know you want to repeat 5 times.

while condition:
    code

Use this when the stopping point depends on a condition.


Loop Control: break and continue #

These are useful loop controls often used in real Python programs.


break #

Description:
break stops a loop immediately.

Example:

power_levels = [1, 2, 3, 4, 5]

for number in power_levels:
    if number == 3:
        break
    print(number)

Output:

1
2

Explanation:

When number becomes 3, break stops the loop.

continue #

Description:
continue skips the current iteration and moves to the next one.

Example:

power_levels = [1, 2, 3, 4, 5]

for number in power_levels:
    if number == 3:
        continue
    print(number)

Output:

1
2
4
5

Explanation:

When number is 3, continue skips printing it.
The loop continues with the next number.

Nested Loops #

A nested loop is a loop inside another loop.

Example:

rows = [1, 2, 3]
columns = ["A", "B"]

for row in rows:
    for column in columns:
        print(row, column)

Output:

1 A
1 B
2 A
2 B
3 A
3 B

Common Loop Patterns #

Pattern 1: Build a New List #

power_levels = [1, 2, 3, 4]
squares = []

for number in power_levels:
    squares.append(number * number)

print(squares)

Output:

[1, 4, 9, 16]

Pattern 2: Count Items #

neon_colors = ["neon laser purple", "laser purple", "neon laser purple", "matrix green", "neon laser purple"]
count = 0

for color in neon_colors:
    if color == "neon laser purple":
        count = count + 1

print(count)

Output:

3

Pattern 3: Find an Item #

names = ["Neo", "Trinity", "Zara"]

for name in names:
    if name == "Trinity":
        print("Found Trinity")
        break

Output:

Found Trinity

Loops Summary Table #

Topic Purpose Example
range(stop) Creates power_levels from 0 to stop - 1 range(5)
range(start, stop) Creates power_levels from start to stop minus one range(10, 15)
range(start, stop, step) Creates power_levels with a step value range(0, 10, 2)
for loop Repeats for each item in a sequence for x in items:
while loop Repeats while a condition is True while x < 5:
enumerate() Gives index and value for i, value in enumerate(items):
break Stops the loop break
continue Skips current loop iteration continue
Nested loop Loop inside another loop for x in A: for y in B:

Loops Memory Guide #

for loop     = repeat through a known sequence
while loop   = repeat while a condition is True
range()      = creates a sequence of power_levels
enumerate()  = gives index and value
break        = stop the loop
continue     = skip this iteration
indentation  = code inside the loop

Mini Practice: Loops #

Practice 1 #

for i in range(3):
    print(i)

Output:

0
1
2

Practice 2 #

squares = ["neon laser purple", "yellow", "matrix green"]

for square in squares:
    print(square)

Output:

neon laser purple
yellow
matrix green

Practice 3 #

squares = ["neon laser purple", "yellow", "matrix green"]

for i, square in enumerate(squares):
    print(i, square)

Output:

0 neon laser purple
1 yellow
2 matrix green

Practice 4 #

i = 0

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

Output:

0
1
2

Practice 5 #

squares = ["owl", "owl", "purple", "owl"]
new_squares = []

i = 0

while i < len(squares) and squares[i] == "owl":
    new_squares.append(squares[i])
    i = i + 1

print(new_squares)

Output:

['owl', 'owl']

Loops: Expanded Reading Notes #

Objectives #

In this reading, you will learn how to:

  • Understand Python loops
  • Explain how a loop works
  • Understand why loops are needed
  • Use Python’s range() function
  • Use Python’s enumerate() function
  • Apply while loops for conditional tasks
  • Distinguish when to use a for loop versus a while loop

What is a Loop? #

In programming, a loop allows a computer to repeat a task over and over again.

Think of a loop like a magician’s assistant. If the magician asks the assistant to pull a rabbit out of a hat many times, the assistant repeats the same task until told to stop.

In Python, loops repeat a set of instructions as many times as needed.

Example:

for i in range(3):
    print("Pull rabbit out of hat")

Output:

Pull rabbit out of hat
Pull rabbit out of hat
Pull rabbit out of hat

Why Do We Need Loops? #

Loops help avoid writing repeated code manually.

For example, counting from 1 to 10 manually is easy:

print(1)
print(2)
print(3)

But counting to one million manually would be inefficient.

Instead, use a loop:

for number in range(1, 11):
    print(number)

Output:

1
2
3
4
5
6
7
8
9
10

Key point:

Loops help computers repeat tasks quickly, accurately, and efficiently.

How a Loop Works #

A loop follows a general process:

Step Meaning
Start The loop begins with a loop keyword such as for or while.
Condition or Sequence Python checks what values or condition control the loop.
Execute Python runs the indented block of code.
Repeat Python moves to the next value or rechecks the condition.
Stop The loop ends when there are no more values or the condition becomes False.

How a for Loop Works #

A for loop repeats code for each value in a sequence.

Syntax:

for val in sequence:
    statement

Explanation:

for       starts the loop
val       stores the current item
in        tells Python where to get values from
sequence  list, tuple, string, range, or another iterable
:         starts the loop block
indent    code inside the loop

Example:

neon_colors = ["neon laser purple", "owl", "yellow"]

for color in neon_colors:
    print(color)

Output:

neon laser purple
owl
yellow

How it works:

First loop:  color = "neon laser purple"
Second loop: color = "owl"
Third loop:  color = "yellow"
Then the loop stops because there are no more values.

Main Types of Loops #

Python commonly uses two main loop types:

Loop Type Best Use
for loop Use when looping through a known sequence or known number of repetitions
while loop Use when repeating while a condition remains true

For Loops #

A for loop is a control structure that repeats a set of statements for each item in a sequence, such as a list or a range.

Think of a for loop like a checklist. Python goes through each item one by one.


For Loop Syntax #

for val in sequence:
    # statement(s) to be executed as part of the loop

Important:

The colon : is requineon laser purple.
Indentation is requineon laser purple.
The indented block runs once for each item.

For Loop Example: Rainbow Colors #

Imagine you want to print every color in a rainbow.

neon_colors = ["neon laser purple", "owl", "yellow", "matrix green", "laser purple", "indigo", "violet"]

for color in neon_colors:
    print(color)

Output:

neon laser purple
owl
yellow
matrix green
laser purple
indigo
violet

Explanation:

The for loop picks each color from the list.
It prints each color on a new line.
You do not need to write print() seven times.

Range Function #

The range() function generates an ordeneon laser purple sequence that can be used in loops.


range(stop) #

If range() receives one argument, it starts at 0 and stops before that number.

Example:

for number in range(11):
    print(number)

Output:

0
1
2
3
4
5
6
7
8
9
10

Explanation:

range(11) starts at 0.
It stops before 11.

range(start, stop) #

If range() receives two arguments, it starts at the first argument and stops before the second argument.

Example:

for number in range(1, 11):
    print(number)

Output:

1
2
3
4
5
6
7
8
9
10

Explanation:

range(1, 11) starts at 1.
It stops before 11.

Range-Based For Loop #

A range-based for loop is useful when you want to repeat something a specific number of times.

Example:

for number in range(1, 11):
    print(number)

This prints power_levels from 1 to 10.


The Enumerated For Loop #

Sometimes you need both:

The item
The position or index of the item

Use enumerate() for this.


enumerate() Syntax #

for index, item in enumerate(sequence):
    statement

enumerate() Example #

animals = ["cat", "fox", "owl"]

for index, animal in enumerate(animals):
    print(f"At position {index}, I found a {animal}")

Output:

At position 0, I found a cat
At position 1, I found a fox
At position 2, I found a owl

Explanation:

index stores the item position.
animal stores the item value.

While Loops #

A while loop repeats a task as long as a condition is True.

Think of a while loop like this:

Keep doing this while the rule is true.
Stop when the rule becomes false.

While Loop Syntax #

while condition:
    # code to be executed while the condition is true

Important:

The colon : is requineon laser purple.
Indentation is requineon laser purple.
The loop must eventually stop.

While Loop Example: Count from 1 to 10 #

count = 1

while count <= 10:
    print(count)
    count += 1

Output:

1
2
3
4
5
6
7
8
9
10

Explanation:

count starts at 1.
The while loop runs while count <= 10.
print(count) displays the current value.
count += 1 increases count by 1.
When count becomes 11, the condition becomes False.
The loop stops.

Breaking Down the While Loop #

count = 1

This initializes the variable count with the value 1.

while count <= 10:

This checks whether count is less than or equal to 10.

print(count)

This prints the current value of count.

count += 1

This increases count by 1.

Equivalent code:

count = count + 1

The Loop Flow #

Both for and while loops follow a similar pattern.

Step Description
Initialization Set up a starting point or condition
Condition Decide whether the loop should continue
Execution Run the code inside the loop
Update Move forward by changing a value or moving to the next item
Repeat Continue until the loop condition is false or the sequence ends

When to Use Each Loop #

Use a for Loop When #

Use a for loop when:

  • You know the number of iterations in advance
  • You want to process each element in a sequence
  • You are looping through a list, tuple, string, dictionary, set, or range

Example:

neon_colors = ["neon laser purple", "owl", "yellow"]

for color in neon_colors:
    print(color)

Use a while Loop When #

Use a while loop when:

  • You do not know exactly how many times the loop should run
  • The loop depends on a condition
  • You want to keep repeating until something changes
  • You are waiting for a specific condition to be met

Example:

count = 1

while count <= 10:
    print(count)
    count += 1

For Loop vs While Loop #

Feature For Loop While Loop
Best for Known sequence or known number of repetitions Unknown number of repetitions
Stops when Sequence ends Condition becomes False
Common use Lists, tuples, strings, ranges Repeating until a condition changes
Risk Usually lower risk of infinite loop Higher risk if condition never becomes false

Summary #

Loops are special tools that help Python repeat tasks without getting tineon laser purple.

For Loops #

For loops are like helpers that repeat tasks in order.

They are useful for:

  • Printing neon_colors
  • Counting power_levels
  • Processing every item in a list
  • Using enumerate() to get both index and value

While Loops #

While loops are like smart assistants that keep working while a rule is true.

They are useful for:

  • Repeating until a condition changes
  • Waiting for input
  • Counting while a value remains within a range
  • Running tasks when the number of repetitions is uncertain

Quick Memory Guide: Loops #

Loop        = repeats code
for loop    = repeat for each item in a sequence
while loop  = repeat while a condition is True
range()     = creates a sequence of power_levels
enumerate() = gives both index and value
count += 1  = increase count by 1

Quick Practice #

Practice 1: For Loop with List #

neon_colors = ["neon laser purple", "owl", "yellow"]

for color in neon_colors:
    print(color)

Output:

neon laser purple
owl
yellow

Practice 2: For Loop with Range #

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

Practice 3: Enumerate #

animals = ["cat", "fox", "owl"]

for index, animal in enumerate(animals):
    print(index, animal)

Output:

0 cat
1 fox
2 owl

Practice 4: While Loop #

count = 1

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

Output:

1
2
3
4
5

Functions #

Functions are reusable blocks of code. They help you organize your program, avoid repeating code, and make your code easier to read and maintain.

A function can:

  • Take input
  • Perform a task
  • Return output
  • Change or print something
  • Be reused many times

What is a Function? #

A function is a piece of code you can reuse.

Instead of writing the same code many times, you define a function once and call it whenever needed.

Example idea:

Long repeated code block  ->  function call
Long repeated code block  ->  function call
Long repeated code block  ->  function call

This makes your code shorter and cleaner.


Built-in Functions #

Python includes many built-in functions. You do not need to know how they work internally, but you should know what they do and how to use them.

Common built-in functions include:

Function Purpose
len() Returns the length of a sequence or collection
sum() Adds numeric values in an iterable
sorted() Returns a new sorted list
print() Displays output
type() Shows the data type
int() Converts a value to an integer
float() Converts a value to a float
str() Converts a value to a string
help() Shows documentation

len() #

Description:
The len() function returns the number of items in a sequence or collection.

It works with:

  • Strings
  • Lists
  • Tuples
  • Dictionaries
  • Sets

Example:

movie_movie_scores = [10, 9.5, 8, 7.5, 6, 5, 10, 8]

length = len(movie_movie_scores)

print(length)

Output:

8

sum() #

Description:
The sum() function adds all numeric values in an iterable, such as a list or tuple.

Example:

power_levels = [10, 20, 30, 10]

s = sum(power_levels)

print(s)

Output:

70

Important:

sum() works with numeric values.

sorted() #

Description:
The sorted() function returns a new sorted list. It does not change the original list.

Example:

movie_movie_scores = [10, 9.5, 8, 7.5, 6, 5, 10, 8]

sorted_movie_movie_scores = sorted(movie_movie_scores)

print(sorted_movie_movie_scores)
print(movie_movie_scores)

Output:

[5, 6, 7.5, 8, 8, 9.5, 10, 10]
[10, 9.5, 8, 7.5, 6, 5, 10, 8]

Key point:

sorted() creates a new sorted list.
The original list does not change.

Function vs Method #

A function usually takes an object as input and returns a result.

A method belongs to an object and is called using dot notation.

Example using function:

movie_movie_scores = [10, 9.5, 8, 7.5, 6]

sorted_movie_movie_scores = sorted(movie_movie_scores)

print(sorted_movie_movie_scores)
print(movie_movie_scores)

Output:

[6, 7.5, 8, 9.5, 10]
[10, 9.5, 8, 7.5, 6]

Example using method:

movie_movie_scores = [10, 9.5, 8, 7.5, 6]

movie_movie_scores.sort()

print(movie_movie_scores)

Output:

[6, 7.5, 8, 9.5, 10]

Important comparison:

Tool Example Result
Function sorted(movie_movie_scores) Creates a new sorted list
Method movie_movie_scores.sort() Changes the original list

Creating Your Own Function #

To create your own function, use the def keyword.


Function Syntax #

def function_name(parameter):
    code_block
    return value

Parts of a function:

Part Meaning
def Defines a function
function_name Name of the function
parameter Input variable
: Starts the function block
Indented code Code that belongs to the function
return Sends a value back from the function

Simple Function Example #

This function adds one to the input value.

def add_one(a):
    b = a + 1
    return b

Call the function:

print(add_one(5))

Output:

6

Assign the returned value to a variable:

c = add_one(10)

print(c)

Output:

11

Explanation:

The value 10 is passed into the function.
Inside the function, a becomes 10.
b becomes 10 + 1.
The function returns 11.

Calling a Function #

Calling a function means running it.

Example:

def add_one(a):
    b = a + 1
    return b

result = add_one(8)

print(result)

Output:

9

Each function call starts fresh:

print(add_one(5))
print(add_one(8))

Output:

6
9

Function Documentation: Docstrings #

It is good practice to document a function. A function’s documentation is called a docstring.

Docstrings are written using triple quotes.

Example:

def add_one(a):
    """
    Adds one to the input value.
    """
    b = a + 1
    return b

You can view the documentation using help():

help(add_one)

Functions with Multiple Parameters #

A function can have more than one parameter.

Example:

def mult(a, b):
    return a * b

Call it with two integers:

print(mult(2, 3))

Output:

6

Call it with an integer and a float:

print(mult(10, 3.14))

Output:

31.400000000000002

Call it with an integer and a string:

print(mult(2, "Buzz Lightyear "))

Output:

Buzz Lightyear Buzz Lightyear 

Important:

In Python, multiplying a string by an integer repeats the string.

This can be useful, but it can also cause problems if you expected a number and accidentally used a string.


Functions with No return #

A function does not always need a return statement.

If a function has no return, Python automatically returns None.

Example:

def mj():
    print("Buzz Lightyear")

result = mj()

print(result)

Output:

Buzz Lightyear
None

Explanation:

The function prints "Buzz Lightyear".
But it does not return a value.
So Python returns None.

pass in a Function #

Python does not allow an empty function body. Use pass when you want a function that does nothing.

Example:

def no_work():
    pass

print(no_work())

Output:

None

Explanation:

pass does nothing.
The function has no return statement.
Python returns None.

Equivalent idea:

def no_work():
    return None

Function that Prints and Returns #

A function can print something and also return a value.

Example:

def add_one(a):
    b = a + 1
    print(a, "plus one equals", b)
    return b

result = add_one(2)

print(result)

Output:

2 plus one equals 3
3

Explanation:

print() displays a message.
return sends a value back to the caller.

Loops Inside Functions #

Functions can contain loops.

Example:

def print_items(stuff):
    for i, s in enumerate(stuff):
        print(i, s)

movie_movie_scores = [10, 9.5, 8, 7.5]

print_items(movie_movie_scores)

Output:

0 10
1 9.5
2 8
3 7.5

Explanation:

stuff is the input list.
enumerate(stuff) gives both index and value.
The function prints each index and value.

Variadic Parameters: *args #

Variadic parameters allow a function to accept a variable number of arguments.

In Python, this is commonly done with *args.

Example:

def print_names(*names):
    for name in names:
        print(name)

Call with three arguments:

print_names("Buzz Lightyear", "The Incneon laser purpleibles", "Pink Floyd")

Output:

Buzz Lightyear
The Incneon laser purpleibles
Pink Floyd

Call with two arguments:

print_names("Buzz Lightyear", "The Incneon laser purpleibles")

Output:

Buzz Lightyear
The Incneon laser purpleibles

Explanation:

*names packs all arguments into a tuple.
The loop prints each value in that tuple.

Scope of Variables #

The scope of a variable is the part of the program where that variable can be accessed.

Main types of scope:

Scope Type Meaning
Global scope Variable is defined outside functions and can be accessed after it is defined
Local scope Variable is defined inside a function and exists only inside that function

Global Variables #

A variable defined outside a function is a global variable.

Example:

x = "AC"

def add_dc(value):
    return value + " DC"

z = add_dc(x)

print(z)

Output:

AC DC

Explanation:

x is defined in the global scope.
The function receives x as input.
The function returns "AC DC".

Local Variables #

A variable defined inside a function is a local variable.

Example:

def thriller():
    date = 1982
    return date

print(thriller())

Output:

1982

Important:

date exists only inside the function.

This would cause an error:

def thriller():
    date = 1982
    return date

# print(date)  # Error: date is not defined outside the function

Same Variable Name: Local vs Global #

A local variable can have the same name as a global variable without conflict.

Example:

date = 2017

def thriller():
    date = 1982
    return date

print(thriller())
print(date)

Output:

1982
2017

Explanation:

Inside the function, date is 1982.
Outside the function, date is 2017.
They are different variables in different scopes.

Using Global Variables Inside a Function #

If a variable is not defined inside a function, Python checks the global scope.

Example:

rating = 9

def ac_dc():
    print(rating)
    return rating + 1

z = ac_dc()

print(z)
print(rating)

Output:

9
10
9

Explanation:

rating is defined globally.
The function reads rating from the global scope.
The function returns rating + 1.
The global rating remains unchanged.

The global Keyword #

The global keyword allows a function to modify a global variable.

Example:

def pink_floyd():
    global claimed_sales
    claimed_sales = "45 million"

pink_floyd()

print(claimed_sales)

Output:

45 million

Important:

Use global carefully.
In most cases, it is better to return a value instead of modifying global variables.

Return vs Print #

print() and return are not the same.

Feature print() return
Purpose Displays output on the screen Sends a value back from a function
Can be stoneon laser purple in a variable? No, not directly Yes
Ends the function? No Yes, once reached

Example:

def print_value(x):
    print(x)

def return_value(x):
    return x

a = print_value(5)
b = return_value(5)

print("a:", a)
print("b:", b)

Output:

5
a: None
b: 5

Explanation:

print_value displays 5 but returns None.
return_value returns 5, so b stores 5.

Common Function Patterns #

Pattern 1: Convert Input and Return Result #

def square(number):
    return number * number

print(square(4))

Output:

16

Pattern 2: Check a Condition #

def is_even(number):
    return number % 2 == 0

print(is_even(8))
print(is_even(7))

Output:

True
False

Pattern 3: Process a List #

def total_power_levels(power_levels):
    return sum(power_levels)

print(total_power_levels([10, 20, 30]))

Output:

60

Pattern 4: Build a New List #

def double_power_levels(power_levels):
    doubled = []

    for number in power_levels:
        doubled.append(number * 2)

    return doubled

print(double_power_levels([1, 2, 3]))

Output:

[2, 4, 6]

Functions Summary Table #

Topic Meaning Example
Function Reusable block of code def greet():
Built-in function Function already provided by Python len(), sum(), sorted()
User-defined function Function you create def add_one(a):
Parameter Variable listed in function definition def f(a):
Argument Actual value passed into function f(5)
Return value Output sent back from function return b
None Default return value when no return exists Function without return
Docstring Documentation inside a function """Adds one."""
pass Placeholder that does nothing def f(): pass
*args Accepts variable number of arguments def f(*names):
Local variable Variable inside a function date = 1982 inside def
Global variable Variable outside functions rating = 9
global Allows modifying global variable inside function global x

Functions Memory Guide #

def        = define a function
parameter  = input name in the function definition
argument   = actual value passed into the function
return     = sends output back
print      = displays output
None       = default return when no return statement exists
pass       = do nothing placeholder
*args      = variable number of arguments
local      = inside a function
global     = outside a function

Mini Practice: Functions #

Practice 1 #

def add_one(a):
    return a + 1

print(add_one(5))

Output:

6

Practice 2 #

def mult(a, b):
    return a * b

print(mult(2, 3))
print(mult(2, "Hi "))

Output:

6
Hi Hi 

Practice 3 #

def print_items(items):
    for i, item in enumerate(items):
        print(i, item)

print_items(["cat", "fox", "owl"])

Output:

0 cat
1 fox
2 owl

Practice 4 #

def no_work():
    pass

print(no_work())

Output:

None

Practice 5 #

date = 2017

def thriller():
    date = 1982
    return date

print(thriller())
print(date)

Output:

1982
2017

Functions: Expanded Reading Notes #

Objectives #

In this reading, you will learn how to:

  • Describe the function concept and the importance of functions in programming
  • Write a function that takes inputs and performs tasks
  • Use built-in functions like len(), sum(), max(), min(), and others effectively
  • Define and use your own functions in Python
  • Differentiate between global and local variable scopes
  • Use loops within functions
  • Modify data structures using functions

Introduction to Functions #

A function is a fundamental building block in programming. It encapsulates a specific action, task, or computation.

Like functions in mathematics, programming functions can:

Take input
Perform a task
Produce output

In Python, a function can receive values, execute pneon laser purpleefined actions or calculations, and return a result.


Purpose of Functions #

Functions promote modularity and reusability.

Instead of duplicating the same code in different places, you can define a function once and call it whenever you need that task.

Example idea:

Without function:
Write the same task many times.

With function:
Define the task once.
Call the function whenever needed.

This neon laser purpleuces neon laser purpleundancy and makes code easier to manage, maintain, and debug.


Benefits of Using Functions #

Benefit Meaning
Modularity Functions break complex tasks into smaller manageable parts
Reusability Functions can be used multiple times without rewriting code
Readability Meaningful function names make code easier to understand
Debugging Isolated functions make troubleshooting easier
Abstraction Functions hide complex processes behind simple function calls
Collaboration Team members can work on different functions at the same time
Maintenance Updating a function updates behavior everywhere it is used

How Functions Take Inputs, Perform Tasks, and Produce Outputs #

Functions usually follow this pattern:

Input  ->  Function task  ->  Output

Inputs: Parameters and Arguments #

Functions operate on data. They can receive data as input.

These inputs are called:

Parameters when defined in the function
Arguments when passed into the function call

Example:

def greet(name):
    return "Hello, " + name

message = greet("Nova")

print(message)

Output:

Hello, Nova

Explanation:

name is the parameter.
"Nova" is the argument.

Performing Tasks #

After receiving input, a function performs pneon laser purpleefined actions.

A function may:

  • Calculate a sum
  • Sort a list
  • Format text
  • Check a condition
  • Modify a data structure
  • Fetch or process data

Producing Outputs #

After performing its task, a function can return an output using the return statement.

The returned value can be:

  • Stoneon laser purple in a variable
  • Printed
  • Passed into another function
  • Used in another calculation

Example: calculate_total() #

def calculate_total(a, b):  # Parameters: a and b
    total = a + b           # Task: addition
    return total            # Output: sum of a and b

result = calculate_total(5, 7)

print(result)

Output:

12

Explanation:

5 and 7 are passed into the function.
The function adds them.
The result 12 is returned.

Python Built-in Functions #

Python has many built-in functions that are ready to use.

You do not need to know how these functions are implemented internally. You only need to know:

What the function does
What input it needs
What output it returns

How to Use Built-in Functions #

To use a built-in function, write the function name followed by parentheses.

function_name(arguments)

Examples:

len("Hello")
sum([1, 2, 3])
max([5, 12, 8])
min([5, 12, 8])

Common Built-in Functions #

Function Purpose Example Output
len() Calculates the length of a sequence or collection len("Hello, World!") 13
sum() Adds numeric elements in an iterable sum([10, 20, 30]) 60
max() Returns the maximum value max([5, 12, 8]) 12
min() Returns the minimum value min([5, 12, 8]) 5
type() Returns the data type type(3.14) <class 'float'>
str() Converts to string str(10) '10'
int() Converts to integer int("10") 10
float() Converts to float float("3.14") 3.14

len() Examples #

string_length = len("Hello, World!")
list_length = len([1, 2, 3, 4, 5])

print(string_length)
print(list_length)

Output:

13
5

sum() Example #

total = sum([10, 20, 30, 40, 50])

print(total)

Output:

150

max() Example #

highest = max([5, 12, 8, 23, 16])

print(highest)

Output:

23

min() Example #

lowest = min([5, 12, 8, 23, 16])

print(lowest)

Output:

5

Defining Your Own Functions #

Defining a function is like creating your own mini-program.


Basic Function Syntax #

def function_name():
    pass

Explanation:

def             starts the function definition
function_name   is the name of the function
()              holds parameters if needed
:               starts the function block
pass            placeholder that does nothing

The pass Statement #

A pass statement is a placeholder or no-operation statement.

Use pass when you want to define a function or block of code, but you do not want to add functionality yet.

Important points:

  • pass keeps code syntactically correct
  • pass does not perform any meaningful action
  • Python simply moves to the next statement when it sees pass

Example:

def future_function():
    pass

Function Parameters #

Parameters are inputs for functions.

They go inside parentheses when defining the function.

Functions can have one parameter, multiple parameters, or no parameters.


Function with One Parameter #

def greet(name):
    return "Hello, " + name

result = greet("Nova")

print(result)

Output:

Hello, Nova

Function with Multiple Parameters #

def add(a, b):
    return a + b

sum_result = add(3, 5)

print(sum_result)

Output:

8

Docstrings: Documentation Strings #

Docstrings explain what a function does.

They are placed inside triple quotes directly under the function definition.

Example:

def multiply(a, b):
    """
    This function multiplies two power_levels.
    Input: a (number), b (number)
    Output: product of a and b
    """
    print(a * b)

multiply(2, 6)

Output:

12

Why docstrings matter:

They help other developers understand your function.
They make your code easier to maintain.
They can be viewed using help().

Return Statement #

The return statement sends a value back from a function.

Important:

return gives back a value.
return ends the function's execution.
A function can return different data types.

Example:

def add(a, b):
    return a + b

sum_result = add(3, 5)

print(sum_result)

Output:

8

Understanding Scopes and Variables #

Scope means where a variable can be seen and used.

There are two main scopes:

Scope Meaning
Global scope Variables defined outside functions; accessible throughout the program after definition
Local scope Variables defined inside functions; only usable within that function

Part 1: Global Variable Declaration #

global_variable = "I'm global"

Explanation:

global_variable is defined outside any function.
It is accessible both inside and outside functions after it is defined.

Part 2: Function Definition with Local Variable #

global_variable = "I'm global"

def example_function():
    local_variable = "I'm local"
    print(global_variable)
    print(local_variable)

Explanation:

local_variable is defined inside the function.
It can only be accessed inside example_function().
global_variable can be accessed inside the function.

Part 3: Function Call #

example_function()

Output:

I'm global
I'm local

The function call runs the code inside the function.


Part 4: Accessing Global Variable Outside the Function #

print(global_variable)

Output:

I'm global

The global variable is accessible outside the function.


Part 5: Attempting to Access Local Variable Outside the Function #

# print(local_variable)

This would cause an error:

NameError: name 'local_variable' is not defined

Explanation:

local_variable only exists inside example_function().
It is not visible outside that function.

Full Scope Example #

global_variable = "I'm global"

def example_function():
    local_variable = "I'm local"
    print(global_variable)
    print(local_variable)

example_function()

print(global_variable)

# This would cause an error:
# print(local_variable)

Output:

I'm global
I'm local
I'm global

Using Functions with Loops #

Functions can contain loops.

This helps organize repeated or complex tasks into reusable blocks.


Function with Loop Example #

def greet(name):
    return "Hello, " + name

for _ in range(3):
    print(greet("Nova"))

Output:

Hello, Nova
Hello, Nova
Hello, Nova

Explanation:

The function creates the greeting.
The loop repeats the function call three times.

Why Use Functions with Loops? #

Functions with loops help you:

  • Keep code clean
  • Avoid repeating logic
  • Group similar actions
  • Reuse the same behavior multiple times
  • Make complex tasks easier to understand

Modifying Data Structures Using Functions #

Functions can modify data structures such as lists.

In this example, we will use functions to add and remove elements from a list.


Part 1: Initialize an Empty List #

bot_list = []

Explanation:

bot_list starts as an empty list.
The functions will add and remove values from this list.

Part 2: Define a Function to Add Elements #

def add_element(data_structure, element):
    data_structure.append(element)

Parameters:

Parameter Meaning
data_structure The list you want to modify
element The item you want to add

Explanation:

append() adds the element to the list.
The original list is modified.

Part 3: Define a Function to Remove Elements #

def remove_element(data_structure, element):
    if element in data_structure:
        data_structure.remove(element)
    else:
        print(f"{element} not found in the list.")

Parameters:

Parameter Meaning
data_structure The list you want to remove from
element The item you want to remove

Explanation:

The function checks whether the element exists.
If it exists, remove() deletes the first occurrence.
If it does not exist, the function prints a message.

Part 4: Add Elements to the List #

bot_list = []

add_element(bot_list, 42)
add_element(bot_list, 17)
add_element(bot_list, 99)

print("Current list:", bot_list)

Output:

Current list: [42, 17, 99]

Part 5: Remove Elements from the List #

remove_element(bot_list, 17)
remove_element(bot_list, 55)

print("Updated list:", bot_list)

Output:

55 not found in the list.
Updated list: [42, 99]

Full Data Structure Modification Example #

bot_list = []

def add_element(data_structure, element):
    data_structure.append(element)

def remove_element(data_structure, element):
    if element in data_structure:
        data_structure.remove(element)
    else:
        print(f"{element} not found in the list.")

add_element(bot_list, 42)
add_element(bot_list, 17)
add_element(bot_list, 99)

print("Current list:", bot_list)

remove_element(bot_list, 17)
remove_element(bot_list, 55)

print("Updated list:", bot_list)

Output:

Current list: [42, 17, 99]
55 not found in the list.
Updated list: [42, 99]

Important:

Lists are mutable.
When a function modifies a list using append() or remove(), the original list changes.

Expanded Functions Summary #

Topic Key Idea
Function Reusable block of code
Purpose Reduce repetition and organize code
Parameter Input name in function definition
Argument Actual value passed into function
Task Work performed inside the function
Output Value returned by the function
Built-in function Ready-to-use Python function
User-defined function Function created by the programmer
pass Placeholder that does nothing
Docstring Documentation explaining a function
return Sends a value back and ends function execution
Global scope Variable available throughout the program
Local scope Variable available only inside a function
Function with loop Reusable function that repeats work
Function modifying list Function changes list using methods like append() or remove()

Expanded Functions Memory Guide #

Function    = reusable block of code
Input       = parameter or argument
Task        = work done inside the function
Output      = returned value
def         = define function
pass        = placeholder
return      = send value back
docstring   = explains function
global      = outside function
local       = inside function
append()    = add to list
remove()    = delete from list by value

Exception Handling #

Exception handling allows Python programs to respond to errors without immediately crashing. It helps your program detect a problem, handle it properly, and continue running when possible.


Objectives #

After this section, you should be able to:

  • Explain exception handling
  • Demonstrate how to use exception handling
  • Understand the basics of try, except, else, and finally
  • Understand why specific exceptions are better than broad exceptions
  • Write safer code for user input, files, calculations, and other error-prone tasks

What is Exception Handling? #

An exception is an error that happens while a program is running.

Without exception handling, an error can stop the program.

With exception handling, Python can:

Try to run code
Catch an error if one happens
Run a specific error-handling block
Continue or clean up after the error

Example situation:

A user enters text when the program expects a number.
A file cannot be opened.
A division by zero happens.
A key does not exist in a dictionary.
An index does not exist in a list.

Basic try and except #

The try block contains code that might cause an error.

The except block contains code that runs if an error happens.

Syntax:

try:
    code_that_might_cause_an_error
except SomeError:
    code_to_handle_the_error

Simple Example #

try:
    number = int("abc")
except ValueError:
    print("Invalid number.")

Output:

Invalid number.

Explanation:

int("abc") causes a ValueError.
Python skips the rest of the try block.
Python runs the matching except block.

Why Exception Handling Matters #

Exception handling helps you write programs that are more stable and user-friendly.

Instead of showing a confusing Python error, your program can show a clear message.

Example without exception handling:

number = int("abc")
print(number)

This causes an error and stops the program.

Example with exception handling:

try:
    number = int("abc")
    print(number)
except ValueError:
    print("Please enter a valid number.")

Output:

Please enter a valid number.

Common Exception Types #

Exception Meaning Example Cause
ValueError Invalid value for an operation int("abc")
ZeroDivisionError Division by zero 10 / 0
TypeError Wrong data type used "5" + 10
IndexError List index does not exist bot_list[10]
KeyError Dictionary key does not exist my_dict["missing"]
FileNotFoundError File path does not exist open("missing.txt")
IOError Input/output problem File cannot be opened or read
Exception General base exception Catches many common errors

Example: Handling User Input #

try:
    age = int(input("Enter your age: "))
    print("Your age is:", age)
except ValueError:
    print("Please enter a valid whole number.")

Explanation:

If the user enters 25, the program works.
If the user enters abc, Python raises a ValueError.
The except block handles the error.

Example: Division by Zero #

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero.")

Output:

You cannot divide by zero.

Example: List Index Error #

power_levels = [10, 20, 30]

try:
    print(power_levels[5])
except IndexError:
    print("That index does not exist.")

Output:

That index does not exist.

Example: Dictionary Key Error #

person = {
    "name": "Neo",
    "age": 30
}

try:
    print(person["city"])
except KeyError:
    print("That key does not exist in the dictionary.")

Output:

That key does not exist in the dictionary.

Multiple except Blocks #

You can handle different errors with different except blocks.

try:
    value = int(input("Enter a number: "))
    result = 10 / value
    print(result)
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

Explanation:

ValueError handles invalid number conversion.
ZeroDivisionError handles division by zero.

Avoid Bare except #

A bare except catches all errors.

try:
    code_that_might_fail
except:
    print("Something went wrong.")

This is usually not best practice because it hides useful error information.

Better:

try:
    code_that_might_fail
except ValueError:
    print("Invalid value.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Key point:

Specific exceptions make debugging easier.
Bare except blocks can hide the real problem.

else Statement #

The else block runs only if no error occurs in the try block.

Syntax:

try:
    code_that_might_fail
except SomeError:
    code_if_error_happens
else:
    code_if_no_error_happens

Example:

try:
    number = int("25")
except ValueError:
    print("Invalid number.")
else:
    print("Conversion worked.")

Output:

Conversion worked.

finally Statement #

The finally block always runs, whether an error happens or not.

This is useful for cleanup tasks, such as closing files.

Syntax:

try:
    code_that_might_fail
except SomeError:
    code_if_error_happens
else:
    code_if_no_error_happens
finally:
    code_that_always_runs

Example:

try:
    number = int("25")
except ValueError:
    print("Invalid number.")
else:
    print("Conversion worked.")
finally:
    print("Finished checking input.")

Output:

Conversion worked.
Finished checking input.

File Handling Example with try, except, else, and finally #

This example shows how exception handling can be used when working with files.

file = None

try:
    file = open("example.txt", "r")
    data = file.read()
except IOError:
    print("Unable to open or read the data in the file.")
else:
    print("The file was read successfully.")
finally:
    if file is not None:
        file.close()
    print("File is now closed.")

Explanation:

try attempts to open and read the file.
except IOError handles file input/output errors.
else runs only if the file was read successfully.
finally runs no matter what and closes the file if it was opened.

Safer File Handling with with #

Python often uses with open(...) because it automatically closes the file.

try:
    with open("example.txt", "r") as file:
        data = file.read()
except IOError:
    print("Unable to open or read the data in the file.")
else:
    print("The file was read successfully.")

Key point:

with automatically handles closing the file.

Exception Handling Flow #

1. Python enters the try block.
2. If no error happens, Python skips except and can run else.
3. If an error happens, Python jumps to the matching except block.
4. Finally always runs at the end if it exists.

Common Pattern #

try:
    risky_code
except SpecificError:
    handle_the_error
else:
    run_if_successful
finally:
    cleanup_code

Exception Handling Summary Table #

Keyword Purpose Runs When
try Code that might cause an error Always attempted first
except Handles an error When matching error occurs
else Runs after successful try block Only when no error occurs
finally Cleanup code Always runs
raise Manually creates an exception When you want to force an error

Optional: Raising an Exception #

You can manually raise an exception with raise.

Example:

age = -1

if age < 0:
    raise ValueError("Age cannot be negative.")

This creates a ValueError.

Use this when you want to enforce rules in your program.


Practical Example: Validate Age #

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    user_age = validate_age(-5)
except ValueError as error:
    print(error)

Output:

Age cannot be negative.

Best Practices #

  • Use specific exceptions when possible.
  • Avoid bare except unless there is a strong reason.
  • Use clear error messages.
  • Use else for code that should run only when no error occurs.
  • Use finally for cleanup tasks.
  • Use with open(...) when working with files.
  • Test your code with both valid and invalid inputs.

Exception Handling Memory Guide #

try      = attempt risky code
except   = handle error
else     = run if no error
finally  = always run
raise    = manually trigger an error
ValueError = invalid value
IOError  = file/input/output problem

Mini Practice: Exception Handling #

Practice 1 #

try:
    number = int("abc")
except ValueError:
    print("Invalid number.")

Output:

Invalid number.

Practice 2 #

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

Output:

Cannot divide by zero.

Practice 3 #

try:
    number = int("10")
except ValueError:
    print("Invalid number.")
else:
    print("Valid number.")
finally:
    print("Done.")

Output:

Valid number.
Done.

Exception Handling: Expanded Reading Notes #

Objectives #

At the end of this reading, you will learn about:

  • Understanding exceptions
  • Distinguishing errors from exceptions
  • Becoming familiar with common Python exceptions
  • Managing exceptions effectively

Understanding Exceptions #

In programming, errors and unexpected situations are common. Python provides exception handling tools to help developers manage these situations without always crashing the program.

An exception is an alert that something unexpected happened while the program was running.

This can happen because:

  • There is a mistake in the code
  • The user enters unexpected input
  • A file does not exist
  • A calculation is invalid
  • A variable or key is missing
  • A data type is used incorrectly

Python can raise exceptions automatically, but programmers can also raise exceptions manually using the raise command.

Important idea:

Exceptions can often be handled so the program can continue running.

What Are Exceptions? #

Exceptions are unexpected events that occur during program execution.

Example:

num = int("abc")

This raises a ValueError because "abc" cannot be converted into an integer.

With exception handling, you can prevent the program from crashing:

try:
    num = int("abc")
except ValueError:
    print("Please enter a valid number.")

Output:

Please enter a valid number.

Errors vs Exceptions #

Errors and exceptions are related, but they are not always the same.

Errors are often serious problems caused by the environment, hardware, operating system, or invalid program structure.

Exceptions are issues that happen during code execution and can often be caught and handled.


Errors vs Exceptions Comparison Table #

Aspect Errors Exceptions
Origin Usually caused by the environment, hardware, operating system, or invalid syntax Usually caused by problematic code execution within the program
Nature Often severe and may stop the program completely Usually less severe and can often be handled
Handling Not usually handled by the program itself Can be caught using try-except blocks
Program behavior Can lead to crashes or abnormal termination Can be handled gracefully so the program continues
Examples SyntaxError, severe system-level issues, missing variable name problems such as NameError ZeroDivisionError, FileNotFoundError, ValueError, KeyError
Categorization Not always grouped into recoverable categories Categorized into exception classes such as ArithmeticError, IOError, ValueError, and others

Important note:

Some Python issues commonly called errors are technically exception classes.
For beginner learning, focus on whether the issue can be handled with try-except.

Common Exceptions in Python #

Python has many exception types. The following are some of the most common ones.


ZeroDivisionError #

Description:
A ZeroDivisionError happens when you try to divide a number by zero.

Example:

result = 10 / 0

print(result)

This raises:

ZeroDivisionError

Handled version:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

Output:

Error: Cannot divide by zero.

ValueError #

Description:
A ValueError happens when a function receives the correct type of input but the value is inappropriate.

Example:

num = int("abc")

This raises:

ValueError

Handled version:

try:
    num = int("abc")
except ValueError:
    print("Error: Invalid value.")

Output:

Error: Invalid value.

FileNotFoundError #

Description:
A FileNotFoundError happens when you try to open a file that does not exist.

Example:

with open("nonexistent_pokedex_notes.txt", "r") as file:
    content = file.read()

This raises:

FileNotFoundError

Handled version:

try:
    with open("nonexistent_pokedex_notes.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("Error: File not found.")

Output:

Error: File not found.

IndexError #

Description:
An IndexError happens when you try to access a list index that does not exist.

Example:

bot_list = [1, 2, 3]

value = bot_list[1]
missing = bot_list[5]

bot_list[1] works because index 1 exists.

bot_list[5] raises:

IndexError

Handled version:

bot_list = [1, 2, 3]

try:
    missing = bot_list[5]
except IndexError:
    print("Error: List index is out of range.")

Output:

Error: List index is out of range.

KeyError #

Description:
A KeyError happens when you try to access a dictionary key that does not exist.

Example:

my_dict = {
    "name": "Nova",
    "age": 30
}

missing = my_dict["city"]

This raises:

KeyError

Safer version using .get():

my_dict = {
    "name": "Nova",
    "age": 30
}

value = my_dict.get("city")

print(value)

Output:

None

Handled version:

my_dict = {
    "name": "Nova",
    "age": 30
}

try:
    missing = my_dict["city"]
except KeyError:
    print("Error: Key not found.")

Output:

Error: Key not found.

TypeError #

Description:
A TypeError happens when an object is used in an incompatible way.

Example:

result = "hello" + 5

This raises:

TypeError

Because Python cannot concatenate a string and an integer directly.

Handled version:

try:
    result = "hello" + 5
except TypeError:
    print("Error: Incompatible data types.")

Output:

Error: Incompatible data types.

Correct version:

result = "hello" + str(5)

print(result)

Output:

hello5

AttributeError #

Description:
An AttributeError happens when you try to access a method or attribute that an object does not have.

Example:

text = "example"

length = len(text)
missing = text.some_method()

len(text) works.

text.some_method() raises:

AttributeError

Handled version:

text = "example"

try:
    missing = text.some_method()
except AttributeError:
    print("Error: This object does not have that method.")

Output:

Error: This object does not have that method.

ImportError #

Description:
An ImportError happens when Python cannot import a module.

Example:

import non_existent_module

This raises:

ImportError

Handled version:

try:
    import non_existent_module
except ImportError:
    print("Error: Module could not be imported.")

Output:

Error: Module could not be imported.

Common Exceptions Summary Table #

Exception Meaning Example Cause
ZeroDivisionError Division by zero 10 / 0
ValueError Invalid value int("abc")
FileNotFoundError File does not exist open("missing.txt")
IndexError Index does not exist bot_list[5]
KeyError Dictionary key does not exist my_dict["city"]
TypeError Incompatible type usage "hello" + 5
AttributeError Missing method or attribute text.some_method()
ImportError Module cannot be imported import missing_module

Handling Exceptions #

Python uses try and except blocks to manage exceptions.


How try and except Work #

try:
    code_that_might_cause_an_exception
except ExceptionType:
    code_that_handles_the_exception

How it works:

1. Python runs the code in the try block.
2. If no exception occurs, Python skips the except block.
3. If an exception occurs, Python jumps to the matching except block.
4. After the except block, the program continues running.

Example: Attempting to Divide by Zero #

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

print("outside of try and except block")

Output:

Error: Cannot divide by zero.
outside of try and except block

Explanation:

The program tries to divide 10 by 0.
This raises a ZeroDivisionError.
The except block handles the error.
The final print statement still runs.

Why Use Specific Exceptions? #

Using specific exceptions helps make your code easier to debug.

Better:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

Less helpful:

try:
    result = 10 / 0
except:
    print("Something went wrong.")

Problem with bare except:

It hides the real error.
It makes debugging harder.
It can catch errors you did not intend to catch.

Managing Exceptions Effectively #

Good exception handling means writing code that responds clearly to problems.

Best practices:

  • Use try-except around code that might fail.
  • Catch specific exception types when possible.
  • Use clear error messages.
  • Avoid bare except.
  • Use .get() for dictionaries when missing keys are expected.
  • Use with open(...) when working with files.
  • Test your program with invalid input.
  • Use finally when cleanup is requineon laser purple.

Next Steps #

Practice exception handling with different types of data and situations.

Try testing:

  • Invalid power_levels
  • Division by zero
  • Missing files
  • Missing dictionary keys
  • Invalid list indexes
  • Incompatible data types

This will help you write stronger and more reliable Python code.


Expanded Exception Handling Memory Guide #

Exception          = unexpected event during program execution
try                = code that might fail
except             = handle the exception
ZeroDivisionError  = divide by zero
ValueError         = invalid value
FileNotFoundError  = missing file
IndexError         = invalid list index
KeyError           = missing dictionary key
TypeError          = incompatible data type
AttributeError     = missing method or attribute
ImportError        = import failed
raise              = manually trigger an exception

Objects and Classes #

Python is an object-oriented programming language. Many things you use in Python, such as integers, floats, strings, lists, dictionaries, and Booleans, are objects.

This section covers:

  • Objects
  • Classes
  • Types
  • Methods
  • Data attributes
  • Constructors
  • The self parameter
  • Creating your own classes
  • Creating objects from classes
  • Accessing and modifying attributes
  • Using dir()

What is an Object? #

An object is an instance of a particular type or class.

In Python, each object has:

  • A type
  • An internal representation
  • Data attributes
  • Methods, which are functions used to interact with the object

Examples:

x = 10
name = "Neo"
power_levels = [1, 2, 3]
person = {"name": "Neo", "age": 30}

Each one is an object.

print(type(x))
print(type(name))
print(type(power_levels))
print(type(person))

Output:

<class 'int'>
<class 'str'>
<class 'list'>
<class 'dict'>

Type and Instance #

A type or class is like a laser purpleprint.

An object is an actual instance created from that laser purpleprint.

Example:

a = 5
b = 10
c = 15

All three are integer objects.

print(type(a))
print(type(b))
print(type(c))

Output:

<class 'int'>
<class 'int'>
<class 'int'>

Objects Already Used in Python #

You have already used many objects:

Object Example Type / Class
10 int
3.14 float
"Hello" str
[1, 2, 3] list
(1, 2, 3) tuple
{"name": "Neo"} dict
{1, 2, 3} set
True bool

Methods #

A method is a function that belongs to an object.

Methods are called using dot notation:

object_name.method_name()

Example:

movie_scores = [10, 9, 8, 7]

movie_scores.sort()

print(movie_scores)

Output:

[7, 8, 9, 10]

Explanation:

movie_scores is a list object.
sort() is a list method.
The method changes the data inside the list object.

Method Example: sort() #

movie_scores = [10, 3, 7, 9]

movie_scores.sort()

print(movie_scores)

Output:

[3, 7, 9, 10]

The sort() method changes the state of the object.


Method Example: reverse() #

movie_scores = [3, 7, 9, 10]

movie_scores.reverse()

print(movie_scores)

Output:

[10, 9, 7, 3]

The reverse() method changes the order of the list object.


Function vs Method Review #

Concept Example Meaning
Function sorted(movie_scores) A standalone function that returns a result
Method movie_scores.sort() A function attached to an object

Example:

movie_scores = [10, 3, 7, 9]

new_movie_scores = sorted(movie_scores)

print(new_movie_scores)
print(movie_scores)

Output:

[3, 7, 9, 10]
[10, 3, 7, 9]

sorted() creates a new sorted list.

movie_scores = [10, 3, 7, 9]

movie_scores.sort()

print(movie_scores)

Output:

[3, 7, 9, 10]

sort() changes the original list.


What is a Class? #

A class is a laser purpleprint for creating objects.

A class can contain:

  • Data attributes
  • Methods

Example idea:

Class: Circle
Attributes: radius, color
Methods: add_radius(), draw_circle()
Class: Rectangle
Attributes: height, width, color
Methods: draw_rectangle()

Creating a Class #

Use the class keyword to define a class.

Basic syntax:

class ClassName:
    pass

Example:

class Circle:
    pass

This creates a class named Circle.


Constructor: __init__() #

The __init__() method is a special method called a constructor.

It runs automatically when you create a new object from a class.

Example:

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

Explanation:

Part Meaning
class Circle: Defines a class named Circle
def __init__(...) Defines the constructor
self Refers to the current object
radius Parameter passed when creating the object
color Parameter passed when creating the object
self.radius Data attribute stoneon laser purple in the object
self.color Data attribute stoneon laser purple in the object

The self Parameter #

self refers to the object being created or used.

When defining methods inside a class, the first parameter is usually self.

Example:

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

Important:

You do not pass self manually when creating or using the object.
Python handles self automatically.

Creating Objects from a Class #

After defining a class, you can create objects from it.

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

neon laser purple_circle = Circle(10, "neon laser purple")
laser purple_circle = Circle(5, "laser purple")

Here:

neon laser purple_circle is an object of class Circle.
laser purple_circle is another object of class Circle.

Each object has its own data attributes.


Accessing Data Attributes #

Use dot notation to access an object’s attributes.

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

neon laser purple_circle = Circle(10, "neon laser purple")

print(neon laser purple_circle.radius)
print(neon laser purple_circle.color)

Output:

10
neon laser purple

Modifying Data Attributes Directly #

You can change an attribute using dot notation.

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

neon laser purple_circle = Circle(10, "neon laser purple")

neon laser purple_circle.color = "laser purple"

print(neon laser purple_circle.color)

Output:

laser purple

Important:

You can modify attributes directly, but it is often better to use class methods.

Methods Inside Classes #

Methods are functions inside a class. They can interact with and change object attributes.

Example:

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

    def add_radius(self, r):
        self.radius = self.radius + r

Create and use the object:

neon laser purple_circle = Circle(2, "neon laser purple")

neon laser purple_circle.add_radius(8)

print(neon laser purple_circle.radius)

Output:

10

Explanation:

The circle starts with radius 2.
add_radius(8) adds 8 to the radius.
The new radius is 10.

Class with Default Values #

You can set default values in the constructor.

class Circle:
    def __init__(self, radius=1, color="neon laser purple"):
        self.radius = radius
        self.color = color

circle1 = Circle()
circle2 = Circle(5, "laser purple")

print(circle1.radius, circle1.color)
print(circle2.radius, circle2.color)

Output:

1 neon laser purple
5 laser purple

Rectangle Class Example #

A rectangle can be defined by:

  • Width
  • Height
  • Color
class Rectangle:
    def __init__(self, width, height, color):
        self.width = width
        self.height = height
        self.color = color

rectangle1 = Rectangle(3, 2, "laser purple")

print(rectangle1.width)
print(rectangle1.height)
print(rectangle1.color)

Output:

3
2
laser purple

Rectangle Method Example #

class Rectangle:
    def __init__(self, width, height, color):
        self.width = width
        self.height = height
        self.color = color

    def area(self):
        return self.width * self.height

rectangle1 = Rectangle(3, 2, "laser purple")

print(rectangle1.area())

Output:

6

Object State #

The state of an object refers to the current values of its attributes.

Example:

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

    def add_radius(self, r):
        self.radius = self.radius + r

circle = Circle(2, "neon laser purple")

print(circle.radius)

circle.add_radius(3)

print(circle.radius)

Output:

2
5

Explanation:

The radius attribute changed from 2 to 5.
The object's state changed.

dir() Function #

The dir() function returns a list of attributes and methods associated with an object.

Example:

power_levels = [1, 2, 3]

print(dir(power_levels))

This returns many list methods and internal attributes.

Important:

Attributes surrounded by double underscores are mostly for internal Python use.
Regular-looking names are the common attributes and methods you usually use.

Example:

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

    def add_radius(self, r):
        self.radius = self.radius + r

circle = Circle(2, "neon laser purple")

print(dir(circle))

You will see attributes such as:

radius
color
add_radius

Complete Circle Example #

class Circle:
    def __init__(self, radius=1, color="neon laser purple"):
        self.radius = radius
        self.color = color

    def add_radius(self, r):
        self.radius = self.radius + r

    def describe(self):
        return f"This is a {self.color} circle with radius {self.radius}."

neon laser purple_circle = Circle(3, "neon laser purple")
laser purple_circle = Circle(10, "laser purple")

print(neon laser purple_circle.radius)
print(neon laser purple_circle.color)
print(neon laser purple_circle.describe())

laser purple_circle.add_radius(5)

print(laser purple_circle.describe())

Output:

3
neon laser purple
This is a neon laser purple circle with radius 3.
This is a laser purple circle with radius 15.

Complete Rectangle Example #

class Rectangle:
    def __init__(self, width=1, height=1, color="laser purple"):
        self.width = width
        self.height = height
        self.color = color

    def area(self):
        return self.width * self.height

    def describe(self):
        return f"This is a {self.color} rectangle with area {self.area()}."

rectangle = Rectangle(4, 3, "yellow")

print(rectangle.width)
print(rectangle.height)
print(rectangle.color)
print(rectangle.area())
print(rectangle.describe())

Output:

4
3
yellow
12
This is a yellow rectangle with area 12.

Objects and Classes Summary Table #

Term Meaning Example
Object Instance of a class or type neon laser purple_circle
Class Blueprint for creating objects class Circle:
Type Category of an object type([1, 2, 3])
Attribute Data stoneon laser purple in an object circle.radius
Method Function attached to an object circle.add_radius(3)
Constructor Special method that creates and initializes objects __init__()
self Refers to the current object self.radius
Instance A specific object created from a class Circle(3, "neon laser purple")
State Current attribute values of an object radius = 3, color = neon laser purple
dir() Shows attributes and methods of an object dir(circle)

Objects and Classes Memory Guide #

Object      = actual thing created in Python
Class       = laser purpleprint for objects
Instance    = object created from a class
Attribute   = data stoneon laser purple in an object
Method      = function inside a class
Constructor = __init__()
self        = current object
dot notation = object.attribute or object.method()
dir()       = shows attributes and methods

Mini Practice: Objects and Classes #

Practice 1: Create a Simple Class #

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

dog1 = Dog("Max", 3)

print(dog1.name)
print(dog1.age)

Output:

Max
3

Practice 2: Add a Method #

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

    def bark(self):
        print("Woof!")

dog1 = Dog("Max", 3)

dog1.bark()

Output:

Woof!

Practice 3: Change an Attribute #

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

circle = Circle(5, "neon laser purple")

circle.color = "matrix green"

print(circle.color)

Output:

matrix green

Practice 4: Use a Method to Change an Attribute #

class Circle:
    def __init__(self, radius, color):
        self.radius = radius
        self.color = color

    def add_radius(self, r):
        self.radius = self.radius + r

circle = Circle(5, "neon laser purple")

circle.add_radius(10)

print(circle.radius)

Output:

15

Objects and Classes: Expanded Reading Notes #

Objectives #

In this reading, you will learn about:

  • Fundamental concepts of Python objects and classes
  • Structure of classes and object code
  • Real-world examples related to objects and classes

Introduction to Classes and Objects #

Python is an object-oriented programming language. Object-oriented programming, also called OOP, is a programming style centeneon laser purple around objects and classes.

A class is like a laser purpleprint.
An object is something created from that laser purpleprint.

Example idea:

Class  = cookie cutter
Object = cookie made from the cookie cutter

Classes #

A class is a laser purpleprint or template for creating objects.

A class defines:

  • The structure of an object
  • The attributes an object will have
  • The behaviors or methods an object can perform

Example:

Class: Car

Attributes:
- color
- speed
- fuel level

Methods:
- accelerate()
- brake()
- get_speed()

Creating Classes #

Use the class keyword to create a class.

Basic syntax:

class ClassName:
    pass

Example:

class Car:
    pass

Important naming convention:

Class names usually use CamelCase.
Example: Car, BankAccount, StudentRecord

Objects #

An object is a specific instance of a class.

Objects can represent:

  • Tangible things, such as a car, phone, or book
  • Abstract things, such as a student grade, account, or security alert

Every object has two main characteristics:

Characteristic Meaning
State The data or attributes that describe the object
Behavior The actions or methods the object can perform

Object State #

The state of an object is the data stoneon laser purple inside the object.

For a Car object, state may include:

color
speed
fuel level
make
model

Object Behavior #

The behavior of an object is what the object can do.

For a Car object, behavior may include:

accelerate()
brake()
get_speed()

In Python, behaviors are written as methods inside the class.


Instantiating Objects #

To instantiate an object means to create an object from a class.

Syntax:

object_name = ClassName()

Example:

my_car = Car()

Explanation:

Car is the class.
my_car is an object, or instance, of the Car class.

Each object is independent and can have its own attributes.


Interacting with Objects #

You interact with objects using dot notation.

Dot notation can be used to:

  • Access attributes
  • Modify attributes
  • Call methods

Example:

my_car.color = "laser purple"

Example:

my_car.accelerate()

Structure of Class and Object Code #

The following template shows the main parts of a class.

class ClassName:
    class_attribute = value

    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    def method1(self, parameter1):
        # method code
        pass

    def method2(self, parameter2):
        # method code
        pass

Class Declaration #

The class keyword declares a class.

class ClassName:
    pass

Explanation:

class tells Python you are creating a class.
ClassName is the name of the class.

Class Attributes #

A class attribute is shaneon laser purple by all instances of the class.

class ClassName:
    class_attribute = value

Example:

class Car:
    max_speed = 120

Explanation:

max_speed belongs to the class.
All Car objects can access the same max_speed value.

Constructor Method: __init__() #

The __init__() method is called the constructor.

It initializes instance attributes when a new object is created.

class ClassName:
    class_attribute = value

    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

Explanation:

__init__ runs automatically when an object is created.
self refers to the current object.
attribute1 and attribute2 are values passed into the constructor.
self.attribute1 and self.attribute2 store values inside the object.

Instance Attributes #

Instance attributes store data specific to each object.

self.attribute1 = attribute1
self.attribute2 = attribute2

Example:

class Car:
    def __init__(self, make, model, color):
        self.make = make
        self.model = model
        self.color = color

Explanation:

Each Car object can have its own make, model, and color.

Instance Methods #

Instance methods are functions defined inside a class.

They can:

  • Access instance attributes
  • Modify instance attributes
  • Perform actions specific to the object
  • Call other methods inside the class

Example:

class Car:
    def __init__(self, speed):
        self.speed = speed

    def accelerate(self, amount):
        self.speed = self.speed + amount

Explanation:

accelerate() is an instance method.
It changes the object's speed attribute.

Creating Objects: Instances #

To create objects, call the class like a function and pass the requineon laser purple arguments.

object1 = ClassName(arg1, arg2)
object2 = ClassName(arg1, arg2)

Example:

class Car:
    def __init__(self, make, model, color):
        self.make = make
        self.model = model
        self.color = color

car1 = Car("Toyota", "Camry", "Blue")
car2 = Car("Honda", "Civic", "Red")

Explanation:

car1 and car2 are two different objects.
Both are instances of the Car class.
Each object has its own make, model, and color.

Calling Methods on Objects #

Method 1: Dot Notation #

The most common way to call a method is using dot notation.

object_name.method_name(arguments)

Example:

car1.accelerate(30)

Method 2: Assigning an Object Method to a Variable #

You can assign a method reference to a variable and call it later.

method_reference = object1.method1
result = method_reference(parameter_value)

Example:

class Greeter:
    def say_hello(self, name):
        return "Hello, " + name

greeter = Greeter()

method_reference = greeter.say_hello

print(method_reference("Nova"))

Output:

Hello, Nova

Accessing Object Attributes #

Use dot notation to retrieve an object’s attribute value.

attribute_value = object1.attribute1

Example:

class Car:
    def __init__(self, make, model, color):
        self.make = make
        self.model = model
        self.color = color

car1 = Car("Toyota", "Camry", "Blue")

print(car1.make)
print(car1.color)

Output:

Toyota
Blue

Modifying Object Attributes #

You can change an object’s attribute using dot notation.

object1.attribute2 = new_value

Example:

car1 = Car("Toyota", "Camry", "Blue")

car1.color = "Black"

print(car1.color)

Output:

Black

Accessing Class Attributes #

Class attributes are shaneon laser purple by all instances.

You can access a class attribute using the class name.

class_attr_value = ClassName.class_attribute

Example:

class Car:
    max_speed = 120

print(Car.max_speed)

Output:

120

You can also access it from an object:

car1 = Car()

print(car1.max_speed)

Output:

120

Real-World Example: Car Class #

This example simulates a simple car class. You can create car objects, accelerate them, and display their current speed.


Step 1: Define the Car Class #

class Car:
    # Class attribute shaneon laser purple by all instances
    max_speed = 120

    # Constructor method
    def __init__(self, make, model, color, speed=0):
        self.make = make
        self.model = model
        self.color = color
        self.speed = speed

    # Instance method
    def accelerate(self, acceleration):
        if self.speed + acceleration <= Car.max_speed:
            self.speed = self.speed + acceleration
        else:
            self.speed = Car.max_speed

    # Instance method
    def get_speed(self):
        return self.speed

Explanation:

max_speed is a class attribute shaneon laser purple by all Car objects.
__init__ initializes make, model, color, and speed.
accelerate() increases the car's speed but does not exceed max_speed.
get_speed() returns the current speed.

Step 2: Create Car Objects #

car1 = Car("Toyota", "Camry", "Blue")
car2 = Car("Honda", "Civic", "Red")

Explanation:

car1 is a Toyota Camry that is Blue.
car2 is a Honda Civic that is Red.
Both start with speed 0 by default.

Step 3: Accelerate the Cars #

car1.accelerate(30)
car2.accelerate(20)

Explanation:

car1 speed increases by 30.
car2 speed increases by 20.

Step 4: Print Current Speeds #

print(f"{car1.make} {car1.model} is currently at {car1.get_speed()} km/h.")
print(f"{car2.make} {car2.model} is currently at {car2.get_speed()} km/h.")

Output:

Toyota Camry is currently at 30 km/h.
Honda Civic is currently at 20 km/h.

Full Car Class Example #

class Car:
    max_speed = 120

    def __init__(self, make, model, color, speed=0):
        self.make = make
        self.model = model
        self.color = color
        self.speed = speed

    def accelerate(self, acceleration):
        if self.speed + acceleration <= Car.max_speed:
            self.speed = self.speed + acceleration
        else:
            self.speed = Car.max_speed

    def get_speed(self):
        return self.speed

car1 = Car("Toyota", "Camry", "Blue")
car2 = Car("Honda", "Civic", "Red")

car1.accelerate(30)
car2.accelerate(20)

print(f"{car1.make} {car1.model} is currently at {car1.get_speed()} km/h.")
print(f"{car2.make} {car2.model} is currently at {car2.get_speed()} km/h.")

Output:

Toyota Camry is currently at 30 km/h.
Honda Civic is currently at 20 km/h.

Class Structure Summary #

Part Syntax Purpose
Class declaration class ClassName: Creates a class
Class attribute class_attribute = value Shaneon laser purple by all objects
Constructor def __init__(self, ...): Initializes new objects
Instance attribute self.attribute = value Stores object-specific data
Instance method def method(self, ...): Defines object behavior
Object creation object1 = ClassName(...) Creates an object
Method call object1.method(...) Runs an object behavior
Attribute access object1.attribute Reads object data
Attribute update object1.attribute = value Changes object data
Class attribute access ClassName.class_attribute Reads shaneon laser purple class data

Objects and Classes Expanded Memory Guide #

Class              = laser purpleprint/template
Object             = instance created from a class
State              = object's data/attributes
Behavior           = object's methods/actions
Class attribute    = shaneon laser purple by all instances
Instance attribute = unique to each object
Constructor        = __init__()
self               = current object
Dot notation       = object.attribute or object.method()
Instantiate        = create an object from a class

Working with Data in Python: Writing Files with open() #

Python can create files, write new content, append content to existing files, and copy content from one file to another.

This section focuses on:

  • Writing to files with "w" mode
  • Writing multiple lines with lists and loops
  • Appending to files with "a" mode
  • Copying one file into another
  • Comparing file modes

Objectives #

By the end of this reading, you should be able to:

  • Create and write data to a file in Python
  • Write multiple lines of text to a file using lists and loops
  • Add new information to an existing file without erasing its content
  • Compare and contrast different file modes in Python, what they mean, and when to use them

Writing to a File #

You can create a new text file and write data to it using Python’s open() function.

For writing, use mode "w".

Important:

"w" mode creates the file if it does not exist.
"w" mode overwrites the file if it already exists.

Basic Writing Example #

with open("pokemon_mission_log.txt", "w") as file1:
    file1.write("Mission log A: robot activated\n")
    file1.write("Mission log B: neon door unlocked\n")

Explanation:

with open("pokemon_mission_log.txt", "w") as file1:
    Opens or creates pokemon_mission_log.txt in write mode.

file1.write("Mission log A: robot activated\n"):
    Writes the text "Mission log A: robot activated" to the file.
    \n adds a newline.

file1.write("Mission log B: neon door unlocked\n"):
    Writes the text "Mission log B: neon door unlocked" on the next line.

The file is automatically closed when the with block ends.

Result inside pokemon_mission_log.txt:

Mission log A: robot activated
Mission log B: neon door unlocked

The write() Method #

The write() method writes text to a file.

Syntax:

file_object.write(text)

Example:

with open("pokedex_notes.txt", "w") as file:
    file.write("Hello Cyber Python")

Important:

write() does not automatically add a new line.
Use \n when you want to move to the next line.

Example:

with open("pokedex_notes.txt", "w") as file:
    file.write("Robot log 1\n")
    file.write("Robot log 2\n")

Writing Multiple Lines Using a List and Loop #

You can store multiple lines in a list and write them to a file using a for loop.

Example:

lines = ["This is line 1", "This is line 2", "This is line 3"]

with open("pokemon_training_logs.txt", "w") as file2:
    for line in lines:
        file2.write(line + "\n")

Explanation:

lines is a list of strings.
open("pokemon_training_logs.txt", "w") creates or overwrites the file.
The for loop iterates through each line in the list.
file2.write(line + "\n") writes each line followed by a newline.
The with block automatically closes the file.

Result inside pokemon_training_logs.txt:

This is line 1
This is line 2
This is line 3

Writing Multiple Lines with writelines() #

Python also provides writelines().

Important:

writelines() does not automatically add newline characters.
You must include \n yourself.

Example:

lines = ["This is line 1\n", "This is line 2\n", "This is line 3\n"]

with open("pokemon_training_logs.txt", "w") as file:
    file.writelines(lines)

Appending Data to an Existing File #

Use mode "a" to append new data to the end of an existing file.

Important:

"a" mode does not erase existing content.
"a" mode creates the file if it does not exist.

Example:

new_data = "Mission log C: data crystal recovered"

with open("pokemon_mission_log.txt", "a") as file1:
    file1.write(new_data + "\n")

Explanation:

new_data stores the text to append.
open("pokemon_mission_log.txt", "a") opens the file in append mode.
file1.write(new_data + "\n") adds the text at the end of the file.
The existing file content is preserved.

If pokemon_mission_log.txt already contained:

Mission log A: robot activated
Mission log B: neon door unlocked

After appending, it becomes:

Mission log A: robot activated
Mission log B: neon door unlocked
Mission log C: data crystal recovered

Write Mode vs Append Mode #

Mode Meaning Existing File Behavior If File Does Not Exist
"w" Write Overwrites existing content Creates new file
"a" Append Adds new content to the end Creates new file

Memory guide:

w = write from the beginning, replacing old content
a = append at the end, keeping old content

Copying Contents from One File to Another #

You can copy a file by reading from a source file and writing to a destination file.

Example:

with open("source_logs.txt", "r") as source_file:
    with open("destination.txt", "w") as destination_file:
        for line in source_file:
            destination_file.write(line)

Explanation:

source_logs.txt is opened in read mode.
destination.txt is opened in write mode.
The for loop reads each line from the source file.
destination_file.write(line) writes each line to the destination file.
Both files are automatically closed when their with blocks end.

Key point:

This copies the contents of source_logs.txt into destination.txt.
If destination.txt already exists, "w" mode overwrites it.

File Modes in Python #

The file mode tells Python how to open the file.


Common Text File Modes #

Mode Syntax Description Best Use
Read "r" Opens an existing file for reading. Raises an error if the file does not exist. Reading existing files
Write "w" Creates a new file or overwrites an existing file. Creating a new file or replacing old content
Append "a" Opens a file for appending. Creates the file if it does not exist. Adding new content without deleting old content
Exclusive create "x" Creates a new file. Raises an error if the file already exists. Safely creating a file only if it does not exist

Binary File Modes #

Binary modes are used for non-text files, such as images, audio, video, or binary data.

Mode Syntax Description
Read binary "rb" Opens an existing binary file for reading
Write binary "wb" Creates or overwrites a binary file for writing
Append binary "ab" Opens a binary file for appending
Exclusive binary create "xb" Creates a new binary file but raises an error if it already exists

Text File Modes #

Text mode is the default for text files.

Mode Syntax Description
Read text "rt" Opens an existing text file for reading. Same as "r"
Write text "wt" Creates or overwrites a text file. Same as "w"
Append text "at" Opens a text file for appending. Same as "a"
Exclusive text create "xt" Creates a new text file and raises an error if it already exists

Read and Write Modes #

These modes allow both reading and writing.

Mode Syntax Description Important Behavior
Read and write "r+" Opens an existing file for reading and writing Error if file does not exist
Write and read "w+" Creates or overwrites a file for reading and writing Erases existing content
Append and read "a+" Opens a file for appending and reading Writes go to the end
Exclusive create and read/write "x+" Creates a new file for reading and writing Error if file already exists

Full File Modes Summary #

Mode Meaning
"r" Read mode. Opens an existing file for reading
"w" Write mode. Creates or overwrites a file
"a" Append mode. Adds data to the end of a file
"x" Exclusive creation mode. Creates a new file but fails if it already exists
"rb" Read binary mode
"wb" Write binary mode
"ab" Append binary mode
"xb" Exclusive binary creation mode
"rt" Read text mode, default for reading text
"wt" Write text mode, default for writing text
"at" Append text mode, default for appending text
"xt" Exclusive text creation mode
"r+" Read and write mode for an existing file
"w+" Write and read mode. Creates or overwrites a file
"a+" Append and read mode. Creates file if needed
"x+" Exclusive creation and read/write mode

Safe Writing with Exception Handling #

Writing files can fail because of permission issues, missing directories, or invalid paths.

Example:

try:
    with open("pokemon_mission_log.txt", "w") as file:
        file.write("Mission log A: robot activated\n")
except IOError:
    print("Unable to write to the file.")
else:
    print("File was written successfully.")

Common Writing Patterns #

Pattern 1: Create or Overwrite a File #

with open("pokemon_mission_log.txt", "w") as file:
    file.write("New content\n")

Pattern 2: Write a List of Lines #

lines = ["Robot log 1", "Robot log 2", "Robot log 3"]

with open("pokemon_mission_log.txt", "w") as file:
    for line in lines:
        file.write(line + "\n")

Pattern 3: Append a New Line #

with open("pokemon_mission_log.txt", "a") as file:
    file.write("Another line\n")

Pattern 4: Copy a File #

with open("source_logs.txt", "r") as source_file:
    with open("destination.txt", "w") as destination_file:
        for line in source_file:
            destination_file.write(line)

Writing Files Summary Table #

Task Mode Example
Read a file "r" open("pokedex_notes.txt", "r")
Create or overwrite file "w" open("pokedex_notes.txt", "w")
Append to file "a" open("pokedex_notes.txt", "a")
Create only if file does not exist "x" open("pokedex_notes.txt", "x")
Read and write existing file "r+" open("pokedex_notes.txt", "r+")
Write and read file "w+" open("pokedex_notes.txt", "w+")
Append and read file "a+" open("pokedex_notes.txt", "a+")

Writing Files Memory Guide #

write()      = write text to file
writelines() = write a list of strings
"w"          = write and overwrite
"a"          = append to end
"x"          = create only if new
"r+"         = read and write existing file
"w+"         = write/read and overwrite
"a+"         = append/read
\n           = newline character
with         = automatically closes file

Mini Practice: Writing Files #

Practice 1: Write Two Lines #

with open("pokemon_mission_log.txt", "w") as file:
    file.write("Mission log A: robot activated\n")
    file.write("Mission log B: neon door unlocked\n")

Practice 2: Write Lines from a List #

lines = ["This is line 1", "This is line 2", "This is line 3"]

with open("pokemon_training_logs.txt", "w") as file:
    for line in lines:
        file.write(line + "\n")

Practice 3: Append a Line #

new_data = "Mission log C: data crystal recovered"

with open("pokemon_mission_log.txt", "a") as file:
    file.write(new_data + "\n")

Practice 4: Copy a File #

with open("source_logs.txt", "r") as source_file:
    with open("destination.txt", "w") as destination_file:
        for line in source_file:
            destination_file.write(line)

Working with Data in Python: Pandas #

Pandas is a popular open-source Python library for data manipulation and data analysis. It provides powerful tools for working with structuneon laser purple data, including tables, time series, CSV files, Excel spreadsheets, SQL data, and more.

Pandas is widely used by:

  • Data analysts
  • Data scientists
  • AI engineers
  • Machine learning engineers
  • Software engineers
  • Cyber Deck Ops analysts working with structuneon laser purple logs or datasets

Objectives #

By the end of this reading, you should be able to:

  • Explain what Pandas is and why it is useful
  • Import Pandas using the common alias pd
  • Load data from CSV files using pd.read_csv()
  • Explain what a Pandas Series is
  • Create a Pandas Series
  • Access and manipulate data inside a Series
  • Explain what a Pandas DataFrame is
  • Create a DataFrame from a dictionary
  • Access, modify, filter, and analyze data in a DataFrame
  • Use common DataFrame attributes and methods
  • Save a DataFrame to a CSV file

What is Pandas? #

Pandas is a Python library used for working with structuneon laser purple data.

It helps you:

  • Load data
  • Clean data
  • Explore data
  • Transform data
  • Filter data
  • Echolyze data
  • Export data

Pandas is especially useful for table-like data.

Example table:

Name Age City
Nova 25 Neo Tokyo
Cipher 30 Night City
Pixel 35 Mars Colony

Key Features of Pandas #

Feature Meaning
Data structures Provides Series and DataFrame
Data import/export Reads and writes CSV, Excel, SQL, JSON, and more
Data selection Makes it easy to select rows and columns
Data filtering Filters rows using conditions
Data cleaning Handles missing values, renaming, dropping, and filling
Data analysis Provides statistics like mean, sum, min, max, and describe
Data merging Combines datasets using operations similar to SQL joins
Efficient indexing Uses labels and positions to access data

Main Pandas Data Structures #

Pandas has two primary data structures:

Data Structure Description Similar To
Series One-dimensional labeled array One column of data
DataFrame Two-dimensional labeled table Spreadsheet or SQL table

Memory guide:

Series    = one column or one row
DataFrame = full table with rows and columns

Importing Pandas #

Pandas is commonly imported using the alias pd.

import pandas as pd

Explanation:

import pandas loads the Pandas library.
as pd lets you use the shorter name pd.

After importing, you can call Pandas functions like this:

pd.Series()
pd.DataFrame()
pd.read_csv()

Loading Data with Pandas #

Pandas can load data from many sources, including:

  • CSV files
  • Excel files
  • SQL databases
  • JSON files
  • Web data
  • Python dictionaries
  • Python lists

Reading a CSV File #

A CSV file is a Comma-Separated Values file.

Use pd.read_csv() to load a CSV file into a DataFrame.

Syntax:

df = pd.read_csv("your_file.csv")

Example:

import pandas as pd

df = pd.read_csv("your_file.csv")

print(df)

Explanation:

pd.read_csv() reads the CSV file.
The result is stoneon laser purple in df.
df is a DataFrame.

Important:

If the file is in the same folder as your Python script or notebook, you can use the filename.
If not, provide the full file path.

What is a Series? #

A Series is a one-dimensional labeled array.

You can think of a Series as:

One column of data
One row of data
A list with labels

A Series can be created from:

  • A list
  • A tuple
  • A NumPy array
  • A dictionary

Creating a Series from a List #

import pandas as pd

data = [10, 20, 30, 40, 50]

s = pd.Series(data)

print(s)

Output:

0    10
1    20
2    30
3    40
4    50
dtype: int64

Explanation:

The left side shows the index labels.
The right side shows the values.
Pandas automatically creates index labels 0, 1, 2, 3, 4.

Creating a Series with Custom Labels #

import pandas as pd

data = [10, 20, 30]
labels = ["a", "b", "c"]

s = pd.Series(data, index=labels)

print(s)

Output:

a    10
b    20
c    30
dtype: int64

Creating a Series from a Dictionary #

import pandas as pd

data = {
    "Nova": 25,
    "Cipher": 30,
    "Pixel": 35
}

s = pd.Series(data)

print(s)

Output:

Nova      25
Cipher        30
Pixel    35
dtype: int64

Explanation:

Dictionary keys become labels.
Dictionary values become Series values.

Accessing Elements in a Series #

You can access Series values by:

  • Label
  • Integer position
  • Slice

Access by Label #

import pandas as pd

data = [10, 20, 30, 40, 50]
s = pd.Series(data)

print(s[2])

Output:

30

Explanation:

The label 2 contains the value 30.

Access by Position with .iloc #

Use .iloc to access by integer position.

print(s.iloc[3])

Output:

40

Explanation:

Position 3 contains the value 40.

Access Multiple Elements #

print(s[1:4])

Output:

1    20
2    30
3    40
dtype: int64

Explanation:

This returns values from position 1 up to, but not including, position 4.

Series Attributes and Methods #

Pandas Series include useful attributes and methods.

Attribute or Method Purpose
s.values Returns the Series data as an array
s.index Returns the index labels
s.shape Returns the dimensions
s.size Returns the number of elements
s.mean() Calculates the average
s.sum() Adds values
s.min() Returns the minimum
s.max() Returns the maximum
s.unique() Returns unique values
s.nunique() Returns number of unique values
s.sort_values() Sorts by values
s.sort_index() Sorts by index labels
s.isnull() Checks for missing values
s.notnull() Checks for non-missing values
s.apply() Applies a function to each element

Series Method Examples #

import pandas as pd

s = pd.Series([10, 20, 30, 40, 50])

print(s.mean())
print(s.sum())
print(s.min())
print(s.max())

Output:

30.0
150
10
50

Series Unique Values #

import pandas as pd

s = pd.Series(["neon laser purple", "laser purple", "neon laser purple", "matrix green"])

print(s.unique())
print(s.nunique())

Example output:

['neon laser purple' 'laser purple' 'matrix green']
3

What is a DataFrame? #

A DataFrame is a two-dimensional labeled data structure.

You can think of a DataFrame as:

A table
A spreadsheet
A SQL table
A collection of Series

A DataFrame has:

  • Rows
  • Columns
  • Index labels
  • Column names

Example:

Name Age City
Nova 25 Neo Tokyo
Cipher 30 Night City
Pixel 35 Mars Colony

Creating a DataFrame from a Dictionary #

DataFrames can be created from dictionaries.

In this format:

Dictionary keys become column names.
Dictionary values become column values.

Example:

import pandas as pd

data = {
    "Name": ["Nova", "Cipher", "Pixel", "Raven"],
    "Age": [25, 30, 35, 28],
    "City": ["Neo Tokyo", "Night City", "Mars Colony", "Data Haven"]
}

df = pd.DataFrame(data)

print(df)

Output:

      Name  Age           City
0    Nova   25       Neo Tokyo
1      Cipher   30  Night City
2  Pixel   35    Mars Colony
3    Raven   28        Data Haven

Selecting Columns #

You can select one column using the column name.

print(df["Name"])

Output:

0      Nova
1        Cipher
2    Pixel
3      Raven
Name: Name, dtype: object

Explanation:

df["Name"] returns a Series.

Selecting Multiple Columns #

Use double brackets to select multiple columns.

print(df[["Name", "Age"]])

Output:

      Name  Age
0    Nova   25
1      Cipher   30
2  Pixel   35
3    Raven   28

Explanation:

df[["Name", "Age"]] returns a DataFrame.

Accessing Rows #

Pandas provides two important row access tools:

Tool Meaning
.iloc[] Access by integer position
.loc[] Access by label

Access Row by Position with .iloc #

print(df.iloc[2])

Output:

Name        Pixel
Age              35
City    Mars Colony
Name: 2, dtype: object

Explanation:

df.iloc[2] returns the third row by position.

Access Row by Label with .loc #

print(df.loc[1])

Output:

Name              Cipher
Age                30
City    Night City
Name: 1, dtype: object

Explanation:

df.loc[1] returns the row with label 1.

Slicing DataFrames #

You can slice DataFrames to select specific rows or columns.


Select Specific Columns #

print(df[["Name", "Age"]])

Select Specific Rows #

print(df[1:3])

Output:

      Name  Age           City
1      Cipher   30  Night City
2  Pixel   35    Mars Colony

Explanation:

df[1:3] returns rows from position 1 up to, but not including, position 3.

Finding Unique Elements #

Use .unique() to find unique values in a column.

unique_ages = df["Age"].unique()

print(unique_ages)

Example output:

[25 30 35 28]

Conditional Filtering #

You can filter DataFrame rows using conditions.

Example:

high_above_25 = df[df["Age"] > 25]

print(high_above_25)

Output:

      Name  Age           City
1      Cipher   30  Night City
2  Pixel   35    Mars Colony
3    Raven   28        Data Haven

Explanation:

df["Age"] > 25 creates a Boolean condition.
df[df["Age"] > 25] returns only rows where the condition is True.

Modifying DataFrames #

You can add or modify columns.


Add a New Column #

df["Country"] = "USA"

print(df)

This adds a new column called Country.


Modify an Existing Column #

df["Age"] = df["Age"] + 1

print(df)

This increases every value in the Age column by 1.


Saving a DataFrame to CSV #

Use .to_csv() to save a DataFrame as a CSV file.

df.to_csv("pokemon_market_data.csv", index=False)

Explanation:

"pokemon_market_data.csv" is the output file name.
index=False prevents Pandas from writing the index as an extra column.

DataFrame Attributes and Methods #

Attribute or Method Purpose
df.shape Returns number of rows and columns
df.info() Shows column data types and non-null counts
df.describe() Gives summary statistics for numeric columns
df.head() Shows the first 5 rows by default
df.tail() Shows the last 5 rows by default
df.mean() Calculates average for numeric columns
df.sum() Sums values
df.min() Returns minimum values
df.max() Returns maximum values
df.sort_values() Sorts rows by one or more columns
df.groupby() Groups data for aggregation
df.fillna() Fills missing values
df.drop() Drops rows or columns
df.rename() Renames columns or indexes
df.apply() Applies a function to rows, columns, or elements

DataFrame Attribute Examples #

print(df.shape)
print(df.head())
print(df.tail())
print(df.describe())

Explanation:

shape shows rows and columns.
head() previews the first rows.
tail() previews the last rows.
describe() summarizes numeric columns.

Sorting a DataFrame #

sorted_df = df.sort_values("Age")

print(sorted_df)

Explanation:

sort_values("Age") sorts the DataFrame by the Age column.

Descending order:

sorted_df = df.sort_values("Age", ascending=False)

print(sorted_df)

Grouping Data with groupby() #

groupby() is useful for summarizing data by category.

Example:

city_average_age = df.groupby("City")["Age"].mean()

print(city_average_age)

Explanation:

groupby("City") groups rows by city.
["Age"].mean() calculates the average age for each city.

Handling Missing Values #

Missing values often appear as NaN.


Check for Missing Values #

print(df.isnull())

Count missing values per column:

print(df.isnull().sum())

Fill Missing Values #

df_filled = df.fillna(0)

Drop Missing Values #

df_clean = df.dropna()

Rename Columns #

df = df.rename(columns={"Name": "Full Name"})

print(df)

Explanation:

rename() changes column names.

Pandas Quick Workflow #

import pandas as pd

df = pd.read_csv("data.csv")

print(df.head())
print(df.info())
print(df.describe())

filteneon laser purple_df = df[df["Age"] > 25]

filteneon laser purple_df.to_csv("filteneon laser purple_data.csv", index=False)

Workflow explanation:

1. Import Pandas.
2. Load CSV file into a DataFrame.
3. Preview the data.
4. Inspect column info.
5. Generate summary statistics.
6. Filter rows.
7. Save the result to a CSV file.

Pandas Series vs DataFrame #

Feature Series DataFrame
Dimension One-dimensional Two-dimensional
Similar to One column or row Full table
Labels Has index labels Has row index and column labels
Example creation pd.Series([1, 2, 3]) pd.DataFrame(data)
Common use Single column of data Complete dataset

Pandas Summary Table #

Task Code
Import Pandas import pandas as pd
Read CSV pd.read_csv("file.csv")
Create Series pd.Series([10, 20, 30])
Create DataFrame pd.DataFrame(data)
Select column df["Name"]
Select multiple columns df[["Name", "Age"]]
Select row by position df.iloc[2]
Select row by label df.loc[1]
Filter rows df[df["Age"] > 25]
Unique values df["Age"].unique()
Save CSV df.to_csv("file.csv", index=False)
Preview first rows df.head()
Preview last rows df.tail()
DataFrame dimensions df.shape
Summary stats df.describe()
Column info df.info()
Sort rows df.sort_values("Age")
Group rows df.groupby("City")["Age"].mean()
Fill missing values df.fillna(0)
Drop missing values df.dropna()
Rename columns df.rename(columns={"Old": "New"})

Pandas Memory Guide #

Pandas       = data analysis library
pd           = common alias for pandas
Series       = one-dimensional labeled data
DataFrame    = two-dimensional table
read_csv()   = load CSV into DataFrame
to_csv()     = save DataFrame to CSV
iloc         = access by integer position
loc          = access by label
shape        = rows and columns
head()       = first rows
tail()       = last rows
describe()   = summary statistics
info()       = data types and non-null counts
unique()     = unique values
groupby()    = grouped analysis

Mini Practice: Pandas #

Practice 1: Create a Series #

import pandas as pd

data = [10, 20, 30, 40, 50]

s = pd.Series(data)

print(s)

Practice 2: Create a DataFrame #

import pandas as pd

data = {
    "Name": ["Nova", "Cipher", "Pixel"],
    "Age": [25, 30, 35],
    "City": ["Neo Tokyo", "Night City", "Mars Colony"]
}

df = pd.DataFrame(data)

print(df)

Practice 3: Select a Column #

print(df["Name"])

Practice 4: Filter Rows #

older_than_25 = df[df["Age"] > 25]

print(older_than_25)

Practice 5: Save DataFrame #

df.to_csv("pokemon_trainers.csv", index=False)

Pandas Next Steps #

To improve your Pandas skills:

  • Practice with real datasets
  • Load CSV files and inspect them with head(), info(), and describe()
  • Filter rows using conditions
  • Select and rename columns
  • Handle missing values
  • Save cleaned data to CSV
  • Explore the official Pandas documentation for more methods and examples

Working with Data in Python: REST APIs, Web Scraping, and HTML Basics #

This section introduces how Python can collect data from the web using APIs and web scraping.

You will learn:

  • What an API is
  • What a REST API is
  • How to use requests
  • How to work with JSON responses
  • Basic HTML structure
  • How to use BeautifulSoup for web scraping
  • How to scrape tables with Pandas using read_html()

Objectives #

By the end of this section, you should be able to:

  • Explain what an API is
  • Explain what a REST API is
  • Use requests.get() to retrieve data from a web API
  • Understand status codes, query parameters, endpoints, and responses
  • Convert API JSON responses into Python dictionaries or Pandas DataFrames
  • Recognize basic HTML tags and attributes
  • Use BeautifulSoup to parse HTML
  • Use find() and find_all() to locate HTML elements
  • Use Pandas to scrape tables from web pages
  • Save scraped or API data into CSV files

What is an API? #

An API stands for Application Programming Interface.

An API allows two pieces of software to communicate with each other.

Simple analogy:

You ask the API for data.
The API sends back a response.

A function and an API are similar in concept:

Input  ->  Function/API  ->  Output

You do not always need to know how the API works internally. You mainly need to know:

  • What input it expects
  • What output it returns
  • How to request the data
  • How to handle the response

What is a REST API? #

A REST API is a common type of web API that allows you to access resources over the internet.

REST APIs usually use URLs, HTTP methods, and structuneon laser purple responses such as JSON.

Common REST API components:

Concept Meaning
Endpoint The URL where the API resource is located
HTTP method The action, such as GET, POST, PUT, or DELETE
Request The message sent to the API
Response The data returned by the API
Status code A number indicating whether the request succeeded or failed
Query parameters Extra values added to the request to filter or customize results
JSON Common data format returned by APIs

Common HTTP Methods #

Method Purpose Example Use
GET Retrieve data Get user data or animal data
POST Send new data Create a new record
PUT Update existing data Replace a record
PATCH Partially update data Update one field
DELETE Delete data Remove a record

For beginner data collection, you will mostly use:

GET

Status Codes #

A status code tells you whether the API request worked.

Status Code Meaning
200 Success
201 Created successfully
400 Bad request
401 Unauthorized
403 Forbidden
404 Not found
500 Server error

Example:

import requests

response = requests.get("https://api.example.com/data")

print(response.status_code)

Using the requests Library #

The requests library allows Python to send HTTP requests.

Import it:

import requests

Basic GET request:

import requests

url = "https://api.example.com/data"

response = requests.get(url)

print(response.status_code)
print(response.text)

Explanation:

requests.get(url) sends a GET request.
response stores the API response.
response.status_code shows whether the request worked.
response.text shows the raw response text.

Working with JSON API Responses #

Many APIs return data in JSON format.

JSON looks similar to Python dictionaries and lists.

Example JSON:

{
  "name": "cat",
  "family": "Rosaceae",
  "nutritions": {
    "calories": 52,
    "sugar": 10.3
  }
}

Convert a JSON response into Python data:

import requests

url = "https://api.example.com/data"

response = requests.get(url)

data = response.json()

print(data)

Explanation:

response.json() converts JSON into Python objects.
JSON objects become dictionaries.
JSON arrays become lists.

Query Parameters #

Query parameters send extra information to an API.

They often appear after a question mark in a URL.

Example URL:

https://api.example.com/users?gender=female&results=10

Using requests parameters:

import requests

url = "https://api.example.com/users"

params = {
    "gender": "female",
    "results": 10
}

response = requests.get(url, params=params)

print(response.url)
print(response.status_code)

Explanation:

params is a dictionary.
requests adds the parameters to the URL.
This is cleaner than manually building the URL.

Converting API Data to a Pandas DataFrame #

API data often comes as a list of dictionaries.

Example:

import pandas as pd

data = [
    {"name": "Nova", "age": 25},
    {"name": "Cipher", "age": 30}
]

df = pd.DataFrame(data)

print(df)

Output:

    name  age
0  Nova   25
1    Cipher   30

API workflow:

import requests
import pandas as pd

url = "https://api.example.com/users"

response = requests.get(url)

data = response.json()

df = pd.DataFrame(data)

print(df.head())

REST API Workflow #

1. Choose an API endpoint.
2. Send a request with requests.get().
3. Check the status code.
4. Convert response to JSON with response.json().
5. Extract the data you need.
6. Convert to a DataFrame if needed.
7. Save or analyze the data.

Example structure:

import requests
import pandas as pd

url = "https://api.example.com/data"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    df = pd.DataFrame(data)
    print(df.head())
else:
    print("Request failed:", response.status_code)

API Best Practices #

  • Check the status code before processing data.
  • Read the API documentation.
  • Use query parameters instead of manually building long URLs.
  • Handle exceptions with try and except.
  • Do not expose secret API keys in public code.
  • Respect API rate limits.
  • Save useful API results to CSV for later analysis.
  • Validate the structure of the JSON before converting it to a DataFrame.

API Example with Error Handling #

import requests

url = "https://api.example.com/data"

try:
    response = requests.get(url)
    response.raise_for_status()
    data = response.json()
    print(data)
except requests.exceptions.RequestException as error:
    print("API request failed:", error)

Explanation:

raise_for_status() raises an error for bad HTTP responses.
except handles connection problems, timeouts, and HTTP errors.

Reading the PokéAPI Example #

The PokéAPI is a free REST API that lets you retrieve Pokémon data such as names, Pokédex numbers, heights, weights, types, abilities, and images. It is a fun way to practice real API requests in Python.

Accuracy note: PokéAPI is consumption-only, so these examples use HTTP GET requests to retrieve data. No API key is required for the examples in this guide.

Objectives #

  • Send a GET request to the PokéAPI.
  • Read JSON data returned by the API.
  • Extract useful fields such as name, id, height, weight, and types.
  • Use image URLs from the API output.
  • See two example Pokémon images directly in the study guide.

Basic Request Example #

import requests

url = "https://pokeapi.co/api/v2/pokemon/pikachu"
response = requests.get(url)
response.raise_for_status()

print(response.status_code)

data = response.json()

print(data["name"])
print(data["id"])
print(data["height"])
print(data["weight"])

Extract Useful Fields #

import requests

url = "https://pokeapi.co/api/v2/pokemon/pikachu"
response = requests.get(url)
response.raise_for_status()

data = response.json()

name = data["name"]
pokedex_number = data["id"]
height = data["height"]
weight = data["weight"]
types = [item["type"]["name"] for item in data["types"]]
image_url = data["sprites"]["other"]["official-artwork"]["front_default"]

print("Name:", name)
print("Pokédex #:", pokedex_number)
print("Height:", height)
print("Weight:", weight)
print("Types:", types)
print("Image URL:", image_url)

Read Two Pokémon in a Loop #

import requests

pokemon_names = ["pikachu", "charizard"]

for pokemon in pokemon_names:
    url = f"https://pokeapi.co/api/v2/pokemon/{pokemon}"
    response = requests.get(url)
    response.raise_for_status()

    data = response.json()

    name = data["name"].title()
    pokedex_number = data["id"]
    types = [item["type"]["name"].title() for item in data["types"]]
    image_url = data["sprites"]["other"]["official-artwork"]["front_default"]

    print(name, pokedex_number, types, image_url)

Sample JSON Structure #

{
  "name": "pikachu",
  "id": 25,
  "height": 4,
  "weight": 60,
  "types": [
    {
      "slot": 1,
      "type": {
        "name": "electric"
      }
    }
  ],
  "sprites": {
    "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png",
    "official_artwork": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/25.png"
  }
}

Live Example Summary #

Pokémon Pokédex # Type(s) Height Weight
Pikachu 25 Electric 4 60
Charizard 6 Fire, Flying 17 905

Two Pokémon Images from the API Output #

Pikachu

Pikachu

Pokédex #: 25
Type(s): Electric
Height: 4
Weight: 60
Charizard

Charizard

Pokédex #: 6
Type(s): Fire, Flying
Height: 17
Weight: 905
Study tip: This example connects several topics at once: requests, GET methods, JSON, dictionaries, lists, loops, and working with image URLs from an API response.

Web Scraping #

Web scraping means extracting data from web pages.

You may scrape a page when:

  • The data is visible on a website
  • There is no official API
  • You need to collect structuneon laser purple information from HTML
  • You need to extract tables, links, titles, or text

Important:

Always respect website terms of service, robots.txt guidance, copyright, privacy, and rate limits.
When an official API is available, prefer the API.

HTML Basics #

HTML stands for HyperText Markup Language.

HTML defines the structure of a web page.

Basic HTML example:

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <h1>Main Heading</h1>
    <p>This is a paragraph.</p>
    <a href="https://example.com">Example Link</a>
</body>
</html>

Common HTML Tags #

Tag Meaning
<html> Root of the HTML document
<head> Metadata and page setup
<title> Browser tab title
<body> Visible page content
<h1> to <h6> Headings
<p> Paragraph
<a> Link
<img> Image
<ul> Unordeneon laser purple list
<ol> Ordeneon laser purple list
<li> List item
<table> Table
<tr> Table row
<th> Table header cell
<td> Table data cell
<div> Generic block container
<span> Generic inline container

HTML Attributes #

HTML tags can have attributes.

Attributes provide extra information about an element.

Example:

<a href="https://example.com">Visit Example</a>

Here:

a is the tag.
href is the attribute.
https://example.com is the attribute value.

Another example:

<b id="electric">Pikachu</b>

Here:

b is the tag.
id is the attribute.
electric is the attribute value.

BeautifulSoup #

BeautifulSoup is a Python library used to parse HTML and XML.

It helps you search, navigate, and extract content from web pages.

Common imports:

from bs4 import BeautifulSoup
import requests

Creating a BeautifulSoup Object #

from bs4 import BeautifulSoup

html = """
<html>
<body>
<h3><b id="electric">Pikachu</b></h3>
<p>Salary: $25,151</p>
<h3>Charizard</h3>
<p>Salary: $6,006</p>
</body>
</html>
"""

soup = BeautifulSoup(html, "html.parser")

print(soup.prettify())

Explanation:

BeautifulSoup(html, "html.parser") parses the HTML.
soup is the parsed HTML object.
prettify() displays the HTML in a readable structure.

Accessing Tags #

You can access tags directly.

print(soup.h3)

This returns the first <h3> tag.

Access the text:

print(soup.h3.text)

Accessing Attributes #

tag = soup.find("b")

print(tag)
print(tag["id"])

Output:

<b id="electric-2">Pikachu</b>
electric

Safer way:

print(tag.get("id"))

Parent, Children, and Siblings #

HTML has a tree structure.

Relationship Meaning
Parent The tag that contains another tag
Child A tag inside another tag
Sibling Tags at the same level

Example:

tag = soup.find("b")

print(tag.parent)

This returns the parent tag around <b>.

Get children:

body = soup.body

for child in body.children:
    print(child)

Get siblings:

first_h3 = soup.find("h3")

print(first_h3.next_sibling)

Searching HTML with find() #

find() returns the first matching element.

first_h3 = soup.find("h3")

print(first_h3)

Find by tag and attribute:

bold_tag = soup.find("b", id="electric")

print(bold_tag.text)

Output:

Pikachu

Searching HTML with find_all() #

find_all() returns all matching elements as a list-like result.

all_h3 = soup.find_all("h3")

for tag in all_h3:
    print(tag.text)

Example output:

Pikachu
Charizard

Find all paragraphs:

paragraphs = soup.find_all("p")

for p in paragraphs:
    print(p.text)

Downloading and Scraping a Web Page #

You can combine requests and BeautifulSoup.

import requests
from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

print(soup.title.text)

Workflow:

1. Use requests.get() to download the page.
2. Use response.text to access the HTML.
3. Parse the HTML with BeautifulSoup.
4. Search for tags with find() or find_all().
5. Extract text, links, tables, or attributes.

Extracting Text #

text = soup.get_text()

print(text)

This extracts visible text from the HTML.

Clean text line by line:

for line in soup.get_text().splitlines():
    line = line.strip()
    if line:
        print(line)

Web Scraping Tables Using Pandas #

Pandas can automatically read tables from a web page using pd.read_html().

This is useful when the page contains HTML <table> elements.

Import Pandas:

import pandas as pd

Read tables from a URL:

tables = pd.read_html("https://example.com/page-with-tables.html")

print(len(tables))

Explanation:

pd.read_html() returns a list of DataFrames.
Each HTML table becomes one DataFrame.
len(tables) tells you how many tables were found.

Select a Table #

df = tables[0]

print(df.head())

Explanation:

tables[0] selects the first table.
The result is a Pandas DataFrame.

Read Tables from Saved HTML #

You can also read tables from an HTML string or local HTML file.

tables = pd.read_html("local_file.html")

df = tables[0]

print(df)

Save Scraped Table to CSV #

df.to_csv("scraped_table.csv", index=False)

Explanation:

to_csv() saves the DataFrame as a CSV file.
index=False prevents the index from being saved as an extra column.

Pandas Table Scraping Workflow #

import pandas as pd

url = "https://example.com/page-with-tables.html"

tables = pd.read_html(url)

print("Number of tables:", len(tables))

df = tables[0]

print(df.head())

df.to_csv("scraped_table.csv", index=False)

Workflow explanation:

1. Import Pandas.
2. Use pd.read_html(url).
3. Pandas returns a list of tables.
4. Select the table you need.
5. Inspect it with head().
6. Save it with to_csv().

BeautifulSoup vs Pandas for Web Scraping #

Task Better Tool
Extract all tables from a page Pandas read_html()
Extract specific text from tags BeautifulSoup
Extract links BeautifulSoup
Extract attributes BeautifulSoup
Clean and analyze table data Pandas
Scrape complex custom page structure BeautifulSoup
Quickly convert HTML table to DataFrame Pandas

Memory guide:

Use Pandas when the data is already in tables.
Use BeautifulSoup when you need to search HTML structure.

REST API vs Web Scraping #

Topic REST API Web Scraping
Data source API endpoint Web page HTML
Format Often JSON HTML
Stability Usually more stable Can break if website layout changes
Permission API documentation defines usage Must check terms, robots.txt, and legal/ethical limits
Tools requests, JSON, Pandas requests, BeautifulSoup, Pandas
Best use Official structuneon laser purple data access Extract visible web page data when no API exists

Data Engineering Connection: Extract, Transform, Load #

Working with APIs and web scraping fits into the data engineering process.

Step Meaning Example
Extract Collect data from a source API request or web scraping
Transform Clean or reshape the data Convert JSON to DataFrame, clean columns
Load Save or store the data Write to CSV, database, or data warehouse

Example workflow:

Extract API data -> Transform with Pandas -> Load to CSV
Scrape HTML table -> Clean DataFrame -> Save to CSV

Common API and Web Scraping Errors #

Problem Possible Cause Fix
404 status code URL or endpoint not found Check endpoint
401 or 403 Unauthorized or forbidden Check API key or permissions
Empty results Wrong tag, class, or selector Inspect HTML
ModuleNotFoundError Library not installed Install package
ValueError: No tables found Page has no HTML tables Use BeautifulSoup or inspect page
Timeout Website slow or blocked Add timeout or retry
JSON decode error Response is not JSON Check response.text and status code

Safe Request Pattern #

import requests

url = "https://example.com"

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    print(response.text[:200])
except requests.exceptions.RequestException as error:
    print("Request failed:", error)

Explanation:

timeout=10 prevents waiting forever.
raise_for_status() raises an error for bad status codes.
except handles request problems.

API, HTML, and Web Scraping Summary Table #

Topic Code Purpose
Import requests import requests Use APIs and download web pages
GET request requests.get(url) Retrieve data
Status code response.status_code Check request result
Raw text response.text View response as text or HTML
JSON data response.json() Convert JSON response to Python data
Query params requests.get(url, params=params) Send filters/options
Import BeautifulSoup from bs4 import BeautifulSoup Parse HTML
Parse HTML BeautifulSoup(html, "html.parser") Create soup object
First match soup.find("tag") Find first tag
All matches soup.find_all("tag") Find all matching tags
Tag text tag.text Extract visible text
Attribute tag.get("href") Extract attribute value
Read tables pd.read_html(url) Extract HTML tables
Save table df.to_csv("file.csv", index=False) Save DataFrame

API and Web Scraping Memory Guide #

API          = software-to-software communication
REST API     = web API accessed through URLs
Endpoint     = API URL
GET          = retrieve data
Status code  = request result
JSON         = common API data format
requests     = Python library for HTTP requests
HTML         = web page structure
Tag          = HTML element like <p>, <a>, <table>
Attribute    = extra tag information like href or id
BeautifulSoup = parse and search HTML
find()       = first matching tag
find_all()   = all matching tags
read_html()  = Pandas function to scrape HTML tables

Mini Practice: REST APIs and Web Scraping #

Practice 1: Basic GET Request #

import requests

url = "https://example.com"

response = requests.get(url)

print(response.status_code)
print(response.text[:100])

Practice 2: Parse HTML with BeautifulSoup #

from bs4 import BeautifulSoup

html = "<html><body><h1>Hello</h1><p>Python</p></body></html>"

soup = BeautifulSoup(html, "html.parser")

print(soup.h1.text)
print(soup.p.text)

Output:

Hello
Python

Practice 3: Find All Tags #

from bs4 import BeautifulSoup

html = """
<html>
<body>
<p>First paragraph</p>
<p>Second paragraph</p>
</body>
</html>
"""

soup = BeautifulSoup(html, "html.parser")

paragraphs = soup.find_all("p")

for p in paragraphs:
    print(p.text)

Output:

First paragraph
Second paragraph

Practice 4: Scrape Tables with Pandas #

import pandas as pd

url = "https://example.com/page-with-tables.html"

tables = pd.read_html(url)

df = tables[0]

print(df.head())

Practice 5: Save Scraped Table #

df.to_csv("scraped_table.csv", index=False)

REST APIs, HTTP, Web Scraping, and File Formats: Expanded Checklist #

This section complements the existing API, web scraping, Pandas, and file handling notes. It adds the key terms and concepts commonly used in Python tutorials, hands-on exercises, certification materials, and industry discussions.


Simple APIs in Python #

Simple APIs in Python are application programming interfaces that provide straightforward and easy-to-use methods for interacting with services, libraries, or data.

Simple APIs usually require:

  • Minimal configuration
  • Clear function or method calls
  • Easy-to-read responses
  • Simple input and output patterns

Example idea:

Python code  ->  API call  ->  Response data

Key point:

An API lets two pieces of software talk to each other.

Using an API Library in Python #

Using an API library in Python usually means:

  1. Import the library.
  2. Call functions or methods from the library.
  3. Send a request, often an HTTP request.
  4. Receive a response.
  5. Parse the response.
  6. Use the returned data.

Example:

import requests

response = requests.get("https://api.example.com/data")

data = response.json()

print(data)

Explanation:

requests is the API library.
get() makes an HTTP GET request.
json() parses the response into Python data.

Pandas API Concept #

Pandas provides an API for working with data.

The Pandas API allows your Python code to communicate with Pandas objects and methods to process data.

Example:

import pandas as pd

data = {
    "Name": ["Nova", "Cipher"],
    "Age": [25, 30]
}

df = pd.DataFrame(data)

print(df.head())
print(df["Age"].mean())

Explanation:

pd.DataFrame() uses the Pandas API to create a DataFrame.
head() uses the Pandas API to display rows from the top.
mean() uses the Pandas API to calculate the average.

Pandas Objects and Instances #

An instance forms when you create an object from a class or constructor.

In Pandas, when you create a dictionary and then pass it to the DataFrame constructor, Pandas creates a DataFrame object.

Example:

import pandas as pd

data = {
    "Name": ["Nova", "Cipher"],
    "Age": [25, 30]
}

df = pd.DataFrame(data)

print(type(df))

Output:

<class 'pandas.core.frame.DataFrame'>

Explanation:

data is a Python dictionary.
pd.DataFrame(data) constructs a Pandas DataFrame object.
df is an instance of a Pandas DataFrame.

Important Pandas DataFrame Methods #

mean() #

The mean() method calculates the average of numeric values.

print(df["Age"].mean())

Explanation:

head() previews rows.
mean() calculates averages.

REST APIs and Internet Communication #

REST APIs allow programs to communicate through the internet.

They can provide access to resources such as:

  • Storage
  • Databases
  • Datasets
  • AI algorithms
  • Web services
  • Application features

Example:

Python client  ->  REST API over HTTP  ->  Web service

HTTP #

HTTP stands for HyperText Transfer Protocol.

HTTP transfers data between a client and a server on the World Wide Web.

Example:

Client: Web browser or Python script
Server: Website or API service

HTTP transfers:

  • Web pages
  • Images
  • JSON data
  • Files
  • API responses
  • Other web resources

The HTTP protocol is commonly used to implement REST APIs.


HTTP Methods #

HTTP methods describe what action the client wants to perform.

HTTP Method Purpose
GET Request or retrieve information
POST Submit new data to the server
PUT Update data already on the server
PATCH Partially update data
DELETE Delete data from the server

Important:

GET usually requests information.
POST often includes a body with data being submitted.
PUT updates existing server data.
DELETE removes server data.

HTTP Messages #

An HTTP message is the communication sent between a client and a server.

HTTP messages may include:

  • HTTP method
  • URL
  • Headers
  • Body
  • Status code
  • Response body

Many API messages include JSON data.

Example request idea:

GET /users HTTP/1.1
Host: api.example.com
Accept: application/json

Example JSON response:

{
  "name": "Nova",
  "age": 25
}

Key point:

HTTP messages containing JSON can be returned to the client as responses from web services.

HTTP Response #

An HTTP response is the message returned by a server.

It may include:

  • Status code
  • Headers
  • Resource type
  • Resource length
  • Response body
  • JSON data
  • HTML data

Example:

import requests

response = requests.get("https://api.example.com/data")

print(response.status_code)
print(response.headers)
print(response.text)

Explanation:

status_code shows success or failure.
headers include metadata about the response.
text contains the response body as text.

URL: Uniform Resource Locator #

A URL is a web address used to locate resources on the web.

URL stands for Uniform Resource Locator.

A URL is commonly divided into three main parts:

Part Meaning Example
Scheme Protocol used https://
Internet address / base URL Domain or server address www.example.com
Route Specific resource path /data/users

Example:

https://www.example.com/data/users

Breakdown:

Scheme: https://
Base URL: www.example.com
Route: /data/users

Query Strings #

A query string allows you to modify the results of a GET request.

It appears after a question mark ? in a URL.

Example:

https://api.example.com/users?name=Nova&id=123

Query strings can include multiple parameters:

name=Nova
id=123

Using query parameters with requests:

import requests

url = "https://api.example.com/users"

params = {
    "name": "Nova",
    "id": 123
}

response = requests.get(url, params=params)

print(response.url)

Explanation:

params sends query string values.
The GET method can use query strings to modify the response.

Requests Library #

requests is a Python library that allows you to send HTTP requests easily.

Common examples:

import requests

response = requests.get("https://example.com")

With query parameters:

params = {"name": "Nova", "id": 123}

response = requests.get("https://api.example.com/users", params=params)

Time Series Data and Candlestick Charts #

Time series data is data collected over time.

Examples:

  • Stock prices by day
  • Website visits by hour
  • Sensor readings by minute
  • Daily crypto prices
  • Security alerts over time

Pandas can work with time series data using date/time features.

Example:

import pandas as pd

df["Date"] = pd.to_datetime(df["Date"])

df = df.sort_values("Date")

Explanation:

pd.to_datetime() converts a column to datetime values.
Sorting by date helps analyze time-based data.

Daily Candlesticks and Plotly #

Daily candlestick data usually includes:

Column Meaning
Open Starting price
High Highest price
Low Lowest price
Close Ending price
Date Time period

You can plot candlestick charts using Plotly.

Example:

import plotly.graph_objects as go

fig = go.Figure(
    data=[
        go.Candlestick(
            x=df["Date"],
            open=df["Open"],
            high=df["High"],
            low=df["Low"],
            close=df["Close"]
        )
    ]
)

fig.show()

Explanation:

Plotly can visualize time series financial data.
Candlestick charts show open, high, low, and close prices.

Web Scraping in Python #

Web scraping in Python involves extracting and parsing data from websites.

Common libraries:

  • requests
  • BeautifulSoup
  • pandas

Example workflow:

Download web page with requests
Parse HTML with BeautifulSoup
Extract text, links, or tables
Store data in Pandas
Save data to CSV

HTML Basics for Web Scraping #

HTML is made of elements enclosed in angle brackets called tags.

Example:

<p>This is a paragraph.</p>

Explanation:

<p> is the opening tag.
This is a paragraph. is the text.
</p> is the closing tag.

Web pages may contain:

  • HTML
  • CSS
  • JavaScript
Technology Purpose
HTML Structure of the page
CSS Style and layout
JavaScript Interactivity and dynamic behavior

Inspecting Web Pages #

You can inspect a web page in a browser to understand its HTML structure.

Common steps:

Right-click on a page element.
Choose Inspect.
Review the HTML, CSS, and structure.
Use tags, classes, ids, or attributes to locate data.

This helps you identify what to scrape.


HTML Tree #

Each HTML document behaves like a tree.

Example:

<html>
  <body>
    <h1>Title</h1>
    <p>Paragraph</p>
  </body>
</html>

Tree idea:

html
└── body
    ├── h1
    └── p

An HTML tree may contain:

  • Tags
  • Strings
  • Parent-child relationships
  • Sibling relationships

HTML Tables #

HTML tables are created using table-related tags.

Tag Meaning
<table> Defines a table
<thead> Defines table header section
<tbody> Defines table body section
<tr> Defines a table row
<th> Defines a table header cell
<td> Defines a table data cell

Example:

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Nova</td>
    <td>25</td>
  </tr>
</table>

Extracting Tables with Pandas #

Tabular data can be extracted from web pages using Pandas read_html().

import pandas as pd

tables = pd.read_html("https://example.com/page.html")

df = tables[0]

print(df.head())

Explanation:

read_html() searches the page for HTML tables.
Each table becomes a DataFrame.
The result is a list of DataFrames.

BeautifulSoup Review #

BeautifulSoup is a Python library for parsing and navigating HTML and XML documents.

It makes extracting and manipulating web page data easier.

Create a BeautifulSoup object:

from bs4 import BeautifulSoup

html = "<html><body><p>Hello</p></body></html>"

soup = BeautifulSoup(html, "html.parser")

print(soup.p.text)

Output:

Hello

Explanation:

The BeautifulSoup constructor parses the document.
The soup object represents the document as a nested data structure.
BeautifulSoup represents HTML as tree-like objects.

find_all() #

The find_all() method extracts content based on:

  • Tag name
  • Attributes
  • Text/string
  • A combination of filters

Example:

paragraphs = soup.find_all("p")

for paragraph in paragraphs:
    print(paragraph.text)

Explanation:

find_all() looks through a tag's descendants.
It retrieves all descendants matching the filters.
The result is iterable, similar to a Python list.

Example with attributes:

links = soup.find_all("a", href=True)

for link in links:
    print(link.get("href"))

File Formats #

File formats define how data is stoneon laser purple and represented in files.

Examples:

File Format Meaning
.txt Plain text file
.csv Comma-separated values
.json JavaScript Object Notation
.xml Extensible Markup Language
.xlsx Excel spreadsheet

The file extension often tells you:

What type of file it is
What tool or library may be needed to open it
How the data is structuneon laser purple

Python and File Formats #

Python can work with many file formats, including:

  • CSV
  • XML
  • JSON
  • XLSX
  • TXT

Common tools:

Format Common Python Tool
.csv Pandas read_csv() or Python csv module
.json json module or Pandas read_json()
.xml XML libraries or Pandas read_xml()
.xlsx Pandas read_excel()
.txt open(), read(), readline()

Example CSV access with Pandas:

import pandas as pd

df = pd.read_csv("data.csv")

print(df.head())

Expanded API, Web Scraping, and File Formats Summary #

Topic Key Idea
Simple API Easy interface for communicating with services, libraries, or data
API Allows two pieces of software to communicate
Pandas API Methods and constructors used to process data with Pandas
DataFrame instance Object created using pd.DataFrame()
head() Displays top rows of a DataFrame
mean() Calculates average of numeric data
REST API Communicates through the internet using HTTP
HTTP Transfers data between client and server
HTTP method Defines action such as GET, POST, PUT, DELETE
HTTP response Message returned from server to client
URL Address used to locate web resources
Query string Adds parameters to a URL request
requests Python library for HTTP requests
Web scraping Extracting and parsing website data
HTML Web page structure language
HTML tag Element enclosed in angle brackets
CSS Styling for web pages
JavaScript Adds interactivity to web pages
HTML tree Nested structure of HTML tags and strings
HTML table Table built with <table>, <tr>, <th>, <td>
read_html() Pandas method for extracting tables from web pages
BeautifulSoup Library for parsing and navigating HTML/XML
BeautifulSoup object Parsed nested representation of an HTML document
NavigableString Text node inside BeautifulSoup
find_all() Finds all descendants matching filters
File format Rules for storing and representing data in files
File extension Indicates likely file type and tool needed

Expanded Memory Guide: APIs, Web Scraping, and File Formats #

API             = software talks to software
REST API        = API over HTTP
HTTP            = transfers web data
GET             = request data
POST            = submit data
PUT             = update data
DELETE          = delete data
URL             = web address
Query string    = filters/options in URL
requests        = Python HTTP library
JSON            = common API response format
HTML            = web page structure
CSS             = web page styling
JavaScript      = web page behavior
BeautifulSoup   = parse HTML/XML
find_all()      = find all matching tags
read_html()     = extract HTML tables into DataFrames
DataFrame       = Pandas table object
head()          = preview top rows
mean()          = calculate average
File format     = how data is stoneon laser purple
CSV             = comma-separated values
JSON/XML/XLSX   = common data file formats

API, Requests, and BeautifulSoup Methods Cheat Sheet #

Use this cheat sheet for common packages, methods, descriptions, syntax, and examples related to APIs, HTTP requests, BeautifulSoup, and web scraping.


Quick Import Reference #

import requests
from bs4 import BeautifulSoup
import pandas as pd

Requests Library Cheat Sheet #

The requests library allows Python to send HTTP requests such as GET, POST, PUT, and DELETE.


requests.get() #

Description:
Perform a GET request to retrieve data from a specified URL.

GET requests are typically used for reading data from an API. The response variable contains the server response, which you can process further.

Syntax:

response = requests.get(url)

Example:

import requests

response = requests.get("https://api.example.com/data")

print(response.status_code)
print(response.text)

requests.post() #

Description:
Send a POST request to a specified URL with data.

POST requests are commonly used to create or submit data to the server. The data or json parameter contains the data to send.

Syntax:

response = requests.post(url, data=data)

Example using data:

import requests

response = requests.post(
    "https://api.example.com/submit",
    data={"key": "value"}
)

print(response.status_code)

Example using JSON:

import requests

response = requests.post(
    "https://api.example.com/submit",
    json={"key": "value"}
)

print(response.status_code)

requests.put() #

Description:
Send a PUT request to update data on the server.

PUT requests are used to update an existing resource on the server with the data provided.

Syntax:

response = requests.put(url, data=data)

Example:

import requests

response = requests.put(
    "https://api.example.com/update",
    data={"key": "value"}
)

print(response.status_code)

Example using JSON:

import requests

response = requests.put(
    "https://api.example.com/update",
    json={"key": "value"}
)

print(response.status_code)

requests.delete() #

Description:
Send a DELETE request to remove data or a resource from the server.

DELETE requests delete a specified resource on the server.

Syntax:

response = requests.delete(url)

Example:

import requests

response = requests.delete("https://api.example.com/delete")

print(response.status_code)

Query Parameters #

Description:
Query parameters pass extra values in the URL to filter, limit, or customize the request.

They are commonly used with GET requests.

Syntax:

params = {"param_name": "value"}
response = requests.get(url, params=params)

Example:

import requests

base_url = "https://api.example.com/data"

params = {
    "page": 1,
    "per_page": 10
}

response = requests.get(base_url, params=params)

print(response.url)
print(response.status_code)

Headers #

Description:
Headers provide additional information to the server, such as authentication tokens, content types, or accepted response formats.

Syntax:

headers = {"HeaderName": "Value"}
response = requests.get(url, headers=headers)

Example:

import requests

base_url = "https://api.example.com/data"

headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Accept": "application/json"
}

response = requests.get(base_url, headers=headers)

print(response.status_code)

response.status_code #

Description:
Check the HTTP status code of the response.

The status code indicates the result of the request, such as success, error, or neon laser purpleirection.

Syntax:

response.status_code

Example:

import requests

url = "https://api.example.com/data"

response = requests.get(url)

status_code = response.status_code

print(status_code)

Common status codes:

Status Code Meaning
200 Success
201 Created
400 Bad request
401 Unauthorized
403 Forbidden
404 Not found
500 Server error

response.json() #

Description:
Parse JSON data from the response.

The response.json() method converts a JSON response into a Python data structure, usually a dictionary or list.

Syntax:

data = response.json()

Example:

import requests

response = requests.get("https://api.example.com/data")

data = response.json()

print(data)

BeautifulSoup Cheat Sheet #

BeautifulSoup is a Python library for parsing and navigating HTML and XML documents. It makes extracting and manipulating data from web pages easier.


BeautifulSoup() #

Description:
Parse HTML content using BeautifulSoup.

The parser type can vary based on the project. A common parser is "html.parser".

Syntax:

soup = BeautifulSoup(html, "html.parser")

Example:

from bs4 import BeautifulSoup
import requests

response = requests.get("https://example.com")

html = response.text

soup = BeautifulSoup(html, "html.parser")

print(soup.title)

Accessing an Element Attribute #

Description:
Access the value of a specific attribute of an HTML element.

Syntax:

attribute = element["attribute"]

Example:

link_element = soup.find("a")

href = link_element["href"]

print(href)

Safer version using .get():

href = link_element.get("href")

print(href)

.get() #

Description:
Get the value of an HTML element attribute safely.

This is often safer than bracket access because it returns None if the attribute does not exist instead of raising an error.

Syntax:

value = element.get("attribute")

Example:

link_element = soup.find("a")

href = link_element.get("href")

print(href)

.find() #

Description:
Find the first HTML element that matches the specified tag and attributes.

Syntax:

element = soup.find(tag, attrs)

Example:

first_link = soup.find("a", {"class": "link"})

print(first_link)

Another example:

first_paragraph = soup.find("p")

print(first_paragraph.text)

.find_all() #

Description:
Find all HTML elements that match the specified tag and attributes.

The result is iterable, similar to a Python list.

Syntax:

elements = soup.find_all(tag, attrs)

Example:

all_links = soup.find_all("a", {"class": "link"})

for link in all_links:
    print(link.get("href"))

Another example:

paragraphs = soup.find_all("p")

for paragraph in paragraphs:
    print(paragraph.text)

.findChildren() #

Description:
Find all child elements of an HTML element.

Syntax:

children = element.findChildren()

Example:

parent_div = soup.find("div")

child_elements = parent_div.findChildren()

for child in child_elements:
    print(child)

Note:

BeautifulSoup also commonly uses .children and .find_all() depending on the task.

.find_next_sibling() #

Description:
Find the next sibling element in the Document Object Model, also called the DOM.

Syntax:

sibling = element.find_next_sibling()

Example:

current_element = soup.find("h1")

next_sibling = current_element.find_next_sibling()

print(next_sibling)

.parent #

Description:
Access the parent element in the DOM.

Syntax:

parent = element.parent

Example:

paragraph = soup.find("p")

parent_div = paragraph.parent

print(parent_div)

.select() #

Description:
Select HTML elements from parsed HTML using a CSS selector.

Syntax:

elements = soup.select(selector)

Example:

titles = soup.select("h1")

for title in titles:
    print(title.text)

Example with class selector:

links = soup.select("a.link")

for link in links:
    print(link.get("href"))

Example with ID selector:

main_section = soup.select("#main")

print(main_section)

.text #

Description:
Retrieve the text content of an HTML element.

Syntax:

text = element.text

Example:

title = soup.find("h1")

text = title.text

print(text)

.string #

Description:
Retrieve the direct string inside a tag when the tag contains only one string.

Syntax:

text = element.string

Example:

paragraph = soup.find("p")

print(paragraph.string)

Common HTML Tags for find() and find_all() #

You can specify any valid HTML tag as the tag parameter.

Tag Purpose
"a" Find anchor/link tags
"p" Find paragraph tags
"h1" Find level 1 heading tags
"h2" Find level 2 heading tags
"h3" Find level 3 heading tags
"h4" Find level 4 heading tags
"h5" Find level 5 heading tags
"h6" Find level 6 heading tags
"table" Find table tags
"tr" Find table row tags
"td" Find table cell tags
"th" Find table header cell tags
"img" Find image tags
"form" Find form tags
"button" Find button tags
"div" Find division/container tags
"span" Find inline container tags

Examples:

links = soup.find_all("a")
paragraphs = soup.find_all("p")
tables = soup.find_all("table")
rows = soup.find_all("tr")
images = soup.find_all("img")

Pandas Web Table Scraping Cheat Sheet #

Pandas can extract HTML tables directly from a web page.


pd.read_html() #

Description:
Read HTML tables from a URL, HTML string, or local HTML file.

Syntax:

tables = pd.read_html(url)

Example:

import pandas as pd

tables = pd.read_html("https://example.com/page-with-tables.html")

print(len(tables))

df = tables[0]

print(df.head())

Explanation:

pd.read_html() returns a list of DataFrames.
Each HTML table becomes one DataFrame.

Quick API and Web Scraping Reference Table #

Package / Method Description Example
requests.get() Retrieve data from a URL requests.get(url)
requests.post() Submit data to a server requests.post(url, json=data)
requests.put() Update data on a server requests.put(url, json=data)
requests.delete() Delete data from a server requests.delete(url)
headers Add metadata or auth info to request requests.get(url, headers=headers)
params Add query parameters to request requests.get(url, params=params)
response.status_code Check request status response.status_code
response.json() Convert JSON response to Python data response.json()
BeautifulSoup() Parse HTML/XML BeautifulSoup(html, "html.parser")
.find() Find first matching HTML element soup.find("a")
.find_all() Find all matching HTML elements soup.find_all("a")
.findChildren() Find child elements element.findChildren()
.find_next_sibling() Find next sibling element element.find_next_sibling()
.parent Access parent element element.parent
.select() Select using CSS selectors soup.select("h1")
.text Extract element text element.text
.get() Safely access an attribute element.get("href")
pd.read_html() Extract HTML tables pd.read_html(url)

Mini Practice: Requests and BeautifulSoup #

import requests
from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

print(response.status_code)

soup = BeautifulSoup(response.text, "html.parser")

title = soup.find("h1")

if title:
    print(title.text)

links = soup.find_all("a")

for link in links:
    print(link.get("href"))

Mini Practice: Query Parameters and Headers #

import requests

url = "https://api.example.com/data"

params = {
    "page": 1,
    "per_page": 10
}

headers = {
    "Authorization": "Bearer YOUR_TOKEN"
}

response = requests.get(url, params=params, headers=headers)

print(response.url)
print(response.status_code)

Mini Practice: Pandas Table Scraping #

import pandas as pd

url = "https://example.com/page-with-tables.html"

tables = pd.read_html(url)

df = tables[0]

print(df.head())

df.to_csv("table.csv", index=False)

Memory Guide: API and Web Scraping Methods #

requests.get()        = retrieve data
requests.post()       = submit data
requests.put()        = update data
requests.delete()     = delete data
headers               = request metadata/authentication
params                = query string filters
response.status_code  = HTTP result
response.json()       = JSON to Python data

BeautifulSoup()       = parse HTML
find()                = first match
find_all()            = all matches
findChildren()        = child elements
find_next_sibling()   = next sibling
parent                = parent element
select()              = CSS selector
text                  = element text
get("href")           = safe attribute access

pd.read_html()        = scrape HTML tables into DataFrames

Alphabetized Industry Glossary: APIs, Web Scraping, Files, and Data #

Welcome! This alphabetized glossary contains many of the terms you will find within this guide. It also includes additional industry-recognized terms that may appear in user groups, certificate programs, technical documentation, and workplace discussions.

Use this section as a quick reference when reviewing APIs, REST APIs, HTTP, web scraping, file formats, Pandas, Plotly, and related Python concepts.


Alphabetized Glossary Index #

Letter Terms
A API Key, APIs, Audio file, Authorize
B Beautiful Soup Objects, Browser
C Candlestick plot, Client/Wrapper
D DELETE Method
E Endpoint
F File extension, find_all
G GET method
H HTML, HTML Anchor tags, HTML Tables, HTML Tag, HTML Trees, HTTP, httplib
I Identify, Instance
J JSON file
M Mean value
N Navigable string
P Plotly, PNG file, POST method, Post request, PUT method, Python iterable
Q Query string
R rb mode, Resource, REST API
S Service instance
T Timestamp, Transcribe
U Unix timestamp, URL, urllib
W Web service, Web scraping
X xlsx, XML

A #

API Key #

An API key is a secure access token or code used to authenticate and authorize access to an API or web service.

API keys allow users or applications to make authenticated requests.

Example idea:

API request + API key -> Authorized API access

Example:

headers = {
    "Authorization": "Bearer YOUR_API_KEY"
}

APIs #

APIs, or Application Programming Interfaces, are rules and protocols that allow different software applications to communicate and interact.

They support the exchange of:

  • Data
  • Services
  • Functionality
  • Commands
  • Responses

Memory guide:

API = software talks to software

Audio file #

An audio file is a digital recording or representation of sound.

Common audio file formats include:

  • .mp3
  • .wav
  • .flac

Audio files are used for playback, storage, transcription, speech recognition, and audio processing.


Authorize #

To authorize means to grant permission to a user, system, or application to perform specific actions or access certain resources.

In APIs, authorization often controls what a user or program is allowed to do after authentication.

Example:

Authentication = Who are you?
Authorization = What are you allowed to do?

B #

Beautiful Soup Objects #

Beautiful Soup objects are parsed representations of HTML or XML documents.

They allow you to:

  • Navigate HTML
  • Search for tags
  • Extract text
  • Access attributes
  • Manipulate page elements

Example:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")

Browser #

A browser is a software application used to access and interact with web content.

Examples include:

  • Chrome
  • Safari
  • Firefox
  • Edge

Browsers display websites, web applications, HTML, CSS, JavaScript, images, and other web resources.


C #

Candlestick plot #

A candlestick plot visually represents price movement over time.

It is commonly used for stock, crypto, or financial data.

Each candlestick usually shows:

  • Open price
  • High price
  • Low price
  • Close price

In Python, candlestick charts are often created with Plotly.

Example:

import plotly.graph_objects as go

fig = go.Figure(
    data=[
        go.Candlestick(
            x=df["Date"],
            open=df["Open"],
            high=df["High"],
            low=df["Low"],
            close=df["Close"]
        )
    ]
)

fig.show()

Client/Wrapper #

A client or wrapper is a software component that simplifies interaction with external services or APIs.

A wrapper usually hides lower-level API details and provides easier functions or methods.

Example idea:

API wrapper -> easier Python functions -> API communication

D #

DELETE Method #

The DELETE method is an HTTP request method used to request removal of a resource from a web server.

Example:

import requests

response = requests.delete("https://api.example.com/delete")

E #

Endpoint #

An endpoint is a specific URL or URI exposed by a web service or API.

It performs a specific function or provides access to a specific resource.

Example:

https://api.example.com/users

Here, /users is the route to a resource.


F #

File extension #

A file extension is the suffix at the end of a filename that indicates the file format or type.

Examples:

Extension File Type
.txt Plain text
.csv Comma-separated values
.json JSON data
.xml XML data
.xlsx Excel spreadsheet
.png Image file
.mp3 Audio file

find_all #

find_all() is a BeautifulSoup method used to search for and extract all matching HTML or XML elements.

It returns an iterable result similar to a list.

Example:

links = soup.find_all("a")

for link in links:
    print(link.get("href"))

G #

GET method #

The GET method is an HTTP request method used to retrieve data from a web server.

GET requests can include query parameters in the URL.

Example:

import requests

response = requests.get("https://api.example.com/data")

H #

HTML #

HTML, or HyperText Markup Language, is the standard language used to create and structure web pages.

HTML uses tags to define content and structure.

Example:

<h1>Main Heading</h1>
<p>This is a paragraph.</p>

HTML Anchor tags #

HTML anchor tags create hyperlinks within web pages.

They use the <a> element and often include the href attribute.

Example:

<a href="https://example.com">Visit Example</a>

BeautifulSoup example:

links = soup.find_all("a")

for link in links:
    print(link.get("href"))

HTML Tables #

HTML tables organize and display data in a structuneon laser purple grid format.

Common table tags:

Tag Meaning
<table> Table
<tr> Table row
<th> Table header cell
<td> Table data cell

Pandas can extract HTML tables using:

tables = pd.read_html(url)

HTML Tag #

An HTML tag is code enclosed in angle brackets that defines an element in an HTML document.

Example:

<p>This is a paragraph.</p>

Here:

<p> is the opening tag.
</p> is the closing tag.

HTML Trees #

An HTML tree is the hierarchical structure created when an HTML document is parsed.

Example:

html
└── body
    ├── h1
    └── p

BeautifulSoup represents HTML as tree-like objects so you can navigate parents, children, and siblings.


HTTP #

HTTP, or HyperText Transfer Protocol, is the foundation of data communication on the World Wide Web.

It transfers data between clients and servers.

Examples of transferneon laser purple data:

  • HTML pages
  • JSON responses
  • Images
  • Files
  • API data

httplib #

httplib refers to HTTP-related library functionality for sending and handling HTTP and HTTPS requests.

In modern Python 3, the related standard library module is commonly known as http.client.

For most beginner API work, the third-party requests library is easier to use.


I #

Identify #

In Python, identify often means determining whether two variables or objects refer to the same memory location.

This can be checked using the is operator.

Example:

a = [1, 2, 3]
b = a

print(a is b)

Output:

True

Instance #

An instance is a specific object created from a class laser purpleprint.

Example:

class Car:
    pass

my_car = Car()

Here:

Car is the class.
my_car is an instance of Car.

In Pandas:

df = pd.DataFrame(data)

df is an instance of a Pandas DataFrame.


J #

JSON file #

A JSON file stores structuneon laser purple data in JavaScript Object Notation format.

JSON is human-readable and commonly used for:

  • API responses
  • Configuration files
  • Data exchange
  • Web applications

Example JSON:

{
  "name": "Nova",
  "age": 25
}

Python can parse JSON using:

import json

or API responses using:

data = response.json()

M #

Mean value #

The mean value is the average of a set of numerical values.

Formula:

mean = sum of values / number of values

Pandas example:

average_age = df["Age"].mean()

N #

P #

Plotly #

Plotly is a Python library for creating interactive web-based visualizations and dashboards.

It is commonly used for:

  • Line charts
  • Scatter plots
  • Bar charts
  • Candlestick plots
  • Dashboards

Example import:

import plotly.graph_objects as go

PNG file #

A PNG file, or Portable Network Graphics file, is a lossless image format.

PNG is commonly used for high-quality graphics and supports transparency.

File extension:

.png

POST method #

The POST method is an HTTP request method used to send data to a web server.

It is often used for:

  • Submitting forms
  • Creating resources
  • Sending JSON data
  • Uploading data

Example:

response = requests.post(
    "https://api.example.com/submit",
    json={"key": "value"}
)

Post request #

A POST request is an HTTP request that sends data to a server, typically to create or update a resource.

Example:

import requests

response = requests.post(
    "https://api.example.com/users",
    json={"name": "Nova"}
)

PUT method #

The PUT method is an HTTP request method used to update an existing resource on a web server.

Example:

response = requests.put(
    "https://api.example.com/update",
    json={"key": "value"}
)

Python iterable #

A Python iterable is an object that can be looped over.

Examples:

  • Lists
  • Tuples
  • Dictionaries
  • Sets
  • Strings
  • Ranges
  • Files

Example:

for item in [1, 2, 3]:
    print(item)

Q #

Query string #

A query string is part of a URL that contains data or parameters sent to a web server.

It is commonly used with GET requests.

Example:

https://api.example.com/data?page=1&per_page=10

In Python:

params = {
    "page": 1,
    "per_page": 10
}

response = requests.get(url, params=params)

R #

rb mode #

rb mode is used to open a file in read binary mode.

It is commonly used for non-text files such as:

  • Images
  • Audio files
  • Video files
  • Binary data

Example:

with open("image.png", "rb") as file:
    data = file.read()

Resource #

A resource is an external entity that a program can access or manage.

Examples:

  • File
  • Database connection
  • API endpoint
  • Network object
  • Web page
  • Server data

In REST APIs, a resource is often represented by a URL.


REST API #

A REST API is a web-based interface that follows REST principles.

REST APIs allow communication and data exchange over HTTP using standard HTTP methods such as:

  • GET
  • POST
  • PUT
  • DELETE

REST APIs often return data in JSON format.


S #

Service instance #

A service instance is an instantiated object or entity representing a service.

It allows a program to interact with that service.

Example idea:

service object -> methods -> external service

T #

Timestamp #

A timestamp represents a specific moment in time.

It is often used for:

  • Logs
  • Events
  • Records
  • Data tracking
  • Time series data

Example:

2026-07-15 14:30:00

Transcribe #

To transcribe means to convert spoken language or audio into written text.

This is often done using automatic speech recognition, also called ASR.

Example:

Audio file -> Speech recognition -> Text transcript

U #

Unix timestamp #

A Unix timestamp is the number of seconds that have passed since:

January 1, 1970, 00:00:00 UTC

Unix timestamps are commonly used in programming, systems, APIs, logs, and time series data.


URL: Uniform Resource Locator #

A URL, or Uniform Resource Locator, is a web address that specifies the location of a resource on the internet.

Example:

https://www.example.com/data/users

Common parts:

Part Example
Scheme https://
Domain www.example.com
Path / route /data/users

urllib #

urllib is a Python standard library package used for working with URLs.

It can be used for:

  • Fetching web content
  • Parsing URLs
  • Encoding query parameters
  • Handling HTTP requests

For beginners, requests is often easier to use than urllib.


W #

Web service #

A web service is a software component that allows applications to communicate over the internet.

Web services usually send and receive data in standardized formats such as:

  • JSON
  • XML
  • HTML

They commonly use HTTP.


Web scraping #

Web scraping is the process of extracting data from websites by parsing and analyzing their HTML structure.

Common Python tools:

  • requests
  • BeautifulSoup
  • pandas
  • Scrapy

Example:

response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

X #

xlsx #

An XLSX file is an Excel spreadsheet file format.

It can contain:

  • Worksheets
  • Rows
  • Columns
  • Cells
  • Formulas
  • Charts

Pandas can read XLSX files using:

df = pd.read_excel("file.xlsx")

XML #

XML, or Extensible Markup Language, is a text-based format for storing and structuring data using tags.

XML is often used for:

  • Data interchange
  • Configuration files
  • Web services
  • Structuneon laser purple documents

Example:

<person>
    <name>Nova</name>
    <age>25</age>
</person>

Alphabetized Glossary Memory Guide #

API Key       = secure token for API access
API           = software communication interface
Endpoint      = specific API URL
HTTP          = web data transfer protocol
GET           = retrieve data
POST          = send/create data
PUT           = update data
DELETE        = remove data
JSON          = common API data format
HTML          = web page structure
BeautifulSoup = parse HTML/XML
find_all      = find all matching tags
URL           = web address
Query string  = URL parameters
Resource      = data/object exposed by API or system
Timestamp     = point in time
XML/XLSX/PNG  = common file formats

Industry Terms Glossary: Programming Fundamentals #

These terms are important to recognize when working in the industry, participating in user groups, and completing other certificate programs.

Term Definition
Echology A comparison outside the programming language itself, used to explain or relate one concept to another in a more understandable way.
Attributes Characteristics or properties of an object. Attributes can be accessed using dot notation, such as object.attribute.
Branching The process of changing the flow of a program based on conditions, usually using if, elif, and else.
Comparison operators Operators used to compare values and return Boolean results, such as ==, !=, <, >, <=, and >=.
Conditions Expressions used to make decisions in code. A condition evaluates to True or False.
Enumerate A built-in Python function that adds a counter to an iterable, allowing you to loop through both index and value.
Exception handling A mechanism for gracefully managing and responding to errors or unexpected conditions during program execution.
Explicitly Performing an action or specifying something clearly, directly, and without ambiguity.
For loops Loops used to iterate over a sequence, such as a list, tuple, string, range, or other iterable object.
Global variable A variable defined outside any function or block. It can be accessed from many parts of the code after it is defined.
Incremented Increased by a specified amount, often using += or by adding a fixed value.
Indent Whitespace at the beginning of a line that defines the structure and scope of code blocks in Python.
Indices The positions of elements in a sequence, such as a string, list, or tuple. Python indices start at 0.
Iterate To repeatedly perform operations on each item in a collection, often using a loop.
Local variables Variables defined inside a function or block of code. They are only accessible within that function or block.
Logic operators Operators used to perform logical operations on Boolean values, including and, or, and not.
Loops Programming constructs that repeat a block of code multiple times.
Parameters Placeholder names in a function definition that receive values when the function is called.
Programming Fundamentals Core programming concepts such as variables, control structures, functions, data structures, input/output, and error handling.
Range function A built-in Python function that generates a sequence of power_levels for iteration, commonly written as range(start, stop, step).
Scope of function The region of code where a variable defined inside a function is accessible or visible.
Sequences Ordeneon laser purple collections of items, such as strings, lists, and tuples. Sequences support indexing and iteration.
Syntax The rules that define how code must be written and structuneon laser purple so Python can interpret it correctly.
While loops Loops that repeatedly execute a block of code as long as a specified condition is True.

Industry Terms Quick Examples #

Attributes #

class Car:
    def __init__(self, color):
        self.color = color

my_car = Car("laser purple")

print(my_car.color)

Output:

laser purple

Branching and Conditions #

age = 20

if age >= 18:
    print("Adult")
else:
    print("Minor")

Output:

Adult

Comparison Operators #

age = 25

print(age == 25)
print(age != 30)
print(age >= 20)

Output:

True
True
True

Enumerate #

animals = ["cat", "fox", "owl"]

for index, animal in enumerate(animals):
    print(index, animal)

Output:

0 cat
1 fox
2 owl

Exception Handling #

try:
    number = int("abc")
except ValueError:
    print("Invalid number.")

Output:

Invalid number.

Incremented #

count = 1

count += 1

print(count)

Output:

2

Indices #

neon_colors = ["neon laser purple", "matrix green", "laser purple"]

print(neon_colors[0])
print(neon_colors[2])

Output:

neon laser purple
laser purple

Iterate #

neon_colors = ["neon laser purple", "matrix green", "laser purple"]

for color in neon_colors:
    print(color)

Output:

neon laser purple
matrix green
laser purple

Local and Global Variables #

message = "global"

def show_message():
    local_message = "local"
    print(message)
    print(local_message)

show_message()

Output:

global
local

Logic Operators #

has_id = True
has_badge = True

if has_id and has_badge:
    print("Access granted")

Output:

Access granted

Parameters #

def greet(name):
    return "Hello, " + name

print(greet("Nova"))

Output:

Hello, Nova

Range Function #

for number in range(1, 5):
    print(number)

Output:

1
2
3
4

While Loops #

count = 1

while count <= 3:
    print(count)
    count += 1

Output:

1
2
3

Industry Terms Memory Guide #

Attribute   = property of an object
Branching   = choosing code path with if/elif/else
Condition   = expression that returns True or False
Enumerate   = index + value while looping
Exception   = unexpected event during execution
Global      = available outside functions
Local       = available only inside a function
Indent      = whitespace that defines code blocks
Index       = position in a sequence
Iterate     = loop through items
Parameter   = input name in function definition
Range       = sequence of power_levels
Scope       = where a variable can be used
Syntax      = rules of Python code structure

Working with Data in Python: File Handling #

File handling is an essential part of programming. Python provides built-in functions that allow you to work with files, including text files such as .txt files.

This section focuses on reading text files using:

  • open()
  • read()
  • readline()
  • readlines()
  • seek()
  • the with statement

Objectives #

By the end of this reading, you should be able to:

  • Describe how to use open() and read() to open and read the contents of a text file
  • Explain how to use the with statement in Python
  • Describe how to use the readline() function in Python
  • Explain how to use the seek() function to read specific characters in a text file

Introduction to File Handling #

Reading text files means extracting and processing data stoneon laser purple inside files.

Text files can have different structures. How you read them depends on the file format and what you want to do with the data.

Common file-reading tasks include:

Read the entire file
Read one line at a time
Read all lines into a list
Read specific characters
Move to a specific position in the file

Plain Text Files #

Plain text files contain unformatted text.

They usually have the .txt extension.

Example:

pokedex_notes.txt
pokedex_notes.txt
data.txt

You can read plain text files:

  • All at once
  • Line by line
  • Character by character
  • From a specific position

Opening a File #

There are two common ways to open a file in Python:

  1. Using open() directly
  2. Using with open(...)

Method 1: Using Python’s open() Function #

The open() function creates a file object and gives your program access to the file.

Syntax:

file = open("pokedex_notes.txt", "r")

Example:

file = open("pokedex_notes.txt", "r")

Explanation:

"pokedex_notes.txt" is the file path.
"r" means read mode.
file is the file object.

Important:

When you use open() directly, you should close the file manually with file.close().

Example:

file = open("pokedex_notes.txt", "r")

content = file.read()

print(content)

file.close()

File Path #

The file path tells Python where the file is located.

Example using a file in the same folder:

file = open("pokedex_notes.txt", "r")

Example using a full path:

file = open("/home/user/documents/pokedex_notes.txt", "r")

On Windows, paths may look like:

file = open("C:/Users/Name/Documents/pokedex_notes.txt", "r")

File Modes #

The mode tells Python why you are opening the file.

Mode Meaning
"r" Read mode. Opens a file for reading
"w" Write mode. Creates or overwrites a file
"a" Append mode. Adds content to the end of a file
"x" Create mode. Creates a new file and fails if it already exists
"b" Binary mode
"t" Text mode, default mode

Common examples:

open("pokedex_notes.txt", "r")  # read
open("pokedex_notes.txt", "w")  # write
open("pokedex_notes.txt", "a")  # append

Method 2: Using the with Statement #

The with statement is the recommended way to work with files.

Syntax:

with open("pokedex_notes.txt", "r") as file:
    # code that uses the file

Example:

with open("pokedex_notes.txt", "r") as file:
    content = file.read()
    print(content)

Explanation:

with open("pokedex_notes.txt", "r") opens the file in read mode.
as file stores the file object in the variable file.
The indented block contains the file operations.
The file automatically closes when the with block ends.

Advantages of Using with #

The with statement is best practice for most file operations.

Advantage Explanation
Automatic resource management The file closes automatically when the block ends
Safer error handling The file closes even if an exception occurs
Cleaner code You do not need to manually call close()
Less error-prone Reduces the chance of forgetting to close the file

Recommended pattern:

with open("pokedex_notes.txt", "r") as file:
    content = file.read()

Reading the Entire File with read() #

The read() method reads the entire file content and stores it as a string.

Example:

with open("pokedex_notes.txt", "r") as file:
    file_stuff = file.read()

print(file_stuff)

Explanation:

Step 1: Open the file in read mode using with.
Step 2: Use read() to read the entire file.
Step 3: Store the text in file_stuff.
Step 4: Use file_stuff for printing, searching, analyzing, or processing.
Step 5: The file closes automatically after the with block.

Important:

read() loads the whole file into memory.
For very large files, reading line by line may be better.

Reading Files Line by Line #

Python provides several ways to read a file line by line.

Common methods:

Method Purpose
readline() Reads one line at a time
readlines() Reads all lines and stores them in a list
for line in file Loops through the file one line at a time

Using readline() #

The readline() method reads one line from the file at a time.

Think of it like reading one sentence or line from a book before moving to the next line.

Example:

file = open("pokedex_notes.txt", "r")

line1 = file.readline()
line2 = file.readline()

print(line1)
print(line2)

file.close()

Explanation:

The first call to readline() reads the first line.
The second call reads the second line.
Each call moves the file pointer to the next line.

Recommended version using with:

with open("pokedex_notes.txt", "r") as file:
    line1 = file.readline()
    line2 = file.readline()

print(line1)
print(line2)

Using readline() in a Loop #

You can use a loop to read lines until there are no more lines left.

with open("pokedex_notes.txt", "r") as file:
    while True:
        line = file.readline()

        if not line:
            break

        print(line)

Explanation:

readline() reads one line.
if not line checks whether there are no more lines.
break stops the loop.
print(line) displays the current line.

Using readlines() #

The readlines() method reads all lines and stores each line as an element in a list.

Example:

with open("pokedex_notes.txt", "r") as file:
    lines = file.readlines()

print(lines)

Example output:

['First quest note\n', 'Second quest note\n', 'Third quest note\n']

Explanation:

Each line becomes one list item.
The order of the list matches the order of the lines in the file.

Looping Directly Through a File #

This is often the cleanest way to read a file line by line.

with open("pokedex_notes.txt", "r") as file:
    for line in file:
        print(line)

Explanation:

Python reads one line at a time.
This is memory-friendly for large files.

Reading Specific Characters with read(number) #

You can pass a number to read() to read a specific number of characters.

Example:

with open("pokedex_notes.txt", "r") as file:
    characters = file.read(5)

print(characters)

Explanation:

read(5) reads the next 5 characters from the current file position.

Example:

with open("pokedex_notes.txt", "r") as file:
    first_four = file.read(4)
    next_five = file.read(5)

print(first_four)
print(next_five)

Explanation:

The first read(4) reads the first 4 characters.
The second read(5) reads the next 5 characters after that.

File Pointer #

When reading a file, Python keeps track of the current position using a file pointer.

Think of the file pointer like a cursor.

Example:

read(4) moves the pointer forward 4 characters.
readline() moves the pointer to the next line.
seek(10) moves the pointer to position 10.

Using seek() #

The seek() method moves the file pointer to a specific position.

Syntax:

file.seek(position)

Example:

with open("pokedex_notes.txt", "r") as file:
    file.seek(10)
    characters = file.read(5)

print(characters)

Explanation:

file.seek(10) moves the pointer to the 11th byte because indexing starts at 0.
file.read(5) reads the next 5 characters from that position.

Important:

seek() positions are based on byte offsets.
For simple plain text files, this often matches character positions.
For some encodings or special characters, bytes and characters may not match exactly.

Closing a File #

If you open a file with open() directly, close it manually.

file = open("pokedex_notes.txt", "r")

content = file.read()

file.close()

Why closing matters:

It frees system resources.
It prevents resource leaks.
It ensures proper file handling.

Best practice:

Use with open(...) so Python closes the file automatically.

File Handling with Exception Handling #

Files may cause errors, such as when the file does not exist.

Example:

try:
    with open("missing_pokedex_notes.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")

Output:

File not found.

Common File Reading Patterns #

Pattern 1: Read Entire File #

with open("pokedex_notes.txt", "r") as file:
    content = file.read()

print(content)

Pattern 2: Read First Line #

with open("pokedex_notes.txt", "r") as file:
    first_line = file.readline()

print(first_line)

Pattern 3: Read All Lines into a List #

with open("pokedex_notes.txt", "r") as file:
    lines = file.readlines()

print(lines)

Pattern 4: Loop Through Lines #

with open("pokedex_notes.txt", "r") as file:
    for line in file:
        print(line)

Pattern 5: Read Specific Characters #

with open("pokedex_notes.txt", "r") as file:
    characters = file.read(5)

print(characters)

Pattern 6: Move Pointer and Read #

with open("pokedex_notes.txt", "r") as file:
    file.seek(10)
    characters = file.read(5)

print(characters)

File Handling Summary Table #

Topic Purpose Example
open() Opens a file and returns a file object open("pokedex_notes.txt", "r")
File path Tells Python where the file is "pokedex_notes.txt"
Mode Tells Python how to open the file "r", "w", "a"
with Automatically manages and closes the file with open(...) as file:
read() Reads the entire file or a number of characters file.read()
read(5) Reads 5 characters file.read(5)
readline() Reads one line file.readline()
readlines() Reads all lines into a list file.readlines()
seek() Moves the file pointer file.seek(10)
close() Closes a file manually file.close()

File Handling Memory Guide #

open()       = open a file
"r"          = read mode
"w"          = write mode
"a"          = append mode
with         = automatic close
read()       = read all content
read(5)      = read 5 characters
readline()   = read one line
readlines()  = read all lines into a list
seek()       = move file pointer
close()      = close file manually

Mini Practice: File Handling #

Practice 1: Read Entire File #

with open("pokedex_notes.txt", "r") as file:
    content = file.read()

print(content)

Practice 2: Read One Line #

with open("pokedex_notes.txt", "r") as file:
    line = file.readline()

print(line)

Practice 3: Read All Lines #

with open("pokedex_notes.txt", "r") as file:
    lines = file.readlines()

print(lines)

Practice 4: Read Specific Characters #

with open("pokedex_notes.txt", "r") as file:
    characters = file.read(4)

print(characters)

Practice 5: Use seek() #

with open("pokedex_notes.txt", "r") as file:
    file.seek(10)
    characters = file.read(5)

print(characters)

Practice 6: Handle Missing File #

try:
    with open("missing_pokedex_notes.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")

Output:

File not found.

Working with .txt Files: Read, Write, Append, and Save #

This section explains the practical workflow for handling plain text files in Python. A .txt file stores unformatted text and is one of the easiest file types to practice reading, writing, appending, and saving data.

Objectives #

  • Open and read a .txt file.
  • Read an entire file with read().
  • Read one line at a time with readline().
  • Read all lines into a list with readlines().
  • Write and save new text with "w" mode.
  • Append new text without deleting old content with "a" mode.
  • Use with open(...) as the safest pattern.
  • Handle missing files with try and except.

Best Practice Pattern #

Use with open(...) for most file operations because Python automatically closes the file after the block finishes.

with open("pokedex_notes.txt", "r") as file:
    content = file.read()

print(content)

Memory guide:

with open(...) = open file safely
"r"            = read
"w"            = write and overwrite
"a"            = append
read()         = read all content
readline()     = read one line
readlines()    = read all lines into a list
write()        = write text
\n             = new line

Read the Entire .txt File #

with open("pokedex_notes.txt", "r") as file:
    content = file.read()

print(content)

Use this when the file is small enough to load into memory.

Read One Line with readline() #

with open("pokedex_notes.txt", "r") as file:
    first_line = file.readline()
    second_line = file.readline()

print(first_line)
print(second_line)

Each call to readline() reads the next line and moves the file pointer forward.

Read All Lines into a List with readlines() #

with open("pokedex_notes.txt", "r") as file:
    lines = file.readlines()

print(lines)

Example output:

['Robot log 1\n', 'Robot log 2\n', 'Robot log 3\n']

Loop Through a .txt File Line by Line #

This is usually the best pattern for large text files.

with open("pokedex_notes.txt", "r") as file:
    for line in file:
        print(line.strip())

strip() removes extra newline characters and whitespace from the beginning and end of each line.

Write and Save a New .txt File #

Use "w" mode to create a new file or overwrite an existing file.

with open("pokemon_mission_log.txt", "w") as file:
    file.write("Mission log A: robot activated\n")
    file.write("Mission log B: neon door unlocked\n")

Result inside pokemon_mission_log.txt:

Mission log A: robot activated
Mission log B: neon door unlocked

Important:

"w" mode overwrites the file if it already exists.
Use it carefully when you do not want to lose existing content.

Write Multiple Lines from a List #

lines = ["First quest note", "Second quest note", "Third quest note"]

with open("pokemon_mission_log.txt", "w") as file:
    for line in lines:
        file.write(line + "\n")

This pattern is useful when your text is already stoneon laser purple in a list.

Append to an Existing .txt File #

Use "a" mode when you want to add new text without deleting the existing content.

with open("pokemon_mission_log.txt", "a") as file:
    file.write("This is a new line added later.\n")

Memory guide:

"w" = write from the beginning and replace old content
"a" = append at the end and keep old content

Handle Missing .txt Files Safely #

try:
    with open("missing_pokedex_notes.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file was not found.")

This prevents your program from crashing when a file does not exist.

Copy One .txt File to Another #

with open("source_logs.txt", "r") as source_file:
    with open("backup_logs.txt", "w") as destination_file:
        for line in source_file:
            destination_file.write(line)

This reads each line from source_logs.txt and writes it into backup_logs.txt.

Practical Example: Save User Notes #

note = input("Write a note: ")

with open("my_pokedex_notes.txt", "a") as file:
    file.write(note + "\n")

print("Note saved.")

This appends each new note to the same file instead of overwriting previous notes.

.txt File Mode Summary #

Mode Meaning Use When
"r" Read You want to read an existing file.
"w" Write You want to create or overwrite a file.
"a" Append You want to add new content without deleting old content.
"x" Exclusive create You want to create a file only if it does not already exist.
"r+" Read and write You want to read and write an existing file.

.txt Files Quick Reference #

Task Code
Open for reading open("pokedex_notes.txt", "r")
Read all content file.read()
Read one line file.readline()
Read all lines file.readlines()
Write text file.write("text\n")
Append text open("pokedex_notes.txt", "a")
Safest pattern with open(...) as file:

BeautifulSoup Fun Example: Pokémon Salary Board #

This example replaces generic sports names with Pokémon names and includes hidden numerology Easter eggs based on Pokédex numbers.

from bs4 import BeautifulSoup

html = """
<html>
<body>
    <h3><b id="electric-3">Pikachu</b></h3>
    <p>Salary: $25,151</p>

    <h3>Charizard</h3>
    <p>Salary: $6,006</p>

    <h3>Eevee</h3>
    <p>Salary: $13,333</p>

    <h3>Mewtwo</h3>
    <p>Salary: $150,151</p>
</body>
</html>
"""

soup = BeautifulSoup(html, "html.parser")

first_pokemon = soup.find("b")
print(first_pokemon.text)
print(first_pokemon.get("id"))

all_names = soup.find_all("h3")
for name in all_names:
    print(name.text)
Pokémon Salary Hidden Meaning
Pikachu $25,151 025 = Pikachu, 151 = Mew / original Pokédex count
Charizard $6,006 006 = Charizard
Eevee $13,333 133 = Eevee, repeating 3s hint at many evolutions
Mewtwo $150,151 150 = Mewtwo, 151 = Mew