0% found this document useful (0 votes)
8 views127 pages

1.PythonFundmentals 1 127

The document outlines a Python workshop series focusing on Python fundamentals, including its popularity, basic concepts, and setting up a development environment. It emphasizes Python's readability, simplicity, versatility, and extensive library ecosystem, particularly in the field of Geomatics. The workshop will cover Python basics, including comments, literals, data types, and creating a first program, using tools like Anaconda, Jupyter Notebook, and Spyder IDE.

Uploaded by

mehrm8113
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views127 pages

1.PythonFundmentals 1 127

The document outlines a Python workshop series focusing on Python fundamentals, including its popularity, basic concepts, and setting up a development environment. It emphasizes Python's readability, simplicity, versatility, and extensive library ecosystem, particularly in the field of Geomatics. The workshop will cover Python basics, including comments, literals, data types, and creating a first program, using tools like Anaconda, Jupyter Notebook, and Spyder IDE.

Uploaded by

mehrm8113
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON FUNDAMENTALS

UNB-GGE PYTHON WORKSHOP SERIES 1

William Liu
Department of Geodesy and Geomatics Engineering
University of New Brunswick
July 2023
Agenda
1. Why Python?
2. Python Overview
3. Setting up Your Development Environment
4. Python Basics
4.0 Comments
4.1 Literals
4.2 Variables
4.3 Operators
4.4 Control Structures
4.5 Data Types
NoneType
Numeric Types: int, float, bool, complex
Sequential Types: str, list, tuple,
Mapping and Set Types: set, dict
4.6 Functions
4.7 Classes, Objects, and Methods
4.8 Packages and Modules
5. Creating Your First Python Program
6. Assignment

2
1. Why Python?

Understand why we choose Python


1. Why Python?
TIOBE Programming Community index: an indicator of the popularity of programming languages.
The index can be used to check whether your programming skills are still up to date or to decide strategically what
programming language should be adopted when starting to build a new software system.

Figure source: [Link] 4


1. Why Python?
A recent survey (link) by the “Stack Overflow” website reveals Python’s popularity among professional developers.

Figure source: [Link] 5


1. Why Python?
Why is Python so popular?
• Readability: Python’s syntax is easy to read and
understand, making it a brilliant choice for all levels
of programmers.
• Simplicity: Python allows developers to express
ideas using fewer lines of code than other
languages.
• Versatility: Python is multi-functional, with
applications for web development, data analysis, AI,
scientific computing, automation, etc.
• Large and Active Community: The Python
programming language benefits from a diverse and
active community of developers who contribute a
wealth of resources, including libraries, frameworks,
and support. This fosters a culture of collaboration,
knowledge sharing, and ongoing improvement of
the language.

6
1. Why Python?
Why is Python so popular?
• Cross-platform Compatibility: Python is available on
various platforms, such as Windows, macOS, Linux,
and has consistent behavior across different
operating systems.
• Extensive Library Ecosystem: Python offers a vast
collection of libraries and frameworks, such as
NumPy, Pandas, Django, TensorFlow, and Flask,
which simplify development tasks and accelerate
the creation of complex applications.
• Integration Capabilities: Python can easily integrate
with other languages and systems, allowing
developers to leverage existing code and
infrastructure seamlessly.
• Career Opportunities: Python's popularity has led
to high demand for Python developers in the job
market, making it a valuable skill for career
advancement.

7
1. Why Python?
Python in the Field of Geomatics
An article (link) in the Gogeomatics website ranked Python as the No 1 programming language in the GIS world:
“Python can be compared to the Swiss army knife for GIS.”

Python is the leading programming language in the GIS world and here are some reasons why:

• Wide Range of Geospatial Libraries: Python has many powerful libraries for working with geospatial data,
including GDAL, Fiona, GeoPandas, Shapely, and PyProj. These tools allow for reading and writing spatial
file formats, performing spatial analysis, handling projections, visualizing geospatial data, and processing
remote sensing imagery.
• Data Analysis and Visualization: Python libraries like NumPy, Pandas, and Matplotlib are great for
geospatial data analysis, manipulation, and visualization.
• Integration with GIS Software: Python works well with GIS software like QGIS and ArcGIS, allowing users to
create custom tools, automate workflows, and access APIs.
• Open Source and Community Support: Python is open-source and has a strong community of geospatial
professionals who contribute to its development and provide support through various online resources.
• Cross-Domain Integration: Python is a popular choice for interdisciplinary projects involving geospatial
data as it easily integrates with remote sensing, data science, machine learning, and web development.

8
2. Python Overview

Understand basic Python concepts


2. Python Overview
Python is an interpreted programming language that differs from the traditional compiled programming language
such as C/C++, C#, and Java.

From a user’s point of view:


Separate compilation process
Compiled
language

Interpreted
language

No separate compilation process, the


interpreter compiles source code on the fly

Figure source: [Link] 10


2. Python Overview
Python Concepts

Python Program Python program is executed by the interpreter

Python Distribution The interpreter abstracts away from the operating system and the
hardware details by providing a uniform programming interface,
handling low-level operations, and ensuring platform independence
Python Interpreter
The interpreter can be extended with C programs by
Standard Library Python API C Program
using the Python API for time-critical applications

The standard library provides powerful and easy-


Operating System to-use functionalities to the Python program

Hardware

11
2. Python Overview
Python Program
Each Python program may contain one or many Python script files. Let’s examine a simple example that only
consists of one Python file:
“Suppose we have a text file named [Link] containing multiple lines of integer numbers. We separate the numbers
from others with a space in the file. Write a Python script file to find the maximum number from the file and then output it
to the screen.”
Read the left script first. If you really need some
explanations, read the right one with comments
(Note: anything following the # symbol on the same line will be considered a
comment and will not be executed by the Python interpreter).

Without comments With comments 12


2. Python Overview
Compare the corresponding C program implementing the same functionality

Without comments With comments 13


2. Python Overview
Python Program

Now, think about the Readability and


Simplicity of the Python language. Are
you convinced of what we claimed
before?

14
2. Python Overview
Python Interpreter
Popular Python interpreter implementations

• CPython: The default and widely used Python interpreter, known for its performance,
stability, and extensive library support.

• PyPy: A faster and more memory-efficient alternative to CPython, featuring a Just-in-


Time (JIT) compiler for performance improvements.

• Jython: Python implementation running on the Java Virtual Machine (JVM), allowing
seamless integration with Java code and libraries.

• IronPython: Python implementation targeting the .NET Framework, enabling Python


and other .NET languages to work together.

• MicroPython: Lightweight Python implementation for microcontrollers and


embedded systems with a small footprint.

This workshop will focus on the default and reference implementation of the Python interpreter – CPython.
15
2. Python Overview
Python Distribution
A pre-packaged bundle of the Python programming language, along with additional tools, libraries, and
resources that make it easier to develop, run, and distribute Python applications.

The official Python installation file provided by [Link] commonly


referred to as "CPython," can be considered a minimal Python distribution. It includes
the core Python interpreter, the standard library, and essential tools for running Python
code. It serves as the base from which other distributions are built.

Python Interpreter Standard Library Development Tools


Interactive CMD-line interface I/O, networking, math… Python package installer – pip,
virtual environment – venv…

Integrated Development and


Learning Environment (IDLE) Comprehensive Documentation
Code editor, Debugging, Python shell… Language reference, STL doc, tutorials…

Official Python Distribution Components


16
2. Python Overview
Popular Python Distributions

• Anaconda: Comprehensive data science distribution with package management (conda).

• Miniconda: Minimal version of Anaconda with conda package manager.

• Python(x,y): Scientific computing distribution with key packages.

• Enthought Canopy: Python distribution for scientific and analytic computing.

• ActivePython: Commercial distribution with enterprise support.

• WinPython: a free open-source portable Python distribution for Windows and scientific
and educational usage.

This workshop will focus on the most popular Anaconda distribution for data science
17
2. Python Overview
Anaconda Components

• A graphical user interface (GUI)


for Python package management

• A tool helps manage and


reproduce data science projects

• Includes the CPython interpreter


• An interactive web-based
environment - Jupyter Notebook
• Spyder IDE
• Popular data science packages
• Additional tools and libraries

• Create isolated environments


• Manage dependencies
• Install/update/remove packages

18
3. Setting up Your Development
Environment

Prepare your coding tools


3. Setting up Your Development Environment
Install Anaconda
Download a version of Anaconda for your computer:
[Link]

• Choose the default options to install Anaconda

Note: this workshop will only focus on the Windows platform


20
3. Setting up Your Development Environment
Test Anaconda Installation Here I launched the command-line interface
of the standard Python interpreter. It’s also
Launch Anaconda [Link] Prompt from within Anaconda Navigator: called the interactive mode, which allows
you to interactively write and run Python
(alternatively: Windows Start ➔ Anaconda3 ➔ Anaconda Prompt)
code statements, providing immediate
feedback and results.

1. Input python on the CMD line and press Enter key

2. Input print(“Hello World”) and press Enter key

21
3. Setting up Your Development Environment
Test Anaconda Installation
Launch Spyder Integrated Development Environment (IDE) from within Anaconda Navigator:

• Open-source IDE for scientific computing and data analysis in Python.


• User-friendly interface with the IPython console and data exploration tools. IPython is an interactive
command-line shell for
• Supports popular scientific libraries, code auto-completion, and debugging. Python that provides
• Cross-platform compatibility (Windows, macOS, Linux). enhancements over the
• Suitable for beginners and experienced users of scientific computing. standard Python interpreter.

22
3. Setting up Your Development Environment
Test Anaconda Installation
Launch Jupyter Notebook from within Anaconda Navigator:
What is Jupyter Notebook?

• Web-based interface for creating interactive


computational documents.
• Supports multiple programming languages, with Python
being popular.
• Combines code cells and text cells using Markdown.
• Enables interactive data analysis, prototyping, and
storytelling.
• Features syntax highlighting, code execution, and inline
output display.
• Supports creation of interactive visualizations and plots.
• Facilitates collaboration and sharing of notebooks in
various formats.
• Integrates with scientific libraries and data analysis
tools.
• Has a large and active community with extensive
documentation. 23
3. Setting up Your Development Environment

Jupyter Notebook usage examples

24
3. Setting up Your Development Environment

Jupyter Notebook How to use?

Watch the following introduction video to learn the basics of Jupter Notebook (15 mins), and then come back.
Jupyter Notebook Tutorial for Beginners with Python by Dave Gray ( [Link] )

25
3. Setting up Your Development Environment

