1.PythonFundmentals 1 127
1.PythonFundmentals 1 127
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?
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
Interpreted
language
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
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).
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.
• Jython: Python implementation running on the Java Virtual Machine (JVM), allowing
seamless integration with Java code and libraries.
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.
• 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
18
3. Setting up Your Development
Environment
21
3. Setting up Your Development Environment
Test Anaconda Installation
Launch Spyder Integrated Development Environment (IDE) from within Anaconda Navigator:
22
3. Setting up Your Development Environment
Test Anaconda Installation
Launch Jupyter Notebook from within Anaconda Navigator:
What is Jupyter Notebook?
24
3. Setting up Your Development Environment
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
2. Click Run
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
29
4. Python Basics
4.0 Comments
Comments can make code more understandable and easier to maintain.
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.
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
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
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.
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
== 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
40
4. Python Basics
4.3 Operators
Membership operators
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
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")
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.")
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)
print("Loop finished.")
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!"
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.
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.
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.
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 = ""
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:
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
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
• 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'
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]
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]
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 += string2
string2 “World" string2 “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."
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]
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
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
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
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.
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}
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 = {}
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
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]
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
Parameters:
name (str): The name of the person.
greeting (str, optional): The greeting to use (default: Hello).
"""
print(greeting + ", " + name + "!")
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
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.
98
4. Python Basics
4.6 Functions
Function Parameters
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)
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"]
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)
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
[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.
# 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.
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
110
4. Python Basics
4.8 Packages and Modules
Best Practices
import numpy as np
import my_module
112
4. Python Basics
4.8 Packages and Modules
Coding Exercises
[Link]
113
5. Creating Your First Python
Program
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
B. Google
C. ChatGPT: [Link]
119
5. Creating Your First Python Program
5.2 Solve a Real Problem
Debug button
1. Read the CSV file to access its content
breakpoints
120
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content
121
5. Creating Your First Python Program
5.2 Solve a Real Problem
1. Read the CSV file to access its content
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
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:
126
THANK YOU
Happy Coding!