Create a new notebook with Python 3


1. Input your Python code here
New ➔ Python 3

2. Click Run

Please keep this browser window


open while you are attending the
workshop. Try the code examples in 3. The output result
the following sections with this new
notebook.

4. Input your new Python code


26
3. Setting up Your Development Environment

For any reason, if you could not use your local version of Jupyter Notebook:

• If you have a UNB ID, you can log in to the cloud-based Jupyter Notebook by Digital Research Alliance of Canada:
[Link]

• Otherwise, you can register an account at Anaconda, and use their cloud-based version.
[Link]

27
4. Python Basics

Learn the basics of Python


4. Python Basics
A sample Python script
This script demonstrates:
• Variable assignment and data types
• Conditional statement (if-else)
• Looping statement (for loop)
• Function definition and function call
• Class definition and instantiation
• Method calls

Try to read and understand this simple


Python script.
• If you have prior programming
experience, it will give you an initial
impression of what Python language
looks like.
• If you don’t have any experience at
all, don’t worry. We will cover them
all in the following sessions.

29
4. Python Basics
4.0 Comments
Comments can make code more understandable and easier to maintain.

1. Single-line comment: Example


# This is a single-line comment # Calculate the sum of two numbers
num1 = 10
2. Multi-line comment (using triple quotes): num2 = 20
sum = num1 + num2
"""
This is a def calculate_area(length, width):
multi-line comment """
""" Calculates the area of a rectangle.
3. Multi-line comment (using multiple single-line comments): Parameters:
# This is a length (float): The length of the rectangle.
# multi-line comment width (float): The width of the rectangle.

Returns:
float: The area of the rectangle.
"""
area = length * width
return area

30
4. Python Basics
4.1 Literals
In Python, literals are values that are directly represented in code.
Basic type literals
[Link] Literals:
• Integer literals: Whole numbers (e.g., 5, -10, 0).
• Floating-point literals: Numbers with decimal points (e.g., 3.14, -0.5).
• Complex literals: Numbers with imaginary parts (e.g., 2+3j, -1j).
[Link] Literals:
• Enclosed in single quotes ('...') or double quotes ("...").
• Examples: 'Hello', "Python", "123", 'Special characters: !@#$'. Note: Python is case-sensitive!
[Link] Literals: So, True != true != TRUE
• Two possible values: True and False.
[Link] Literal:
• The special value None represents the absence of a value or a null value.

Literal Type Example Description


Numeric Literals 5, 3.14, 2+3j Represent numerical values
String Literals 'Hello', "Python" Represent sequences of characters
Boolean Literals True, False Represent logical values (True or False)
None Literal None Represents the absence of a value or null
31
4. Python Basics
4.1 Literals
In Python, literals are values that are directly represented in code.

Collection literals
[Link] Literals: Literal
• Enclosed in square brackets ([]). Type Example Description
• Examples: [1, 2, 3], ['apple', 'banana', 'cherry'], [True, False].
Ordered collection
[Link] Literals: List Literals [1, 2, 3]
of elements
• Enclosed in parentheses (()) or without any brackets.
• Examples: (1, 2, 3), 'apple', 'banana', 'cherry'. Ordered collection
Tuple
[Link] Literals: (1, 2, 3) or 1, 2, 3 of immutable
Literals
• Enclosed in curly braces ({}) with key-value pairs. elements
• Examples: {'name': 'John', 'age': 25}, {'fruit': 'apple', 'color': 'red'}. Dictionary Collection of key-
{'name': 'John', 'age': 25}
[Link] Literals: Literals value pairs
• Enclosed in curly braces ({}) or created using the set() constructor. Unordered
• Examples: {1, 2, 3}, {'apple', 'banana', 'cherry'}, set([True, False]). Set Literals {1, 2, 3} collection of
unique elements

Don’t worry if you don’t understand it for now.


This page is just for the completeness of literals
32
4. Python Basics
4.1 Literals
What will happen to a literal declared in Python? An integer literal: 25

Identity 1349065
When a literal is encountered in a Python program, the Python
interpreter creates the corresponding object in memory. Each object Type int
has three properties: Value 25

• Identity: Each object occupies a specific memory address. In


Python, an object’s identity is determined by its memory address. Identity 1349050
• Type: The type determines the behavior and allowed values of
the object. Type str
• Value: The literal’s content Value John

Memory
A string literal: “John”

33
4. Python Basics
4.1 Literals
What will happen to a literal declared in Python?

Identity 1349065
To access the created literals in memory, we need to reference them to
continue using their values. We can use the assignment operator = to age Type int
create a reference to the object. Value 25
name = "John"
age = 25
Identity 1349050
name and age are the symbolic identifiers used for referencing objects
name Type str
and are usually called variable names.
Value John
Variable in Python is the conceptual container or entity that holds a
reference to an object.
Memory
Although variable and variable name are often used interchangeably,
it’s helpful to be aware of this distinction.

34
4. Python Basics
4.2 Variables
In Python, valid variable names should follow:
1. Valid Characters: Valid variable
• Variable names can consist of letters (both uppercase and lowercase), digits, and underscores (_).
name examples:
• The first character of a variable name cannot be a digit. It must be a letter or an underscore.
2. Case-Sensitivity: name
• Python is case-sensitive, so variable names such as myVar, myvar, and MYVAR are all considered different. age
3. Reserved Keywords: my_var
• Variable names cannot be the same as Python-reserved keywords. Reserved keywords are special words in
total_count
the Python language with predefined meanings and cannot be used as variable names. Examples of
reserved keywords include if, for, while, def, class, import, and others.
student1
4. Descriptive and Meaningful:
• It is good practice to choose variable names that are descriptive and convey the purpose or meaning of the Invalid or not
variable. This improves code readability and maintainability. recommended
5. Avoid Starting with Underscore: variable names:
• Variable names starting with a single underscore (_) have a conventional meaning in Python. They are
considered "weak internal use" and are typically used for special cases or as a hint to indicate that the 23name
variable is intended for internal use within a class or module. totalCount
6. Style Conventions:
• Python has style conventions defined in PEP 8 (Python Enhancement Proposal) that recommend using
lowercase letters for variable names and separating words with underscores (snake_case). This
convention helps to improve code readability and consistency.
class
nnnnn
?
35
4. Python Basics
4.2 Variables
Reserved keywords that can’t be used as variable names:

Reserved Keywords
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

36
4. Python Basics
4.2 Variables
• Python has no command for declaring a variable
A variable is created the moment you first assign a value to it. (as we mentioned
before, in the background, a value/object is referenced by a variable name )
name = "John"
age = 25
• Python is a dynamically typed language, meaning that variables are not explicitly declared with a specific type.
When you create a literal and assign it to a variable, Python infers the variable’s type based on the literal value.
E.g., age = 25, 25 is an integer literal, so Python assigns the int type to the variable age.

• A variable’s type may even be changed later after its initialized


Python infers the variable’s new type based on the new literal value, or the new variable assigned to it. Try
the following statements with your Anaconda [Link] Prompt.

Notice that the variable name was


changed to reference an integer variable
after the assignment statement:
name = age
37
4. Python Basics
4.3 Operators
Python operators enable you to perform various operations, such as performing mathematical operations,
assigning values, comparing values, evaluating logical conditions, manipulating bits, checking membership,
testing identity, and applying unary operations.

Operator Category Operators


Arithmetic Operators +, -, *, /, //, %, **

Assignment Operators =, +=, -=, *=, /=, //=, %=, **=

Comparison Operators ==, !=, >, <, >=, <=


Logical Operators and, or, not
Bitwise Operators &, |, ^, ~, <<, >>
Membership Operators in, not in
Identity Operators is, is not
Unary Operators +, -

38
4. Python Basics
4.3 Operators
Arithmetic operators Assignment operators
Operator Description Example Operator Description Example
+ Addition 2 + 3 equals 5 = Assigns a value to a variable x = 5 assigns 5 to x
- Subtraction 7 - 4 equals 3
+= Adds a value and assigns it x += 3 is equivalent to x = x + 3
* Multiplication 5 * 6 equals 30
-= Subtracts a value and assigns it x -= 2 is equivalent to x = x - 2
/ Division 10 / 2 equals 5.0
*= Multiplies by a value and assigns it x *= 4 is equivalent to x = x * 4
// Floor Division 10 // 3 equals 3
Modulo /= Divides by a value and assigns it x /= 2 is equivalent to x = x / 2
% 10 % 3 equals 1
(Remainder)
** Exponentiation 2 ** 4 equals 16 //= Performs floor division and assigns it x //= 3 is equivalent to x = x // 3

Note: in Python, the result of division / is always a float %= Performs modulo operation and assigns it x %= 5 is equivalent to x = x % 5
number, which is different from C/C++ programs. Floor
division // in Python is like the division / in the latter. **= Performs exponentiation and assigns it x **= 2 is equivalent to x = x ** 2

Note: in Python, there is no


increment ++ and decrement
operators --. You can use the
assignment operator += and -=
to achieve the same results.
39
4. Python Basics
4.3 Operators
Comparison operators Logical operators
Operator Description Example Operator Description Example

== Equal to 5 == 5 evaluates to True and Returns True if both are True True and False evaluates to False
or Returns True if at least one is True True or False evaluates to True
!= Not equal to 7 != 3 evaluates to True
not Returns the opposite not True evaluates to False
> Greater than 10 > 5 evaluates to True
Bitwise operators
< Less than 2 < 6 evaluates to True
Operator Description Example (Binary)
>= Greater than or equal to 8 >= 8 evaluates to True & Bitwise AND 0b1100 & 0b0111 returns 0b0100
<= Less than or equal to 4 <= 3 evaluates to False
| Bitwise OR 0b1100 | 0b0111 returns 0b1111

Unary operators ^ Bitwise XOR (exclusive OR) 0b1100 ^ 0b0111 returns 0b1011

Operator Description Example ~ Bitwise NOT (complement) ~0b1100 returns -0b1101


+ Unary positive +5 returns 5 << Bitwise left shift 0b1010 << 2 returns 0b101000
- Unary negative -7 returns -7
>> Bitwise right shift 0b1010 >> 2 returns 0b10

40
4. Python Basics
4.3 Operators

Membership operators

Operator Description Example


in Evaluates if a value is present in a sequence 'a' in ['a', 'b', 'c'] returns True
not in Evaluates if a value is not present in a sequence 'd' not in ['a', 'b', 'c'] returns True

Identity operators
Operator Description Example
x = 5
is Evaluates if two objects are the same object y = x
x is y returns True
x = 5
is not Evaluates if two objects are not the same y = 10
x is not y returns True

41
4. Python Basics
4.3 Operator Precedence
Python operator precedence determines the order in which operators are evaluated in an expression. When
multiple operators exist in an expression, Python follows a specific order of precedence to evaluate them.
Here's a summary of the operator precedence in Python, from highest to lowest precedence:

Precedence Operators
1 () (Parentheses)
2 ** (Exponentiation)
3 *, /, //, % (Multiplication, Division, Floor Division, Modulo)
4 +, - (Addition, Subtraction)
5 <<, >> (Bitwise Shifts)
6 & (Bitwise AND)
7 ^ (Bitwise XOR)
8 |(Bitwise OR)
9 ==, !=, >, <, >=, <=, is, is not, in, not in (Comparison Operators)
10 not (Logical NOT)
11 and (Logical AND)
12 or (Logical OR)

42
4. Python Basics
4.3 Operator Precedence
Ensure that your code is more readable, maintainable, and less prone to operator precedence-related errors,
follow the best practice:
Best practice:
• Use parentheses for clarity in complex expressions.
# Complex expression without parentheses
result = 2 + 3 * 4 / (5 - 1) ** 2
# Preferred: Complex expression with parentheses for clarity
result = 2 + ((3 * 4) / ((5 - 1) ** 2))
• Follow Python's operator precedence rules.
• Add whitespace for readability.
result = 2+3*4 # Less readable
result = 2 + 3 * 4 # More readable with whitespace

• Break down complex expressions when necessary.


complex_result = (2 + 3 * 4) / (5 - 1) # Complex expression
# Preferred: Breaking down the expression
intermediate_result = 3 * 4
complex_result = (2 + intermediate_result) / (5 - 1)
• Comment on unusual or non-intuitive precedence.
# Non-intuitive precedence: Comment to clarify the order of evaluation
result = (2 + 3) * 4 # Add 2 and 3 first, then multiply by 4
# Unusual precedence: Comment to explain the order of operations
result = (2 + 3) ** 4 # Add 2 and 3 first, then raise the sum to the power of 4 43
4. Python Basics
4.4 Control Structures
Python provides various control structures that enable you to control the flow and execution of your code.
Conditionals
The if statement The if elif statement
if condition: if condition1:
# Code to be executed if the condition is true # Code to be executed if condition1 is true
statement1 statement1
statement2 statement2
# ... # ...
else: elif condition2:
# Code to be executed if the condition is false # Code to be executed if condition1 is false and
statement3 # condition2 is true
statement4 statement3
# ... statement4
# ...
elif condition3:
# Code to be executed if both condition1 and condition2
# are false and condition3 is true
statement5
statement6
# ...
else:
# Code to be executed if none of the above conditions are
# true
statement7
statement8
# ... 44
4. Python Basics
4.4 Control Structures
Python provides various control structures that enable you to control the flow and execution of your code.
Conditionals
A nested if statement
Python control structure formatting: if condition1:
# Outer if block
statement1
• Indentation: Python defines code blocks using statement2
indentation (usually 4 spaces) instead of curly braces ({ }). # ...

Consistent indentation with spaces or tabs is crucial for if condition2:


# Nested if block
proper code structure and readability. (If you use tab, statement3
make sure to set one tab equal to 4 spaces in your editor statement4
# ...
settings) else:
• Indentation Block Marker: The colon ( : ) indicates the # Nested else block
statement5
beginning of an indented code block. It is typically used statement6
# ...
after a statement that requires an indented block, such as
# More statements after the nested if-else blocks
in if, else, elif, for, while, and function definitions. statement7
The code block following the colon must be indented statement8
# ...
consistently to maintain the block structure. else:
# Outer else block
statement9
statement10
# ... 45
4. Python Basics
4.4 Control Structures

Conditionals
Learning by doing is an effective way to master a language. Try
Example 1 each example with your new notebook created before.
x = 5

if x > 0:
print("The value of x is positive.")
else:
print("The value of x is non-positive.")

46
4. Python Basics
4.4 Control Structures

Conditionals
Automatic type conversion Example 3 Comparing two close float numbers
Example 2
x = 5 x = 0.1 + 0.1 + 0.1 # 0.3
y = 3.14 y = 0.3

# Comparing an integer and a float tolerance = 1e-10 # Set your desired tolerance level
if x > y:
print("x is greater than y") if abs(x - y) < tolerance:
elif x < y: print("x is approximately equal to y")
print("x is less than y") else:
else: print("x is not equal to y")
print("x is equal to y")

Avoid using simple equality comparisons (== or !=) due to


When comparing an integer with a float, Python will potential precision issues when comparing close float numbers.
automatically perform type conversion and convert Instead, use a tolerance-based approach by checking if the
the integer to a float for comparison. absolute difference falls within an acceptable range. This accounts
for floating-point limitations and provides more reliable
approximate equality comparisons.
47
4. Python Basics
4.4 Control Structures
Conditionals
Conditional expressions
How to simplify this block? Conditional expression template
if x == 1: value_if_true if condition else value_if_false
var = 20
else:
var = 30 In this template:

• condition represents the expression or condition


var = (20 if x == 1 else 30) that is evaluated.
• value_if_true is the value to be returned if the
The conditional expression provides a concise condition evaluates to True.
way to express a simple conditional statement. • value_if_false is the value to be returned if the
It allows you to make a decision and return condition evaluates to False.
different values based on the outcome of the
condition in a single line of code.

48
4. Python Basics
4.4 Control Structures
Loops
while statement Example 1
while condition: count = 0 Note: print() is a Python
# Code to be executed while the condition is true built-in function to display
statement1 while count < 5: or output text or values to
statement2 print("Count:", count)
# ...
the console. We will
count += 1
introduce functions later.
print("Loop finished.")

for statement Example 2


for item in iterable: my_string = "Hello!"
# Code to be executed for each item in the iterable
statement1 for char in my_string:
statement2 print(char)
# ...

In this template:
• item represents a variable that takes on the value of each item in the iterable object during each iteration Output
of the loop.
• iterable is an object that can be looped or iterated over. It's like a container or a sequence with multiple
elements, such as a list of items, a string of characters, or even a range of numbers. 49
4. Python Basics
4.4 Control Structures
When the break statement is encountered within a
Loops loop, the program flow immediately exits the loop,
Terminate a loop: use the break keyword skipping any remaining iterations or code within the loop.
Example 1 Example 2
count = 0 outer_string = "XYZ"
inner_string = "abc"
while True:
print("Count:", count) for outer_char in outer_string:
count += 1 print("Outer loop:", outer_char)

if count >= 5: for inner_char in inner_string:


break print("Inner loop:", inner_char)

print("Loop finished.") if inner_char == "b":


break

print("Loop finished.")

Note: The break statement only exits the innermost loop in


nested loops. If you have multiple nested loops, the break
statement will break out of the innermost loop and resume the
execution from the next statement outside that loop. 50
4. Python Basics
4.4 Control Structures
Loops
The while-else block to detect a loop break
The while-else block allows you to handle scenarios where you want to perform certain actions if a while loop
completes normally without encountering a break statement.

while condition:
# Code to be executed inside the loop Example
statement1
statement2 my_string = "Hello, World!" my_string[index]
# ... target = “Z" means taking the nth
character of the string.
if break_condition: index = 0 Don’t worry about the
# Code to be executed if break while index < len(my_string): syntax here and the
# condition is met if my_string[index] == target: len() function,
break break which means taking
index += 1 the length of
else: else: my_string.
# Code to be executed if the loop print("Target not found in the string.")
# completes without encountering a break
statement3
statement4
# ...
51
4. Python Basics
4.4 Control Structures
Loops
Use the continue keyword to abort the current iteration
The continue keyword allows you to skip certain iterations of a loop when a particular condition is met. It effectively
aborts the current iteration and proceeds to the next iteration without executing the remaining code within the loop
for that iteration.

Example
my_string = "Hello, World!"

for char in my_string: Notice there is an


if char == ",": empty row, and the
continue “,” sign never got
print(char) printed here
print("Loop finished.")

52
4. Python Basics
4.4 Control Structures
Loops
Use the pass statement as a placeholder for an unimplemented code block
Purpose: The pass statement is used as a placeholder when you need a statement syntactically but don't want to
perform any specific action at that point.
Usage: It is commonly used in situations where you are defining a code block, such as in function or class definitions,
conditional statements, or loops, but you want to skip that block without causing a syntax error.
Example
if condition: my_string = "Hello, World!"
pass # Placeholder, no action needed for now
else: for char in my_string:
# Some code here if char == ",":
statement1 pass # No action needed for commas
statement2 else:
print(char)

print("Loop finished.")

53
4. Python Basics
4.5 Data Types
A data type refers to the category of values that a particular object can have. It determines the kind of operations
that can be performed on the object and the storage format for the data. Some built-in data types in Python
include numeric types (int, float, complex), string (str), boolean (bool), list, tuple, dict, set, and more.
Data Type Description Example Mutability
NoneType Represents the absence of a value result = None Immutable
Numeric Types
int Represents whole numbers x = 5 Immutable
float Represents floating-point numbers pi = 3.14 Immutable
bool Represents binary values of either True or False is_valid = True Immutable
complex Represents complex numbers with real and imaginary parts z = 2 + 3j Immutable
Sequential Types
str Represents a sequence of characters message = "Hello, World!" Immutable
bytes Represents immutable sequences of bytes data = b'Hello' Immutable
tuple Represents an ordered collection of elements coordinates = (10, 20) Immutable
list Represents an ordered collection of elements numbers = [1, 2, 3, 4] Mutable
bytearray Represents mutable sequences of bytes data = bytearray(b'Hello') Mutable
Set and Mapping Types
set Represents an unordered collection of unique elements unique_numbers = {1, 2, 3} Mutable
dict Represents a collection of key-value pairs person = {'name': 'John', 'age': 25} Mutable
frozenset Represents an immutable, unordered collection of unique elements frozen_numbers = frozenset({1, 2, 3}) Immutable
54
4. Python Basics
4.5 Data Types
Objects and Data Types

• In Python, everything is an object, which refers to the concept that all entities in the language, including
values, data structures, functions, and even classes, are objects.
• Every object in Python is an instance of a specific data type or class, and objects are created based on those
data types.

❑ In this example, all these numbers are the instances of the int
type (integer)
200 ❑ The int type specifies the storage format and behaviors of the
instances (numbers)
int • Storage Format: The int type specifies the specific format used to
represent integer numbers in memory. Internally, integer numbers
13869
are stored using a fixed amount of memory, typically 32 bits or 64
bits, depending on the platform.
0 • Behaviors: The int type defines the behaviors and operations
-137 that can be performed on integer numbers. For example, the int
type supports mathematical operations like addition, subtraction,
multiplication, and division and comparison operations like
equality and inequality checks.
55
4. Python Basics
4.5 Data Types
NoneType

The NoneType is a special data type in Python that represents the absence of a value or the lack of a value. It
is commonly associated with the singleton object None, which is a built-in constant. It is often used in
conditional statements or function returns to handle cases where a value is missing or not applicable.

• Singleton Object: None is a unique instance of NoneType in the system.


• Comparisons: Use is operator to check if a variable refers to None.
• Usage: Commonly used to handle missing or non-applicable values.
• Immutable: The value of None cannot be changed once assigned.

Example
name = None In this example, we initialize the variable name with
if name is None: None, indicating that no specific value has been
print("No name provided") assigned yet. We then use the is operator to check if
name is None.

56
4. Python Basics
4.5 Data Types
Numeric Types

All numeric types (int, float, bool, complex) are immutable, meaning that their value cannot be changed
once related objects are created.

Numeric Types: int

Range: The int type can represent a wide range of integer values, limited only by the available memory in the
system. On most platforms, the range of int values is approximately -2^31 to 2^31-1 for 32-bit systems and -
2^63 to 2^63-1 for 64-bit systems.
Example: access the largest and smallest integer constant on your system
• If a memory can hold an integer value
import sys
up to 2^31-1, it would require a
largest_int = [Link] memory capacity of approximately 2
smallest_int = -[Link] - 1 gigabytes (GB) on a 32-bit system;
• To hold an integer up to 2^63-1 on a
# Output: 9223372036854775807 (or platform-dependent) 64-bit system, the memory capacity
print(largest_int) must be around 1,048,576 TB !!!!!
# Output: -9223372036854775808 (or platform-dependent)
print(smallest_int)
57
4. Python Basics
4.5 Data Types
Numeric Types: float

Finite Range: The range of finite float numbers is limited by the specific implementation and the floating-point
format used. In Python, the range is typically from approximately 2.2 x 10^-308 to 1.8 x 10^308 for positive and
negative values.
Not-a-Number (NaN): The floating-point format includes a special NaN (Not-a-Number) value. NaN represents
the result of mathematically undefined or indeterminate operations, such as dividing zero by zero or taking the
square root of a negative number.
Precision limitations: floating-point arithmetic is subject to precision limitations due to the nature of
representing real numbers in a finite format. This can lead to rounding errors and small discrepancies when
calculating float numbers.
import sys Example: access the largest and
smallest float number constant on
largest_float = sys.float_info.max your system
smallest_float = -sys.float_info.max
# Output: 1.7976931348623157e+308 (or platform-dependent)
print(largest_float)
# Output: -1.7976931348623157e+308 (or platform-dependent)
print(smallest_float)

58
4. Python Basics
4.5 Data Types
Numeric Types: bool

In Python, the bool type is considered a numeric type because it shares certain characteristics and behaviors
with other numeric types. It can participate in numeric operations, is internally represented as integers (True
as 1, False as 0), and can be converted to other numeric types.

For each other data type, a specific value is defined as bool False, as listed below. Except these, all other
values are defined as True.
Objects Example Description
False False The boolean value False.
None None The special object representing absence of a value.
Numeric Zero 0, 0.0, 0j Numeric values equal to zero.
Empty Sequences '', [], (), set(), {} Empty sequences like strings, lists, tuples, sets, and dictionaries.

Custom objects that define their own truthiness behavior. They


Empty Objects Custom objects with special "empty" state
evaluate as False when their length or internal state is empty.

59
4. Python Basics
4.5 Data Types
Numeric Types: bool

Other objects can also be converted to By using a logical operator not, the
bool type using the built-in function operand that is defined as False will be
bool(). automatically interpreted as a truth value.

Example 1 Example 2
string = "" string = ""

if bool(string) == False: if not string:


print("The string is empty.") print("The string is empty.")
else: else:
print("The string is not empty.") print("The string is not empty.")

60
4. Python Basics
4.5 Data Types
Numeric Types:

Built-in functions in Python that can be used for converting between numeric data types:

Function Description Example Usage Result


int(x) Converts x to an integer int(3.14) 3
float(x) Converts x to a float float(5) 5.0
complex(real, imag) Creates a complex number with the given real and imaginary parts complex(2, 3) (2+3j)

bin(x) Converts an integer x to a binary string representation bin(10) '0b1010'


oct(x) Converts an integer x to an octal string representation oct(20) '0o24'
hex(x) Converts an integer x to a hexadecimal string representation hex(15) '0xf'
round(x, n) Rounds x to n decimal places round(3.14159, 2) 3.14
abs(x) Returns the absolute value of x abs(-10) 10
divmod(a, b) Returns the quotient and remainder of a divided by b as a tuple divmod(10, 3) (3, 1)
bool(x) Converts x to a boolean value bool(0) False

61
4. Python Basics
4.5 Data Types
Sequential Types

In Python, a sequential type is a data type that represents an ordered sequence of elements. Sequential types
allow accessing and manipulating individual elements within the sequence based on their positions or indices.
Sequential Types
Data Type Description Example Mutability
str Represents a sequence of characters message = "Hello, World!" Immutable
tuple Represents an ordered collection of elements (could be in different types) coordinates = (10, 20) Immutable
list Represents an ordered collection of elements (could be in different types) numbers = [10, 23, 30, 4] Mutable
range Represents a sequence of numbers within a specified range range1 = range(0, 10) Immutable

• str, tuple, and list are general-purpose sequential types used for different purposes. str is used for
working with text, tuple for fixed collections, and list for dynamic collections that can be modified.
• The range type in Python is a special sequential data type that serves a specific purpose. It generates
numbers on-the-fly as they are needed, rather than storing all the numbers explicitly in memory. This makes
range objects memory-efficient, particularly for large ranges. Used primarily for iterating over a specific
range of numbers.

62
4. Python Basics
4.5 Data Types
Sequential Types: Creating new objects The range() function accepts one, two, or three arguments, and
returns an object of the range type, representing a sequence of
# Creating a string numbers that can be iterated over.
greeting = "Hello"
• range(stop): Generates numbers starting from 0 up to
sentence1 = 'Python is a versatile programming language.'
Sentence2 = 'Python is a "versatile" programming language.' stop (exclusive) with a default step size of 1.
• range(start, stop): Generates numbers starting from
# Creating a tuple start up to stop (exclusive) with a default step size of 1.
my_tuple = (1, 2, 3, 4, 5) • range(start, stop, step): Generates numbers
mixed_tuple = ('apple', 3.14, True) starting from start up to stop (exclusive) with a specified
step size.
# Creating a list
my_list1 = [1, 2, 3, 4, 5] # Generating numbers from 0 to 4 (exclusive)
my_list2 = [True, False, True] for num in range(5):
mixed_list = [True, 'apple', 3.14] print(num) # Output: 0, 1, 2, 3, 4

# Creating a range # Generating numbers from 1 to 6 (exclusive)


my_range = range(1, 6) for num in range(1, 6):
custom_range = range(0, 10, 2) print(num) # Output: 1, 2, 3, 4, 5

# Generating even numbers from 2 to 10 (exclusive)


for num in range(2, 10, 2):
print(num) # Output: 2, 4, 6, 8

63
4. Python Basics
4.5 Data Types my_string = "Python"
Sequential Types: Indexing Index from front 0 1 2 3 4 5
Elements P y t h o n
Index from back -6 -5 -4 -3 -2 -1

• Indexing is zero-based: In Python, indexing starts from 0, so the first element in a


sequence has an index of 0, the second element has an index of 1, and so on.

• Positive indexing: You can access elements sequentially using positive indices. For
example, my_list[0] retrieves the first element of the list, my_string[2]
retrieves the third character of the string, and my_tuple[1] retrieves the second
element of the tuple.

• Negative indexing: Python also supports negative indexing, which allows you to access
elements from the end of the sequence. For example, my_list[-1] retrieves the last
element of the list, my_string[-2] retrieves the second-to-last character of the
string, and my_tuple[-3] retrieves the third-to-last element of the tuple.

• Out-of-range indexing: If you try to access an index that is outside the valid range of
indices for the sequence, Python raises an IndexError. For example, attempting to
access my_list[6] when my_list has only 6 elements will result in an IndexError.
64
4. Python Basics
4.5 Data Types The slicing syntax follows a common pattern:
s[start:end:step]
Sequential Types: Operations on objects • start (optional): The index where the slice begins. If omitted,
the slice starts from the beginning (index 0).
1. Indexing: Accessing individual elements by their position using • end (optional, exclusive): The index where the slice ends. The
square brackets []. slice does not include this index. If omitted, the slice goes up
my_string = 'Hello' to the end of the sequence.
my_tuple = (1, 2, 3) • step (optional): The step or increment between elements in
my_list = [True, False, True]
print(my_string[0]) ⟶ Output: 'H' the slice. If omitted, the default step is 1. A positive step
print(my_tuple[2]) ⟶ Output: 3 moves forward through the sequence, while a negative step
print(my_list[1]) ⟶ Output: False moves backward.
2. Slicing: Extracting a subset of elements using a range of indices. my_string = 'Hello World'
my_string = 'Hello World' print(my_string[1:5]) # Output: 'ello'
my_tuple = (1, 2, 3, 4, 5) print(my_string[:5]) # Output: 'Hello'
my_list = [True, False, True, False, True] print(my_string[6:]) # Output: 'World'
print(my_string[1:5]) ⟶ Output: 'ello' print(my_string[::2]) # Output: 'HloWrd'
print(my_tuple[2:4]) ⟶ Output: (3, 4)
print(my_list[:3]) ⟶ Output: [True, False, True]
print(my_string[::-1]) # Output: 'dlroW olleH'

3. Membership: Checking if an element is present in the sequence my_list = [1, 2, 3, 4, 5]


print(my_list[1:4]) # Output: [2, 3, 4]
using the in operator.
my_string = 'Hello World'
print(my_list[:3]) # Output: [1, 2, 3]
my_tuple = (1, 2, 3) print(my_list[2:]) # Output: [3, 4, 5]
my_list = [True, False, True] print(my_list[::2]) # Output: [1, 3, 5]
print('o' in my_string) ⟶ Output: True print(my_list[::-1]) # Output: [5, 4, 3, 2, 1]
print(2 in my_tuple) ⟶ Output: True
print(False in my_list) ⟶ Output: True 65
4. Python Basics
4.5 Data Types
Sequential Types: Operations on objects

4. Equality: Comparing if two sequences are equal using the == operator.


str1 = 'Hello'
str2 = 'World'
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
list1 = [True, False]
list2 = [1, 2, 3]
print(str1 == str2) ⟶ Output: False
print(tuple1 == tuple2) ⟶ Output: False
print(list1 == list2) ⟶ Output: False

5. Iteration: Looping over each element in the sequence using a for loop.
my_string = 'Hello'
my_tuple = (1, 2, 3)
my_list = [True, False, True]

for char in my_string:


print(char)

for num in my_tuple:


print(num)

for item in my_list:


print(item) 66
4. Python Basics
4.5 Data Types
Sequential Types: Operations on objects

6. Returns the maximum value from a sequence using the max() function.
my_string = 'Hello World'
max_char = max(my_string)
print(max_char) ⟶ Output: 'r'
my_tuple = (5, 2, 8, 1, 9, 3)
max_value = max(my_tuple)
print(max_value) ⟶ Output: 9

7. Returns the minimum value from a sequence using the min() function.
my_list = [5, 2, 8, 1, 9, 3]
min_value = min(my_list)
print(min_value) ⟶ Output: 1
my_tuple = (5, 2, 8, 1, 9, 3)
min_value = min(my_tuple)
print(min_value) ⟶ Output: 1

8. Returns the number of occurrences of a specified element in a sequence using the count() function.
my_string = 'Hello World'
count = my_string.count('l')
print(count) ⟶ Output: 3
my_list = [1, 2, 3, 4, 1, 5, 1]
count = my_list.count(1)
print(count) ⟶ Output: 3

67
4. Python Basics
4.5 Data Types
Sequential Types: Operations on objects

9. Length: Getting the number of elements in the sequence using the len() function.
my_string = 'Hello World'
my_tuple = (1, 2, 3, 4, 5)
my_list = [True, False, True]
print(len(my_string)) ⟶ Output: 11
print(len(my_tuple)) ⟶ Output: 5
print(len(my_list)) ⟶ Output: 3

10. Returns the index of the first occurrence of a specified element in a sequence using the index() function
my_string = 'Hello World'
index = my_string.index('W')
print(index) ⟶ Output: 6
my_list = [5, 2, 8, 1, 9, 3]
index = my_list.index(8)
print(index) ⟶ Output: 2

11. Repetition: Repeating the elements using the * operator. (Not applicable to the range object)
my_string = 'abc'
my_tuple = (1, 2)
my_list = [True, False]
print(my_string * 3) ⟶ Output: 'abcabcabc'
print(my_tuple * 2) ⟶ Output: (1, 2, 1, 2)
print(my_list * 4) ⟶ Output: [True, False, True, False, True, False, True, False]

68
4. Python Basics
4.5 Data Types
Sequential Types: Operations on objects
12. Concatenation: Joining or combining multiple sequences using the + operator. (Not applicable to the range object)
str1 = 'Hello'
str2 = 'World'
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
list1 = [True, False]
list2 = [1, 2, 3]
print(str1 + ' ' + str2) ⟶ Output: 'Hello World'
print(tuple1 + tuple2) ⟶ Output: (1, 2, 3, 4, 5, 6)
print(list1 + list2) ⟶ Output: [True, False, 1, 2, 3]

13. Mutation: Modifying elements or structure of the sequence. (Only applicable to the mutable object)
my_list = [1, 2, 3, 4, 5]
my_list[0] = 'New'
my_list.append(6)
print(my_list) ⟶ Output: ['New', 2, 3, 4, 5, 6]

Note: A tuple is an immutable object, meaning my_tuple = ([1, 2, 3], 4, 5)


you cannot directly assign a new value to the print(my_tuple) # Output: ([1, 2, 3], 4, 5)
tuple or modify other elements. However, if it
contains a list object as its element, that list my_tuple[0].append(4)
object could still be updated. print(my_tuple) # Output: ([1, 2, 3, 4], 4, 5)

69
4. Python Basics
4.5 Data Types
Sequential Types: Operations on objects

More on mutations

Considering the right example, it seems like the immutable string1 = "Hello "
string1 is updated by the assignment operator, which is not string2 = "World"
string1 += string2
the case. Actually, a new string object is created with the value of print(string1)
string1 + string2, which is then referenced by string1.
So, after that operation, the three objects "Hello ",
"World", and "Hello World" exist in the memory, whereas
there is no reference to "Hello " anymore.

string1 "Hello " "Hello "

string1 += string2
string2 “World" string2 “World"

string1 "Hello World"

Memory Memory
70
4. Python Basics
4.5 Data Types
Sequential Types: the str type

The str type in Python represents a sequence of characters and is used to store and manipulate
textual data. Here are key points summarizing the str type:

• Textual Data: str objects hold strings of characters, enclosed in single quotes ('') or double quotes
(""). They can represent words, sentences, paragraphs, or any other text-based information.
• Immutable: str objects are immutable, meaning their contents cannot be changed after creation.
Any operation that modifies a string actually creates a new string object.
• Type Conversion: You can convert other data types to str using the str() function, which creates
a string representation of the given object.
• String Interpolation: Python offers multiple ways to format strings and allows you to create
dynamic strings without the need for excessive concatenation or complex formatting operations.
• String Methods: str objects have many built-in methods that allow you to perform operations like
case conversion, string formatting, searching, replacing, splitting, and more.

71
4. Python Basics
4.5 Data Types
Sequential Types: the str type
String Interpolation: Python offers multiple ways to format strings and allows you to create dynamic
strings without the need for excessive concatenation or complex formatting operations.
1. Concatenation: You can concatenate strings and variables using the + operator.
name = "Alice"
age = 25
message = "My name is " + name + " and I am " + str(age) + " years old."

2. %-formatting: This method uses the % operator to format strings. You provide a format
specifier and pass the values in a tuple.
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)

3. [Link](): This method uses the [Link]() function to format strings. You can specify
placeholders in the string and provide the values in the format() function.
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age) 72
4. Python Basics
4.5 Data Types
Sequential Types: the str type
String Interpolation: Python offers multiple ways to format strings and allows you to create dynamic
strings without the need for excessive concatenation or complex formatting operations.

4. f-strings (formatted string literals): Introduced in Python 3.6, f-strings provide a concise and
readable way to interpolate variables and expressions directly into strings. You can enclose
expressions within curly braces {} and prefix the string with the letter f.
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."

All the above outputs are the same:

73
4. Python Basics
4.5 Data Types
Sequential Types: the str type
String Methods: commonly used methods are listed below. More methods can be found in the online
documentation: [Link]

Method Description Example


[Link]() Returns a lowercase version of the string. "Hello".lower() returns "hello".
[Link]() Returns an uppercase version of the string. "Hello".upper() returns "HELLO".
[Link]() Removes leading and trailing whitespace. " Hello ".strip() returns "Hello".
[Link](old, new) Replaces occurrences of a substring with another. "Hello".replace("l", "L") returns "HeLLo".
[Link](separator) Splits the string into a list of substrings. "Hello World".split(" ") returns ["Hello", "World"].
[Link](iterable) Joins the elements of an iterable into a string. " ".join(["Hello", "World"]) returns "Hello World".
[Link]() Checks if all characters are digits. "123".isdigit() returns True.
[Link]() Checks if all characters are alphabetic. "Hello".isalpha() returns True.
[Link]() Checks if all characters are lowercase. "hello".islower() returns True.
[Link]() Checks if all characters are uppercase. "HELLO".isupper() returns True.
[Link](prefix) Checks if the string starts with the given prefix. "Hello".startswith("He") returns True.
[Link](suffix) Checks if the string ends with the given suffix. "Hello".endswith("lo") returns True.
[Link](substring) Counts the number of occurrences of a substring. "Hello World".count("o") returns 2.
74
4. Python Basics
4.5 Data Types
Sequential Types: the list type

The list type in Python is an ordered collection of items that can hold various data types. Here are
key points summarizing the list type:

• Ordered Collection: Lists maintain the order of elements, meaning the position of each item is
preserved.

• Heterogeneous Data: Lists can hold items of different data types, such as integers, floats, strings, or
even other lists.

• Dynamic Size: Lists can grow or shrink dynamically as items are added or removed. They have no
fixed size limitations.

• Mutable: Lists are mutable, which means you can modify their elements by assigning new values,
adding or removing items, or reordering the existing items. Lists provide methods like append(),
extend(), insert(), remove(), pop(), and clear() to manipulate their contents.

75
4. Python Basics
4.5 Data Types
Sequential Types: the list type

Operators on the list type for in-place modification.


The following operators demonstrate how to modify list elements, replace sublists with new elements, and
delete elements or sublists using the del statement. Note that the examples modify the list in-place, resulting in
a modified list after each operation.
Operation Description Example
Changes the value at the specified my_list = [1, 2, 3]
list[index] = value
index in the list. my_list[1] = 4 # Result: [1, 4, 3]
Replaces a sublist with the elements my_list = [1, 2, 3, 4]
list[start:end] = iterable
from the iterable. my_list[1:3] = ['a', 'b’] # Result: [1, 'a', 'b', 4]
Replaces a sublist with the elements my_list = [1, 2, 3, 4, 5]
list[start:end:step] = iterable
from the iterable using a step. my_list[::2] = ['a', 'b', 'c’] # Result: ['a', 2, 'b', 4, 'c']
Deletes the item at the specified my_list = [1, 2, 3]
del list[index]
index in the list. del my_list[1] # Result: [1, 3]
Deletes a sublist from the list within my_list = [1, 2, 3, 4, 5]
del list[start:end]
the specified range. del my_list[1:4] # Result: [1, 5]
Deletes a sublist from the list using a my_list = [1, 2, 3, 4, 5]
del list[start:end:step]
step value. del my_list[::2] # Result: [2, 4]

76
4. Python Basics
4.5 Data Types
Sequential Types: the list type
List Methods: commonly used methods are listed below. More methods can be found in the online
documentation: [Link]
Method Description Example
my_list = [1, 2, 3]
[Link](item) Appends an item to the end of the list.
my_list.append(4) # Result: [1, 2, 3, 4]
Extends the list by appending elements my_list = [1, 2, 3]
[Link](iterable)
from the iterable. my_list.extend([4, 5]) # Result: [1, 2, 3, 4, 5]
Inserts an item at the specified index in my_list = [1, 2, 3]
[Link](index, item)
the list. my_list.insert(1, 'a’) # Result: [1, 'a', 2, 3]
Removes the first occurrence of the item my_list = [1, 2, 3, 2]
[Link](item)
from the list. my_list.remove(2) # Result: [1, 3, 2]
Removes and returns the item at the
my_list = [1, 2, 3]
[Link](index=-1) specified index, or the last item if no
item = my_list.pop(1) # Result: my_list = [1, 3], item = 2
index is provided.
my_list = [1, 2, 3]
[Link]() Removes all items from the list.
my_list.clear() # Result: []
Sorts the items in the list in ascending my_list = [3, 1, 2]
[Link](key=None, reverse=False)
order. my_list.sort() # Result: [1, 2, 3]
my_list = [1, 2, 3]
[Link]() Reverses the order of items in the list.
my_list.reverse() # Result: [3, 2, 1]

77
4. Python Basics
4.5 Data Types
Sequential Types: the tuple type

The tuple type in Python is an ordered collection of items that can hold various data types. Here are
key points summarizing the tuple type:

• Ordered Collection: Lists maintain the order of elements, meaning the position of each item is
preserved.

• Heterogeneous Data: Lists can hold items of different data types, such as integers, floats, strings, or
even other tuples.

• Immutable: meaning its elements cannot be modified after creation. Although tuples are
immutable, they can contain mutable objects like lists.

78
4. Python Basics
4.5 Data Types
Sequential Types: the tuple type

The tuple type in Python is an ordered collection of items that can hold various data types. Here are
key points summarizing the tuple type:

• Ordered Collection: Lists maintain the order of elements, meaning the position of each item is
preserved.

• Heterogeneous Data: Lists can hold items of different data types, such as integers, floats, strings, or
even other tuples.

• Immutable: meaning its elements cannot be modified after creation. Although tuples are
immutable, they can contain mutable objects like lists.
Common Methods Description Example
my_tuple = (1, 2, 3, 2, 4, 2)
Returns the number of occurrences of a specified
[Link](value) count = my_tuple.count(2)
value in the tuple. # Result: count = 3
my_tuple = (1, 2, 3, 2, 4, 2)
Returns the index of the first occurrence of a
[Link](value, start=0, end=len(tuple)) index = my_tuple.index(4)
specified value in the tuple within the given range. # Result: index = 4
79
4. Python Basics
4.5 Data Types
Sequential Types: Packing and Unpacking

Sequential data types in Python, such as lists, tuples, and strings, have the unique feature of packing
and unpacking.

• Packing is the process of combining multiple values into a single sequential data object. For
example, you can pack multiple values into a tuple by simply enclosing them within parentheses ( )
(optional for tuple) or a list by using square brackets [ ]. Packing allows you to group related values
together into a single object.

• Unpacking, on the other hand, is the process of extracting values from a sequential data object
into individual variables. It allows you to assign the elements of a tuple, list, or string to separate
variables in a single statement. Unpacking is particularly useful when you want to conveniently
access and work with the individual elements of a sequence.

• To unpack a sequential data object, you can assign its elements to variables using the assignment
operator = and separate the variables with commas. The number of variables on the left side of the
assignment must match the number of elements in the unpacked sequence.

80
4. Python Basics
4.5 Data Types
Sequential Types: Packing and Unpacking

Packing and unpacking examples for the str, list, and tuple types.
# List Packing and Unpacking
my_list = [1, 2, 3] # List Packing
a, b, c = my_list # List Unpacking
print(a, b, c) # Output: 1 2 3

# Tuple Packing and Unpacking


my_tuple = 1, 2, 3 # Tuple Packing
a, b, c = my_tuple # Tuple Unpacking
print(a, b, c) # Output: 1 2 3

# String Packing and Unpacking


my_string = "hello" # String Packing
a, b, c, d, e = my_string # String Unpacking
print(a, b, c, d, e) # Output: h e l l o

81
4. Python Basics
4.5 Data Types
Sequential Types: Packing and Unpacking

In unpacking, you can use the asterisk (*) to collect multiple elements into a single variable. The
variable that collects the remaining elements always receives a list type reference.
my_list = [1, 2, 3, 4, 5]
a, *b, c = my_list

print(a) # Output: 1
print(b) # Output: [2, 3, 4]
print(c) # Output: 5

my_tuple = (1, 2, 3, 4, 5)
a, *b, c = my_tuple

print(a) # Output: 1
print(b) # Output: [2, 3, 4]
print(c) # Output: 5

my_string = "hello"
a, *b, c = my_string

print(a) # Output: 'h'


print(b) # Output: ['e', 'l', 'l']
print(c) # Output: 'o' 82
4. Python Basics
4.5 Data Types
Mapping and Set

Mapping data types (dictionaries) in Python represent key-value pairs, while set data types represent
unordered collections of unique elements. Both are mutable, and their size and elements can be
modified.

Set and Mapping Types


set Represents an unordered collection of unique elements unique_numbers = {1, 2, 3} Mutable
dict Represents a collection of key-value pairs person = {'name': 'John', 'age': 25} Mutable

83
4. Python Basics
4.5 Data Types
Mapping and Set: the set type
• Set data type in Python represents a mutable unordered collection of unique elements.
• Sets are created by enclosing comma-separated values within curly braces ({}), or by using the
set() constructor.
• Sets provide operations like union, intersection, difference, and membership testing.
• Sets are useful for tasks that involve finding unique values, testing membership, or performing set
operations.
# Creating a Set using Curly Braces
my_set = {1, 2, 3, 4, 5}

# Creating a Set using the set() Constructor


my_set = set([1, 2, 3, 4, 5])

# Creating an Empty Set


my_set = set()

# Creating a Set from a String


my_set = set("hello")

# Creating a Set from a List


my_list = [1, 2, 3, 4, 5]
my_set = set(my_list) 84
4. Python Basics
4.5 Data Types
Mapping and Set: the set type
Some common set operators

Operator Description Example


set1 = {1, 2, 3}
Union: Returns a set containing all elements
set1 | set2 set2 = {3, 4, 5}
from both sets. union_set = set1 & set2 # Result: {1, 2, 3, 4, 5}
set1 = {1, 2, 3}
Intersection: Returns a set containing common
set1 & set2 set2 = {3, 4, 5}
elements between two sets. intersection_set = set1 & set2 # Result: {3}
set1 = {1, 2, 3}
Difference: Returns a set containing elements
set1 - set2 set2 = {3, 4, 5}
present in the first set but not in the second set. difference_set = set1 - set2 # Result: {1, 2}
Symmetric Difference: Returns a set containing set1 = {1, 2, 3}
set1 ^ set2 elements that are in either of the sets, but not set2 = {3, 4, 5}
both. symmetric_difference_set = set1 ^ set2 # Result: {1, 2, 4, 5}
set1 = {1, 2}
Subset: Returns True if all elements of the first
set1 <= set2 set2 = {1, 2, 3}
set are present in the second set. is_subset = set1 <= set2 # Result: True
set1 = {1, 2, 3}
Superset: Returns True if all elements of the
set1 >= set2 set2 = {1, 2}
second set are present in the first set. is_superset = set1 >= set2 # Result: True

85
4. Python Basics
4.5 Data Types
Mapping and Set: the set type
Some common set methods. Refer to the documentation for details:
[Link]

Method Description
[Link](element) Adds an element to the set.
[Link](element) Removes an element from the set.
[Link](element) Removes an element from the set if it exists, otherwise does nothing.
[Link]() Removes and returns an arbitrary element from the set.
[Link]() Removes all elements from the set, making it empty.
[Link]() Returns a shallow copy of the set.
[Link](iterable) Updates the set by adding elements from an iterable.
[Link](*others) Returns a new set with elements common to the set and all other sets.
[Link](*others) Returns a new set with elements in the set but not in any of the other sets.
set.symmetric_difference(other) Returns a new set with elements present in either the set or the other set, but not both.
[Link](*others) Returns a new set with elements from the set and all other sets.

86
4. Python Basics
4.5 Data Types
Mapping and Set: the dict type

• dict data type in Python represents a mutable unordered collection of key-value pairs.
• Each key-value pair in a dictionary is separated by a colon (:) and enclosed in curly braces ({}).
• Keys within a dictionary must be unique, and they are typically immutable types such as strings or
numbers.
• Values within a dictionary can be of any type and can be accessed and modified using their
corresponding keys.
• Dictionaries provide fast lookups based on keys, making them efficient for data retrieval by key-
value association.
# Creating an empty dictionary
my_dict = {}

# Creating a dictionary with key-value pairs


my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Using the dict() constructor


my_dict = dict()

# Creating a dictionary from a list of tuples


my_dict = dict([('name', 'John'), ('age', 30), ('city', 'New York')])

# Creating a dictionary using keyword arguments


my_dict = dict(name='John', age=30, city='New York')
87
4. Python Basics
4.5 Data Types
Mapping and Set: the dict type
Iteration
1. Iterating over keys using 'for key in dict'
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict:
print(key)
2. Iterating over values using 'for value in [Link]()'
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for value in my_dict.values():
print(value)
3. Iterating over key-value pairs using 'for key, value in [Link]()'
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in my_dict.items():
print(key, value)

88
4. Python Basics
4.5 Data Types
Mapping and Set: the dict type
Operators
Operator Description Example
my_dict = {'name': 'John’}
[] Accessing values by key: my_dict[key]
value = my_dict['name’] # Result: 'John'
my_dict = {'name': 'John'}
in Checking if a key exists: key in my_dict if 'name' in my_dict:
print('Key exists')
my_dict = {'name': 'John’}
not in Checking if a key does not exist: key not in my_dict if 'age' not in my_dict:
print('Key does not exist')
dict1 = {'name': 'John’}
dict2 = {'name': 'John’}
== Equality comparison: dict1 == dict2
if dict1 == dict2:
print('Dictionaries are equal')
dict1 = {'name': 'John’}
dict2 = {'name': 'Jane’}
!= Inequality comparison: dict1 != dict2
if dict1 != dict2:
print('Dictionaries are not equal')
my_dict = {'name': 'John', 'age': 30}
len() Getting the number of key-value pairs: len(my_dict)
length = len(my_dict) # Result: 2
my_dict = {'name': 'John'}
del Deleting a key-value pair: del my_dict[key]
del my_dict['name'] # Result: dictionary is empty
89
4. Python Basics
4.5 Data Types
Mapping and Set: the dict type

Some common dict methods. Refer to the documentation for details:


[Link]

Method Description
[Link](key, default) Returns the value for a given key. If the key is not found, returns default.
[Link]() Returns a view object containing all the keys in the dictionary.
[Link]() Returns a view object containing all the values in the dictionary.
[Link]() Returns a view object containing all the key-value pairs in the dictionary.

[Link](other_dict) Updates the dictionary with the key-value pairs from another dictionary.

[Link](key, default) Removes and returns the value for a given key. If the key is not found, returns default.

[Link]() Removes and returns an arbitrary key-value pair from the dictionary.

[Link]() Removes all key-value pairs from the dictionary, making it empty.
[Link]() Returns a shallow copy of the dictionary.

90
4. Python Basics
4.5 Data Types
Sequence Comprehension
Python comprehensions create new sequences from existing ones. There are three types of
comprehensions in Python:

1. List Comprehensions: List Comprehensions provide a way to create new lists from existing iterables (e.g., a list,
tuple, or string) and applying an expression to each element. The result is a new list derived from the original
elements. List comprehensions follow the syntax: [expression for item in iterable if condition].
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers if n % 2 == 0] # a new list: [4, 16]

2. Set Comprehensions: Set comprehensions are similar to list comprehensions but produce sets as output.. Set
comprehensions follow the syntax: {expression for item in iterable if condition}.
numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]
unique_squares = {n**2 for n in numbers} # a new set: {1, 4, 9, 16, 25}

3. Dictionary Comprehensions: Dictionary comprehensions allow you to create new dictionaries by iterating over
an iterable and constructing key-value pairs based on an expression. Dictionary comprehensions follow the
syntax: {key_expression: value_expression for item in iterable if condition}.
fruits = ['apple', 'banana', 'orange']
fruit_lengths = {fruit: len(fruit) for fruit in fruits} # a new dict: {'apple': 5, 'banana': 6, 'orange': 6}

91
4. Python Basics
Coding exercises

W3schools offers interactive quizzes and coding exercises to help you learn Python. Please pause the
video and open the following page. Try all you have learned so far.

[Link]

Try all these sections

92
4. Python Basics
4.6 Functions
Functions in Python are reusable blocks of code that perform specific tasks. They help organize code,
improve readability, and promote code reuse.
• function_name is the name you choose for
Defining a Function your function.
• parameter1, parameter2, ... are optional
def function_name(parameter1, parameter2, ...): input parameters that your function may
""" accept. You can define as many parameters
Docstring: Description of the function. as needed, separating them with commas.
Optional documentation providing more details about the function. • A docstring in triple quotes """… """
"""
provides information on a function’s
# Function code block purpose, inputs, return value, and more.
# Perform operations and calculations here (optional)
• The function code block is indented
# Optional: Return a value beneath the function definition. This is
return result where you write the actual code to execute
when the function is called.
• If your function is designed to return a
value, you can use the return statement
followed by the value you want to return.
This is optional, and not all functions need
to have a return statement.
93
4. Python Basics
4.6 Functions
Defining a local (nested) Function within another function
def outer_function():
# Define the local function
def inner_function():
# Function logic goes here
pass Remember that the local function is only
# Call the local function
accessible within the scope of the outer
inner_function() function. It cannot be directly accessed or
called from outside the outer function.
# Call the outer function
outer_function()

94
4. Python Basics
4.6 Functions
Function Example
def square(number):
""" In Python, you need to define a function
Calculates the square of a given number.
before you can call it. This is because Python is
Parameters:
an interpreted language, which means it
number (int or float): The number to be squared. executes code line by line. When you define a
function, you are creating a block of code that
Returns: can be executed later when you call it.
int or float: The square of the input number.
""" If you try to call a function before it is defined,
result = number ** 2
you will encounter a NameError because
return result
Python hasn't encountered the function
# Calling the square function definition yet.
result = square(5)
print(result)

95
4. Python Basics
4.6 Functions
Function Parameters
Functions can have different types of parameters that allow you to pass information into the function.
1. Positional Parameters: Parameters defined by their position in the function call. The values passed as
arguments match the parameters based on their position.
def function_name(param1, param2, ...):
# Function code
2. Default Parameters: Default parameters have predefined values assigned to them. The default value is used if
no argument is provided for a default parameter.
def function_name(param1=default_value1, param2=default_value2, ...):
# Function code

def greet(name, greeting="Hello"):


"""
Greets a person with a specified greeting (default: Hello).

Parameters:
name (str): The name of the person.
greeting (str, optional): The greeting to use (default: Hello).
"""
print(greeting + ", " + name + "!")

# Calling the greet function with default greeting


greet("Alice") # Output: Hello, Alice!

# Calling the greet function with a custom greeting


greet("Bob", "Hi") # Output: Hi, Bob! 96
4. Python Basics
4.6 Functions
Function Parameters

3. Variable-Length Positional Parameters (args): Variable-length positional parameters, commonly known as


*args, allow you to pass an arbitrary number of positional arguments to a function. The arguments are
collected into a tuple within the function.
def function_name(*args):
# Function code

def calculate_sum(*numbers):
"""
Calculates the sum of an arbitrary number of numbers.

Parameters:
*numbers (float): Variable-length positional parameters representing numbers.

Returns:
float: The sum of the input numbers.
"""
total = sum(numbers)
return total

# Calling the calculate_sum function with different numbers


result1 = calculate_sum(2, 4, 6) # Output: 12
result2 = calculate_sum(1, 3, 5, 7, 9) # Output: 25

print(result1)
print(result2) 97
4. Python Basics
4.6 Functions
Function Parameters def create_person(name, age, occupation=None, city=None):
"""
Creates a person with a given name, age, occupation, and city.
4. Keyword Parameters: Keyword parameters, also known
as named parameters, allow you to pass arguments Parameters:
name (str): The name of the person.
using their parameter names. This provides clarity and age (int): The age of the person.
occupation (str, optional): The occupation of the person. Default is None.
flexibility in function calls. city (str, optional): The city of the person. Default is None.

def function_name(param1=value1, param2=value2, ...): Returns:


dict: A dictionary containing the person's information.
# Function code """
person = {
'name': name,
'age': age,
'occupation': occupation,
'city': city
}
return person

# Creating a person with required parameters only


person1 = create_person('Alice', 25)
print(person1)
# Output: {'name': 'Alice', 'age': 25, 'occupation': None, 'city': None}

# Creating a person with additional information


person2 = create_person('Bob', 30, occupation='Engineer', city='New York')
print(person2)
# Output: {'name': 'Bob', 'age': 30, 'occupation': 'Engineer', 'city': 'New York'}

98
4. Python Basics
4.6 Functions
Function Parameters

5. Variable-Length Keyword Parameters (kwargs): Variable-length keyword parameters, commonly


known as **kwargs, allow you to pass an arbitrary number of keyword arguments to a function.
The arguments are collected into a dictionary object within the function.
def function_name(**kwargs):
# Function code

def print_student_details(**kwargs):
"""
Prints the details of a student.

Parameters:
**kwargs (dict): Variable-length keyword parameters representing student details.
"""
for key, value in [Link]():
# Print each key-value pair
print(key + ':', value)

# Calling the function with different student details


print_student_details(name='Alice', age=20, major='Computer Science’)
print("")
print_student_details(name='Bob', age=22, major='Physics', university='ABC University')

99
4. Python Basics
4.6 Functions
# Returning as Tuple
Function Returns def get_values_tuple():
value1 = 10
value2 = "Hello"
Return Multiple Values return (value1, value2)
In Python, you can return multiple values from a function by
result_tuple = get_values_tuple()
using a tuple, a list, or multiple variables separated by commas print(result_tuple) # Output: (10, "Hello")

# Returning as List
def get_values_list():
value1 = 10
value2 = "Hello"
return [value1, value2]

result_list = get_values_list()
print(result_list) # Output: [10, "Hello"]

# Returning as Multiple Variables


def get_values_multiple():
value1 = 10
value2 = "Hello"
The values are implicitly packed into a tuple return value1, value2

result1, result2 = get_values_multiple()


print(result1) # Output: 10
Tuple unpacking print(result2) # Output: "Hello"

100
4. Python Basics
4.6 Functions
def add_item_to_list(item, my_list):
“Calling by Reference” Side Effects """
Adds an item to the provided list.
In Python, when you pass an argument to a function, it is passed Parameters:
by reference. If the argument is mutable, any modifications made item: The item to be added.
my_list: The list to which the item is added.
to it within the function persist outside the function scope, """
affecting the original object. my_list.append(item)
print("Inside the function:", my_list)

Be aware of these effects of altering mutable objects inside a # Creating an empty list
my_list = []
function.
print("Before the function call:", my_list)

# Calling the function and modifying the list


add_item_to_list("Apple", my_list)

print("After the function call:", my_list)

101
4. Python Basics
4.6 Functions
# Global variable
Namespace and Scope global_var = "Global"

def outer_function():
In Python, a namespace is a system that determines the scope # Outer function's local variable
outer_var = "Outer"
and accessibility of names (variables, functions, classes, etc.)
within a program. def inner_function():
# Inner function's local variable
inner_var = "Inner"
• Each function in Python has its own namespace, which is a
# Accessing variables from different scopes
local scope where the function's variables and other names print("Inner:", inner_var)
are stored. print("Outer:", outer_var)
print("Global:", global_var)
• Any names defined within the function are inaccessible
outside of the function. # Calling the inner function
inner_function()
• The function can access names from its own namespace and
names from any outer scopes (such as global scope or # Calling the outer function
outer_function()
enclosing functions) where it was defined. If a name is not
found in the local namespace, Python will search the # Attempting to access variables from outer scopes
# Uncommenting any of the lines below will result in
enclosing scopes and then the global scope until the name is # a NameError.
found or an error occurs.
# print("Outer (from global):", outer_var)
# print("Inner (from global):", inner_var)

102
4. Python Basics
4.6 Functions
Built-in Functions
Python provides a rich set of built-in functions that are readily available for use without requiring explicit import
statements. Here is a summary of some commonly used Python built-in functions:
Function Description
print() Outputs text or values to the console.
len() Returns the length of an object, such as a string, list, or tuple.
type() Returns the type of an object.
int(), float(), str(), bool() Converts values to integer, float, string, or boolean types, respectively.
input() Reads input from the user via the console.
range() Generates a sequence of numbers within a specified range.
abs() Returns the absolute value of a number.
max(), min() Returns the maximum or minimum value from a sequence of values.
sum() Calculates the sum of values in a sequence.
round() Rounds a number to a specified precision.
sorted() Returns a new sorted list from an iterable.
enumerate() Returns an iterator of tuples with indices and corresponding values from an iterable.
zip() Combines multiple iterables into a single iterator of tuples.
any(), all() Returns True if any or all elements in an iterable are true, respectively.
map() Applies a function to each element of an iterable and returns an iterator with the results.
filter() Filters elements from an iterable based on a specified condition and returns an iterator

For complete reference: [Link] 103


4. Python Basics
4.6 Functions
Do some coding exercises here:

[Link]
[Link]

104
4. Python Basics
4.7 Classes, Objects, and Methods
• Class: A blueprint/template that defines the structure and behavior of objects. It encapsulates related data and
functionality into a single entity.
• Object: A specific instance created from a class, representing an individual entity with its own data and behaviors.
• Method: A function defined within a class that operates on objects, defining their behavior and allowing them to
perform actions.

105
4. Python Basics
4.7 Classes, Objects, and Methods
Let's use the str class (or type) as an example to explain the concepts
• Class: The str class in Python is a built-in class that represents strings. It defines the structure and behavior of
string objects.
• Object: An object of the str class is an instance of the class representing a specific string value. For example,
"Hello, World!" is an object of the str class, representing a string with that specific content.
• Method: The str class provides various methods that can be applied to string objects. For instance, the upper()
method is a method defined within the str class. We can use it on string objects to convert the string to the
uppercase.

my_string = "Hello, World!"

# The `str` class represents the structure and behavior of string objects.
# `my_string` is an object of the `str` class, representing the specific string
"Hello, World!". Python can access methods
from objects using dot
uppercase_string = my_string.upper()
# `upper()` is a method defined within the `str` class.
notation:
• object_name.object_method()
# It is called on the `my_string` object to convert the string to uppercase.

print(uppercase_string) # Output: "HELLO, WORLD!"

106
4. Python Basics
4.8 Packages and Modules
In Python, packages and modules are organizational structures that help manage and organize code.

A module is a single file containing Python definitions, functions, classes, or variables. It is a way to organize code into
reusable components.
• You can import a module into other Python scripts or modules using the import statement. After that, you
can use dot notation to access code in a module, such as module_name.function_name() or
module_name.variable_name.
• For example, if you have a module called my_module.py with a function named my_function, you can
import and use it as follows:
import my_module
my_module.py
my_module.my_function()

107
4. Python Basics
4.8 Packages and Modules
In Python, there are primarily three types of modules:

1. Built-in Modules: These modules are part of the Python Standard Library and come pre-installed with Python.
They offer various functionalities, including file handling, math operations, network communication, and data
manipulation. Examples of built-in modules include math, os, datetime, and random.

2. Third-Party Modules: Not part of the Python Standard Library, these modules are created by outside developers.
They can be installed separately using package managers like pip. Third-party modules offer additional
functionality beyond what is available in the built-in modules and can be used to extend the capabilities of
Python. Popular third-party modules include NumPy, pandas, requests, and matplotlib.

3. User-Defined Modules: These modules are created by users to encapsulate reusable code. User-defined modules
are typically Python scripts with .py extensions that contain functions, classes, or variables that can be imported
and used in other Python programs. By organizing related code into modules, you can achieve better code
organization and reusability.

108
4. Python Basics
4.8 Packages and Modules
In Python, packages and modules are organizational structures that help manage and organize code.

A package is a way to organize related modules into a directory hierarchy. It can contain multiple modules and even
nested sub-packages. Packages allow for a more structured code organization, especially for larger projects.
• A package is simply a directory that contains an __init__.py file, which marks the directory as a Python
package. This file can be empty or can include the initialization code for the package. The package directory
can also contain other modules or sub-packages.
• Packages are imported similarly to modules, using the import statement. When importing a package, you can
access its modules and sub-packages using dot notation.
• For example, if you have a package called my_package with modules module1 and module2 inside it, you
can import and use them as follows:
my_package
import my_package.module1
import my_package.module2 __init__.py
my_package.module1.my_function() [Link]
my_package.module2.my_function()
[Link]
sub_package
__init__.py 109
4. Python Basics
4.8 Packages and Modules
Possible import statements

# Importing the Entire Module


import math # Imports the entire math module

# Importing Specific Items


from math import sqrt, pi # Imports only sqrt() and pi from math

# Importing with an Alias


import pandas as pd # Imports pandas module with an alias pd

# Importing All Items from a Module (Discouraged)


from math import * # Imports all items from math (not recommended)

# Importing a Module from a Package


from my_package import my_module # Imports my_module from my_package

110
4. Python Basics
4.8 Packages and Modules
Best Practices

# Use Explicit Imports


import math # Good: Importing the entire module

from math import sqrt # Good: Importing specific items

# Avoid using import *


# from math import * # Avoid: Imports all items from math (not recommended)

# Import with an Alias


import pandas as pd # Good: Importing with an alias

# Import Each Module on a Separate Line


import os
import sys

import numpy as np

import my_module

# Avoid importing multiple modules on a single line


# import os, sys # Avoid: Importing multiple modules on a single line
111
4. Python Basics
4.8 Packages and Modules
Best Practices (continued)

# Group Imports Appropriately


# Standard library imports
# Third-party library imports
# Local module imports

# Standard library imports


import os
import sys
import datetime

# Third-party library imports


import numpy as np
import pandas as pd
import requests

# Local module imports


import my_module
from my_package import my_other_module

112
4. Python Basics
4.8 Packages and Modules
Coding Exercises
[Link]

113
5. Creating Your First Python
Program

Apply what you have learned so far


5. Creating Your First Python Program
5.1 Getting familiar with the Spyder IDE
Jupyter Notebook excels in interactive data exploration and analysis, but only has limited functionality to debug your
code if you work in a larger project.

Spyder offers a complete IDE with a code editor, variable explorer, debugger, profiler, and file explorer. It offers a
comprehensive development environment focusing on code editing, project management, and debugging
capabilities. This makes it well-suited for larger projects and more traditional software development workflows.

• Spyder's variable explorer provides an interactive way to inspect and explore variables in your code. It allows you
to view, modify, and track the values of variables during execution, making it easier to debug and understand your
code's behavior.
• Spyder offers a feature-rich code editor with advanced code editing capabilities. It includes features like syntax
highlighting, code folding, code navigation, and integrated code documentation. Spyder also provides
autocompletion, which can help speed up coding by suggesting possible completions as you type.

Watch the following video to learn how to use the Spyder IDE:
Introduction to the Spyder IDE for Python by Kyle Bradbury (15 mins)
Covering the IPython shell, text editor, variable editor, and code execution and debugging tools.

115
5. Creating Your First Python Program
5.2 Solve a Real Problem
Task: Find the maximum number from a CSV file

Requirement:
We have a CSV (Comma-Separated Values) file ([Link]) which contains multiple rows of integer numbers. Write a
Python script to find the maximum integer from the file and then output it to the screen.

116
5. Creating Your First Python Program
5.2 Solve a Real Problem
General problem-solving process:
1. Separate your complex problem into multiple manageable components.
2. For each component, set up the requirements, research possible solutions, develop, and test the code.
3. Combine your components together and test them again with the original requirements.

For this specific task, we need to separate it into the following components:
1. Read the CSV file to access its content
2. For each row, find the maximum integer number, and store it somewhere.
3. After we complete iterating all the rows, we should get a collection of maximum numbers for each row.
4. Find the maximum number from the above collection and print it out on the screen.

117
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content

The functionalities of CSV file manipulation are part of the Python Standard library. You may have never used it
before. However, you may seek help from

A. Python Standard library official documentation: [Link]

B. Google

C. ChatGPT: [Link]

Your best friend to solve


problems quicker!
118
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content

1) Raise a question to ChatGPT and check


its answer. Carefully read the
explanations following the code. If you
don’t understand some statements,
ask ChatGPT for clarification (and/or
read Python documentation) until you
fully understand them.
2) Copy and paste the code to a newly
created Python file in the Spyder IDE.
Save the file to a local folder.
3) Put the supplied “[Link]” file in the
same folder.
4) Change the corresponding CSV file
name in the Python file to “[Link]”
and save it.

119
5. Creating Your First Python Program
5.2 Solve a Real Problem
Debug button
1. Read the CSV file to access its content

5) Set a couple of breakpoints of your


interest and start debugging the code
by pressing the debug button

breakpoints

120
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content

6) Check the Variable Explorer for the active variables.


Examine their Name, Type, Size, and Value Variable Explorer

121
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content

7) Go to the next breakpoint until you can see the row


variable is active and appears in the Variable Explorer pane Click to go to the next breakpoint

122
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content Do you find something
interesting here?
8) Go to the next breakpoint until you can see the row
variable is active and appears in the Variable Explorer pane Each row is read as a list that
contains a series of str type elements

The list element is a str type,


although it represents an integer!

Compared with the input [Link]


file, the first row of numbers read
into Python is correct!

We are done for the first step! 123


5. Creating Your First Python Program
5.2 Solve a Real Problem
Try applying what you have learned from this session for the rest of the steps. Modify the code and debug it,
until you get the maximum number.

STOP
I will show you my solution on the next slide. But don’t
peek at it. Try your solution first.

124
5. Creating Your First Python Program
5.2 Solve a Real Problem
Try applying what you have learned from this session for the rest of the steps. Modify the code and debug it,
until you get the maximum number. There are many ways to solve the problem. I just show you my way to
solve it:

Why did I put this statement here


instead of inside of the for loop?

What’s this? Check


“set comprehension”!

What did I do here?

I used built-in functions to


make my life easier!
125
6. Assignment
Parse an XML file
Research the XML (eXtensible Markup Language) file structure via Google or ChatGPT. Write a Python script to
analyze the provided XML file ([Link]), find the books that were published the earliest, and finally print out
their titles and publish year. Make sure your logic can handle multiple books published in the same year.
Note, the book’s title and author are random strings in the provided XML file, such as “SysXGxgMgX,” and not
the same as the following examples.
<?xml version='1.0' encoding='utf-8'?>
<catalog>
<book id="1">
<title>Python Crash Course</title>
<author>Eric Matthes</author>
<year>2015</year>
</book>
<book id="2">
<title>Fluent Python</title>
<author>Luciano Ramalho</author>
<year>2015</year>
</book>
</catalog>

A sample structure of the provided “[Link]” file

126
THANK YOU

Happy Coding!

You might also like