0% found this document useful (0 votes)
5 views46 pages

Part 1 Handout Intro to Programming With Python

The document outlines a course on Introduction to Computer Programming with Python at the University of Mines and Technology, focusing on computational problem-solving and algorithm development. It includes a comprehensive course outline, reference materials, and emphasizes hands-on laboratory practice. Key topics covered include programming concepts, Python syntax, control structures, functions, and object-oriented programming.

Uploaded by

adaneanson2007
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)
5 views46 pages

Part 1 Handout Intro to Programming With Python

The document outlines a course on Introduction to Computer Programming with Python at the University of Mines and Technology, focusing on computational problem-solving and algorithm development. It includes a comprehensive course outline, reference materials, and emphasizes hands-on laboratory practice. Key topics covered include programming concepts, Python syntax, control structures, functions, and object-oriented programming.

Uploaded by

adaneanson2007
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
You are on page 1/ 46

UNIVERSITY OF MINES AND TECHNOLOGY

TARKWA

SCHOOL OF RAILWAYS AND INFRASTRUCTURE


DEVELOPMENT (SRID)

LECTURE MATERIAL
DS 163 Introduction to Computer Programming with
Python

Compiled by:
Ernest Kwame Ampomah ( PhD)

1
Course Objective
The primary objective of this course is to equip students with a comprehensive understanding of
computational problem-solving by introducing them to algorithm development and the
corresponding process of creating computer programs to implement these algorithms. Emphasis
will be placed on cultivating fundamental computational skills through program design and
implementation, utilizing Python's simple syntax and powerful capabilities. Real-world examples
will be incorporated to demonstrate Python's versatility and effectiveness in various applications.

Course Outline
 Introduction to Programming Concepts
 Basic Python Syntax and Operations
 Python Control Structures
 Functions
 Modules and Libraries
 File Handling
 Error Handling and Exceptions
 Introduction to Object-Oriented Programming (OOP)

Reference
1) Deitel, P. and Deitel, H. (2020), Intro to Python: For Computer Science and Data Science.
Pearson Education.
2) Abraham, N., (2017), Coding All-in-One For Dummies, For Dummies; 1st edition, ISBN:
978-1119363026, 800pp.
3) Clark, N. (2018), Computer Programming for Beginners: Fundamentals of Programming
Terms and Concepts, CreateSpace Independent Publishing Platform, ISBN: 978-
1719439558, 207pp.
4) Hawramani, I. (2018), Computer Programming for Complete Beginners: A Quick Course
for Mastering the Basics of Coding through Interactive Steps and Visual Examples,
Independently published, ISBN: 978-1728763620, 198pp.

Course Presentation
This course is delivered through a combination of lectures and hands-on laboratory practice,
supplemented by comprehensive handouts. During lab sessions, students will be guided in solving
practical problems of varying complexity to reinforce theoretical concepts. In addition, students
will be assigned practical exercises to complete independently and submit as assignments. To gain
a thorough understanding and appreciation of the subject, students are encouraged to actively
participate in all lectures and lab sessions, consistently practice programming tasks, review
provided references and handouts, and complete all assignments on time.

2
Chapter 1:
Introduction to Programming Concepts

Programming is the process of creating a set of instructions that enable a computer to perform
specific tasks or solve problems. This involves designing and implementing algorithms—(step-
by-step procedures or formulas for solving problems)—by writing code in one or more
programming languages. These languages serve as a medium for humans to communicate with
machines, allowing us to instruct computers in a way they can understand and execute.

The act of programming encompasses several key activities, including:


 Problem Analysis
o Understanding the problem that needs to be solved.
o Breaking the problem into smaller, manageable components.
o Identifying inputs, outputs, and constraints.
 Algorithm Design
o Developing a logical sequence of steps or procedures (algorithm) to solve the
problem.
o Ensuring the algorithm is efficient and meets the requirements.
 Writing Code
o Translating the algorithm into a programming language (coding).
o Choosing an appropriate programming language based on the problem's needs and
environment.
o Following syntax and style rules of the chosen language.
 Testing and Debugging
o Running the code to test its functionality.
o Identifying and fixing errors (bugs) in the code.
o Ensuring the program produces the correct output for all valid inputs.
 Optimization
o Improving the efficiency of the code (e.g., reducing runtime or memory usage).
o Refactoring the code to make it cleaner, more readable, or easier to maintain

3

 Documentation
o Writing clear comments and documentation to explain the code.
o Ensuring others (and future versions of yourself) can understand and use the
program.
 Maintenance
o Updating the program to fix bugs, improve performance, or add new features.
o Ensuring compatibility with changing environments and requirements

1.1 Algorithm Design


Algorithm Design is a critical step in programming that focuses on creating a clear, logical
sequence of steps to solve a problem or perform a specific task. This process ensures that the
solution is efficient, effective, and can be implemented in code.

Characteristics of a Good Algorithm


 Correctness: Produces the correct output for all valid inputs.
 Efficiency: Uses minimal resources (time and space).
 Clarity: Easy to understand and follow.
 Scalability: Can handle larger inputs without significant performance degradation.
 Robustness: Handles edge cases and invalid inputs gracefully.

Common Tools for Algorithm Design


1.) Pseudocode:
o A high-level, language-independent description of the steps in the algorithm.
o ie: a simple, clear explanation of what the algorithm does, without focusing on any
specific programming language. It describes the process in general terms, using basic
steps like "input data," "perform operation," and "produce result."
Example
Step 1: Input the list of numbers
Step 2: Initialize a variable to store the sum
Step 3: Loop through each number in the list
Step 4: Add the number to the sum

4
Step 5: Output the sum
2.) Flowcharts:
 A graphical representation of the algorithm using shapes to represent steps and arrows for
flow.

Figure 1.1. Illustration of Flowchart

Flowchart Standardized Symbols


Flowcharts rely on a set of standard symbols to represent different types of actions or decisions:
 Oval: Start and end points of the process.
 Rectangle: A process or action step (e.g., calculation, operation).
 Diamond: A decision point (e.g., yes/no, true/false).
 Parallelogram: Input or output (e.g., user input, result display).
 Arrow: Indicates the flow of control or data from one step to the next.

Example
Design a flowchart that takes an integer as input and determines whether it is even or odd.
Answer
To determine whether a given integer is even or odd, you can follow this flowchart:
1. Start: Begin the process.
2. Input Number: Enter the integer you want to check.
3. Is Number Divisible by 2?:
o If Yes, the number is even.
o If No, the number is odd.
4. End: Conclude the process.

5
Constructing the Flowchart
 Start: Draw an oval labeled "Start".
 Input: Draw a parallelogram with the label "Input N".
 Decision: Draw a diamond with the condition "Is N % 2 = 0?".
 Output (Yes Branch): If Yes, draw a parallelogram with "Display 'N is Even'".
 Output (No Branch): If No, draw a parallelogram with "Display 'N is Odd'".
 End: Draw an oval labeled "End".
 Connect: Use arrows to connect all the steps logically.

Figure 1.2. Flowchart to check whether a given number is odd or even

6
Example
Design a flowchart which gets two numbers and prints the sum of their value?

Answer
Flowchart Steps:
1. Start
2. Input Number 1 (A)
3. Input Number 2 (B)
4. Add A and B (Sum = A + B)
5. Display the Result (Sum)
6. End

Figure 1.2. Flowchart to add two number

7
1.2 Programming language
A programming language is a formal system used to communicate instructions to a computer,
enabling the creation of software applications, websites, and various other digital solutions. These
languages consist of syntax (rules governing structure) and semantics (meaning of constructs),
allowing developers to write code that machines can execute.

1.3 Programming Language Classifications


Programming languages can be grouped based on two main things: how close they are to machine
language (called levels of abstraction), how the code is written to solve problems (called
programming paradigms), and how the code is run on a computer (execution model).

1.) Levels of Abstraction:


This refers to how much the language hides the details of how the computer works. The more
abstract, the easier it is for humans to use.

 Low-Level Languages: These are very close to what the computer understands directly,
often requiring you to deal with hardware-specific details.
o First-Generation Languages (1GL): These are written in machine code, which
is the raw set of instructions that a computer can understand. It's very hard for
humans to read and write.
o Second-Generation Languages (2GL): These are assembly languages, which
are a bit easier than machine code. They use symbols to represent instructions, but
you still have to manage things like memory directly.

 High-Level Languages: These are designed to be much easier for humans to read and
write. They are more abstract and do not require you to worry much about the computer's
hardware.
o Third-Generation Languages (3GL): These languages, like C, Java, and Python,
are the most commonly used. They let you write clear instructions in a way that's
easier to understand and are usually more flexible for different tasks.

8
o Fourth-Generation Languages (4GL): These are designed for specific tasks,
such as managing databases. SQL (used to query databases) is a good example.
They are more specialized and often focus on simplifying complex tasks.
o Fifth-Generation Languages (5GL): These languages are used for advanced
fields like artificial intelligence. An example is Prolog, which is used to solve
problems based on logic and constraints rather than step-by-step instructions.

2.) Programming Paradigms:


This refers to how the logic of the code is structured and organized to address problems.

 Imperative Programming: In this style, you write instructions that explicitly tell the
computer how to perform a task, step by step. The computer follows these instructions
and changes its state as it goes along.
 Procedural Programming: This is a type of imperative programming where you
organize your code into procedures or functions that can be reused. Instead of writing
everything from scratch, you can call these pre-defined procedures to simplify the
process.
 Object-Oriented Programming (OOP): OOP organizes your code around objects, which
are pieces of data combined with functions that can manipulate that data. It’s a way to
make code more modular and reusable by focusing on objects that have attributes (data)
and methods (functions). Languages like Java and Python often use OOP.
 Functional Programming: Instead of writing instructions that change the computer's
state, functional programming focuses on creating functions that take inputs and return
outputs. It avoids changing data as much as possible, making the code easier to reason
about and often more predictable.
 Declarative Programming: In this paradigm, you focus on describing what you want the
program to do, rather than how to do it. You let the computer figure out the steps. This
approach is often used in database languages like SQL, where you specify the kind of
data you want without worrying about the process to retrieve it.

9
3.) Execution Model:
This refers to how the code is run on a computer. There are two main ways of executing code: by
compiling it or interpreting it.
 Compiled Languages: In compiled languages, the entire source code is converted into
machine code all at once by a compiler before execution.
o Examples: C, C++, Rust, Go.
o Advantages: These languages tend to run faster because they are directly translated
into machine code.
o Disadvantages: The development process can be slower because you need to
recompile the code every time you make changes.
 Interpreted Languages: In interpreted languages, the source code is translated into
machine code line-by-line by an interpreter at runtime.
o Examples: Python, JavaScript, Ruby, PHP.
o Advantages: These languages are easier to test and debug since you can
immediately see the effects of any changes without waiting for a compile step.
o Disadvantages: They tend to run slower than compiled languages because the
translation happens while the program is running.

1.4 Python Programming Language


Python is a versatile, high-level programming language known for its readability and broad
applicability across various domains, including web development, data analysis, artificial
intelligence, scientific computing, and more. Its extensive standard library and active community
contribute to its popularity among developers.

Features of Python:
 Readability: Python's syntax is designed to be clear and intuitive, making it accessible for
beginners and efficient for experienced programmers.
 Versatility: Python supports multiple programming paradigms, such as procedural, object-
oriented, and functional programming, allowing developers to choose the approach that best
fits their project needs.

10
 Extensive Libraries: The Python Package Index (PyPI) hosts a vast collection of third-party
libraries and frameworks, enabling rapid development and integration of various
functionalities.
 Community Support: A large and active community provides extensive documentation,
tutorials, and forums, facilitating learning and problem-solving.

Common Uses of Python:


 Web Development: Frameworks like Django and Flask streamline the creation of robust web
applications.
 Data Analysis and Visualization: Libraries such as Pandas, NumPy, and Matplotlib are
widely used for data manipulation and visualization.
 Machine Learning and AI: Tools like TensorFlow, Keras, and Scikit-learn support the
development of machine learning models and AI applications.
 Automation and Scripting: Python is often employed for automating repetitive tasks and
writing scripts to enhance productivity.

1.5 Python Installation


1. Download the Python Installer:
o Visit the official Python download page.
o Click on the "Download Python" button to get the latest version suitable for
Windows.

11
2. Run the Installer:
o Locate the downloaded installer file (e.g., python-3.x.x.exe) and double-click it to
start the installation process.

3. Customize Installation (Optional):


o In the installer window, you can choose to customize the installation by selecting
"Customize installation."
o Here, you can select optional features and advanced options.

12
4. Add Python to PATH:
o Ensure that the option to "Add Python to environment variables" is checked. This
allows you to run Python from the command line.
5. Complete the Installation:
o Click "Install Now" to proceed with the installation.

13
6. Verify the Python Installation
Once the installation is complete, you can verify it by opening the Command Prompt and typing
python --version to check the installed Python version.

Go to Start and enter cmd in the search bar. Click Command Prompt.

An example of the output is:

You can also check the version of Python by opening the IDLE application.
Go to Start and enter IDLE (python) in the search bar and then click the IDLE app

14
Chapter 2:
Basic Python Syntax and Operations

A Variable
A variable is a fundamental concept in programming that acts as a container for storing data values.
It holds information that can be referenced and manipulated throughout a program. The data stored
in a variable can vary during the execution of the program, which is why it’s called a "variable."
Variables play a crucial role in making programs dynamic and flexible, allowing developers to
store temporary data, perform calculations, and manage information effectively. Each variable is
identified by a unique name, known as an identifier, which is used to access the stored value when
needed.

Declaring Variables
When declaring variables, some programming languages require you to specify the type of data
the variable will hold (e.g., integer, string, float). However, in Python, there is no need to explicitly
declare the data type. Instead, Python automatically determines the data type based on the value
assigned to the variable.
Syntax:

Example

Variable Naming Rules


1. Must Start with a Letter or an Underscore (_)
When creating a variable name, it is essential to begin with either an alphabetic character
(A–Z or a–z) or an underscore (_). Variable names cannot start with a number or special
characters like @, $, or %. For example, valid variable names include _count and value1,
while 1value or #data are invalid and will result in a syntax error.

2. Can Contain Letters, Numbers, and Underscores


After the first character, variable names can include a combination of letters (both
uppercase and lowercase), digits (0–9), and underscores (_). This allows for descriptive
and readable variable names, such as student_name, age2024, or total_count. However,
spaces and special characters are not permitted within variable names. Instead of using
spaces, underscores are commonly used to improve readability.

15
3. Case-Sensitive
Variable names are case-sensitive, meaning that uppercase and lowercase letters are treated
as distinct characters. For example, Name, name, and NAME are considered three different
variables. This rule requires careful attention when referencing variables, as incorrect
capitalization can lead to errors or unexpected behavior in the code.
NB: It’s also a good practice to choose meaningful variable names that reflect the data they
represent, making the code easier to understand and maintain.

Multiple Assignments
1. Assign Multiple Values to Multiple Variables
In many programming languages, especially Python, you can assign multiple values to
multiple variables in a single line of code. This technique improves code readability and
reduces redundancy. The syntax involves separating both the variables and the values with
commas. For example:

In this case, x is assigned the value 10, y is assigned 20, and z is assigned 30.
2. Assign the Same Value to Multiple Variables
You can also assign the same value to multiple variables simultaneously. This is useful
when initializing several variables with the same default value. The syntax uses the equals
sign (=) to chain the assignments:

Here, all three variables (a, b, and c) are assigned the value 50. Changing the value of one
variable later will not affect the others unless they are mutable objects like lists.
3. Unpacking Collections
Multiple assignments can also be used to unpack values from collections such as lists,
tuples, or sets. This technique allows you to extract elements from a collection and assign
them to individual variables:

In this example, the tuple data contains three values, which are unpacked into the variables
m, n, and o respectively.

4. Using the Asterisk (*) for Extended Unpacking


In cases where the number of variables does not match the number of values, you can use
the asterisk (*) to capture multiple items into a list:

Here, p will be 1, r will be 5, and q will capture the middle values [2, 3, 4] as a list

16
Dynamic Typing:
 Python Allows Reassigning Variables to Different Data Types:

One of the key features of Python is dynamic typing, which means that you do not need
to explicitly declare the data type of a variable when creating it. Instead, Python
automatically determines the variable's data type based on the value assigned to it.
Additionally, you can reassign the same variable to a different data type at any point in
your code without any errors.

In this example, the variable x initially holds an integer value 10, then it is reassigned to a
string "Hello", and finally to a floating-point number 3.14. Python handles these changes
seamlessly because it dynamically manages variable types at runtime.

Benefits of Dynamic Typing:


 Flexibility: You can easily reuse variable names with different data types as your
program’s logic evolves.
 Concise Code: There’s no need to specify data types explicitly, making the code
cleaner and more readable.
 Rapid Development: It speeds up development, especially in scripting, prototyping,
and quick data manipulations.

Potential Drawbacks of Dynamic Typing:


 Runtime Errors: Since data types are checked at runtime, errors related to
incompatible data types may occur if not handled properly.
 Harder to Debug: It can sometimes lead to bugs that are difficult to trace, especially
in large codebases where variable types change unexpectedly.
 Performance Overhead: Dynamic type checking adds some overhead compared to
statically typed languages like C++ or Java.

17
Type Checking with type()
Although Python is dynamically typed, you can still check the type of a variable using the
type() function

Basic Data Types in Python


Python provides several fundamental data types that are used to store and manipulate different
kinds of data. Understanding these basic data types is essential for writing efficient and effective
Python programs.

1.) Integer (int)


 The int data type represents whole numbers, both positive and negative, including zero. It
does not support fractional or decimal parts.

Common Operations: You can perform arithmetic operations like addition (+), subtraction
(-), multiplication (*), division (/), modulus (%), exponentiation (**), and integer division
(//).

2.) Float (float)


 The float data type represents real numbers with decimal points. It is used for storing
numerical data that requires precision, such as scientific calculations, measurements, or
financial data.

Common Operations: Similar to integers, floats support arithmetic operations, but


division always results in a float, even if the result is a whole number.

3.) String (str)


 The str data type represents a sequence of characters (text) enclosed within single ('...'),
double ("..."), or triple quotes ('''...''' or """...""") for multi-line strings.

18
Common Operations: Strings support concatenation (+), repetition (*), slicing, indexing,
and built-in methods like .upper(), .lower(), .strip(), .replace(), and .split() for manipulation.

4.) Boolean (bool)


 The bool data type represents truth values: True or False. It is commonly used in
conditional statements, loops, and logical operations to control the flow of a program. In
Python, True and False are case-sensitive and must be written with an uppercase first letter.

 Booleans are often used with comparison operators (==, !=, >, <, >=, <=) and logical
operators (and, or, not).

Arithmetic Operations in Python


Python supports a wide range of arithmetic operations that allow you to perform mathematical
calculations. These operations can be applied to both integers (int) and floating-point numbers
(float).

Addition (+)
 Adds two numbers together.

Subtraction (-)
 Subtracts the right-hand operand from the left-hand operand.

19
Multiplication (*)
 Multiplies two numbers.

Division (/)
 Divides the left-hand operand by the right-hand operand. The result is always a float,
even if the division is exact.

Modulus (%)
 Returns the remainder of the division between two numbers.

Exponentiation (**)
 Raises the left-hand operand to the power of the right-hand operand (i.e., base **
exponent).

Integer Division (//)


 Performs floor division, which returns the largest integer less than or equal to the division
result (i.e., it discards the decimal part).

Combining Operations (Order of Precedence)


When performing multiple arithmetic operations in a single expression, Python follows the
standard order of precedence (PEMDAS):
 P: Parentheses ()
 E: Exponentiation **
 MD: Multiplication *, Division /, Floor Division //, Modulus % (from left to right)
 AS: Addition +, Subtraction - (from left to right)

20
To change the order of operations, you can use parentheses:

String Operations in Python

1) Concatenation (+):
 Concatenation is the process of joining two or more strings together using the + operator.

2) Repetition (*)
 The * operator is used to repeat a string multiple times.

3) Indexing
 Indexing allows you to access individual characters in a string using their position (index).
o Python uses zero-based indexing, meaning the first character is at index 0.
o You can use negative indexing to access characters from the end of the string.

21
4) Slicing
 Slicing allows you to extract a portion (substring) of a string using the syntax string
[start:end:step].
o start: The starting index (inclusive).
o end: The ending index (exclusive).
o step: (Optional) The step size or interval between characters.

Built-in String Methods:


Python provides many built-in methods for string manipulation. Here are some of the most
commonly used ones:

1) upper() –
o Converts all characters in the string to uppercase.

2) lower() –
o Converts all characters in the string to lowercase.

22
3) strip() –

 Removes leading and trailing whitespace (spaces, tabs, newlines) from the string.

4) replace()

 Replaces occurrences of a specified substring with another substring.

5) split() –

 Splits the string into a list of substrings based on a specified delimiter (default is space).

f-Strings (Formatted String Literals) — Python 3.6+


f-Strings are the most concise and readable way to embed expressions inside string literals.
They are created by prefixing the string with the letter f (or F) and using curly braces {} to insert
variables or expressions.

23
format() Method — Works in Python 2.7+ and 3.x
 The format() method inserts values into placeholders {} within a string.
 It’s flexible and allows for positional and named placeholders.

Syntax:

Example 1: Positional Formatting

Output:

Example 2: Named Placeholders

Reordering placeholders

Formatting numbers

24
Comparison Operators in Python
Comparison operators are used to compare two values. The result of a comparison is always a
boolean value: True if the comparison is correct, and False if it is not. These operators are often
used in conditional statements and loops.
Types of Comparison Operators:
1. Equal to (==)
This operator checks if the values on both sides are the same.
Example

2. Not Equal to (!=)


This checks if the values on both sides are different.

3. Greater Than (>)


Checks if the value on the left is greater than the value on the right.
Example:

4. Less Than (<)


Checks if the value on the left is less than the value on the right.

5. Greater Than or Equal to (>=)


Returns True if the value on the left is greater than or equal to the value on the right.

6. Less Than or Equal to (<=)


Returns True if the value on the left is less than or equal to the value on the right.
Example:

25
Logical Operators in Python
Logical operators are used to combine multiple conditions. They are typically used in conditional
statements like if, while, or assert to control the flow of programs.
Types of Logical Operators:
1. AND (and)
Returns True if both conditions are True. Otherwise, it returns False.
Example:

2. OR (or)
Returns True if at least one condition is True. If both are False, it returns False.
Example:

3. NOT (not)
Reverses the boolean value. If the condition is True, not makes it False, and vice versa.
Example:

Practical Example Combining Comparison and Logical Operators

26
Chapter 3:

Data Structures

Data structures are ways of organizing and storing data in a computer so that it can be accessed,
processed, and modified efficiently. They provide a systematic way to manage large amounts of
data for tasks such as searching, sorting, and performing complex calculations.

Types of Data Structures


Data structures can be broadly categorized into two main types:

1. Primitive Data Structures:


These are the basic data types provided by programming languages. They serve as the
building blocks for more complex data structures.
o Examples: Integers, Floats, Characters, Booleans, Pointers

2. Non-Primitive Data Structures:


These are more complex and are used to store large collections of data in an organized way.
They can be further divided into:
o Linear Data Structures (Lists, Tuples, Arrays, Stacks, Queues)
(A linear data structure stores data in a sequence, where elements are arranged
one after another).
o Non-Linear Data Structures (Trees, Graphs, Sets, Dictionaries)

3.1 Lists in Python


A list is an ordered, mutable (modifiable) collection of elements. It can contain items of different
data types such as integers, floats, strings, or even other lists. Lists allow duplicate elements and
maintain the order in which items are added.
List are created by enclosing elements in square brackets [], separated by commas.

Features of Lists
 Ordered: Maintains the order of elements as they are added.
 Mutable: Elements can be changed after the list is created.
 Dynamic: Can grow or shrink as needed (unlike arrays in some languages).
 Heterogeneous: Can contain elements of different data types.

27
Basic List Operations
1. Adding Elements to a List
 append(): Adds a single element to the end of the list.

 insert(index, element): Inserts an element at a specific index.

 extend(iterable): Adds multiple elements from another list (or any iterable) to the end.

2. Removing Elements from a List


 remove(element): Removes the first occurrence of the specified element.

 pop(index): Removes the element at the specified index. If no index is provided, it


removes the last element.

28
 clear(): Removes all elements from the list, making it empty.

Accessing Elements in a List

 Indexing:
Access individual elements using their index. Python uses zero-based indexing (the first
element is at index 0).

 Slicing:
Access a range of elements using the slice notation start:stop:step.

 Iteration Over a List


You can loop through a list using a for loop to perform actions on each element.

3.2 Tuples in Python


A tuple is an ordered, immutable collection of elements. This means that once a tuple is created,
its elements cannot be changed, added, or removed. Tuples can contain items of different data
types, including numbers, strings, and even other tuples.

Tuples are similar to lists, but their immutability makes them useful when you need data to remain
constant throughout the program.

Tuples are defined by enclosing elements in parentheses (), separated by commas. However, the
parentheses are optional—just the commas are enough to create a tuple.

29
NB: Without the comma, Python will treat (5) as an integer in parentheses, not a tuple.

Basic Tuple Operations


1. Accessing Elements
Tuples support indexing and slicing just like lists.

 Indexing:
Access individual elements using their index. Python uses zero-based indexing.

 Slicing:
Retrieve a range of elements using slice notation start:stop:step.

 Iteration Over a Tuple


You can iterate through a tuple using a for loop, just like with lists.

30
Output:

You can also use enumerate() to access both the index and the value:

3. Immutability of Tuples
The key characteristic of tuples is their immutability. This means:
 You cannot modify, add, or delete elements after the tuple is created.
 Attempting to change an element will result in an error.

Tuple Operations That Are Allowed


Although tuples are immutable, there are still several operations you can perform:
 Concatenation (+): Combines two tuples to create a new one.

31
 Repetition (*): Repeats the elements of a tuple.

 Membership Testing (in, not in): Checks if an element exists in a tuple.

 Length (len()): Returns the number of elements in the tuple.

 Index (index()): Finds the first occurrence of an element.

 Count (count()): Counts the number of times an element appears in the tuple.

32
Output

NB: Tuples are an essential data structure in Python, especially when dealing with constant,
unchangeable data. Their immutability provides security and performance benefits, making them
ideal for use cases where data integrity is crucial.

3.3 Sets in Python


A set is an unordered collection of unique elements. This means:
 Sets do not allow duplicate values.
 The elements are unordered, meaning they do not maintain the insertion order.
 Sets are mutable, allowing you to add or remove elements, but the elements themselves
must be immutable (e.g., numbers, strings, tuples).
Sets are commonly used to eliminate duplicate data, perform mathematical set operations like
union, intersection, and difference, and for fast membership testing.
Set is created by placing comma-separated elements inside curly braces {} or using the built-in
set() function.

33
NB: Curly braces {} create an empty dictionary, not a set. Use set() for an empty set.

Characteristics of Sets
1. Unordered:
The elements have no defined order. The output may differ each time you print the set.
2. Unique Elements:
Sets automatically remove duplicate values.

Mutable:
You can add or remove elements after creation, but the elements themselves must be immutable
(e.g., no lists or dictionaries inside a set).

Basic Set Operations


1.) Adding Elements to a Set
 add(): Adds a single element to the set.

 update(): Adds multiple elements from an iterable (like a list, tuple, or another set).

2. Removing Elements from a Set


 remove(): Removes a specified element. Raises an error if the element doesn’t exist.

 discard(): Removes a specified element. Does NOT raise an error if the element is
missing.

34
 pop(): Removes and returns a random element (since sets are unordered).
If the set is empty, it raises a KeyError.

 clear(): Removes all elements from the set.

3. Set Operations (Mathematical Operations)


Python provides built-in operators and methods for performing union, intersection, difference,
and symmetric difference operations.
 Union (| or union()): Combines all unique elements from both sets.

 Intersection (& or intersection()): Returns elements common to both sets.

 Difference (- or difference()): Returns elements in set A but not in set B.

 Symmetric Difference (^ or symmetric_difference()): Returns elements in either set A


or B, but not in both.

4. Membership Testing
You can check if an element exists in a set using in or not in.

35
5. Other Useful Set Methods
 issubset(): Checks if all elements of one set are present in another set.

 issuperset(): Checks if a set contains all elements of another set.

 isdisjoint(): Returns True if two sets have no elements in common.

3.4 Dictionaries in Python


A dictionary is a collection of key-value pairs.
 Keys are unique and immutable (e.g., strings, numbers, tuples).
 Values can be of any data type and can be duplicated.

 Dictionaries are mutable, allowing you to add, modify, or delete key-value pairs after
creation.
Dictionaries are also known as hash maps or associative arrays in other programming languages.
Dictionary is created using curly braces {} or the dict() constructor.

36
Characteristics of Dictionaries
1. Key-Value Structure
Each item is a pair: key → value.
2. Unique Keys
Keys must be unique; if a duplicate key is assigned, the latest value overwrites the previous
one.

3. Mutable
You can modify, add, or delete key-value pairs after the dictionary is created.

Basic Dictionary Operations


1. Adding or Updating Elements
You can add a new key-value pair or update an existing key using square brackets [] or the update()
method.

 Using [] to Add or Update:

 Using update() to Add/Update Multiple Pairs

37
2. Accessing Elements
You can access dictionary values by referencing their keys.

 Using [] (Direct Access):

NB: If the key doesn’t exist, it raises a KeyError.

 Using get() (Safe Access):

3. Removing Elements
 Using del Statement: Removes a key-value pair by key.

 NB: Raises KeyError if the key doesn’t exist.

 Using pop(): Removes a key and returns its value. Raises KeyError if the key isn’t found
(unless a default is provided).

38
 Using clear(): Removes all key-value pairs, leaving an empty dictionary.

Iterating Through Dictionaries


You can loop through dictionaries using for loops

 Iterating Over Keys:

 Iterating Over Values:

 Iterating Over Key-Value Pairs:

 Using enumerate() for Indexing:

39
Dictionary Methods

Nested Dictionaries
Dictionaries can contain other dictionaries, allowing for complex data structures.

40
You can also loop through nested dictionaries:

Dictionary Comprehensions
Similar to list comprehensions, you can create dictionaries using a concise syntax.

 Example 1: Squaring numbers

 Example 2: Filtering items

3.5 Stacks in Python


A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle.
 The last element added to the stack is the first one to be removed.

 Think of a stack of plates: you add (push) plates on top and remove (pop) plates from the
top.

Stack Operations:
1. Push: Add an element to the top of the stack (append() in Python).
2. Pop: Remove the top element from the stack (pop() in Python).
3. Peek/Top: View the top element without removing it.
4. isEmpty: Check if the stack is empty.
5. Size: Get the number of elements in the stack.

41
Implementation of Stack Using Lists

Check if Empty:

Size of Stack:

42
3.6 Queues in Python
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle.
 The first element added to the queue is the first one to be removed.

Queue Operations:
1. Enqueue: Add an element to the rear of the queue.
2. Dequeue: Remove an element from the front of the queue.
3. Peek/Front: View the front element without removing it.
4. isEmpty: Check if the queue is empty.
5. Size: Get the number of elements in the queue.

Implementation Using collections.deque

43
3.7 Arrays in Python
An Array is a data structure that stores a collection of items of the same data type in contiguous
memory locations.
 Arrays allow efficient access to elements using an index.
 They are commonly used when working with large amounts of numerical data.

While lists in Python can store different data types, arrays are more memory-efficient for
numerical data because they are optimized for performance.

Using the array Module in Python

 Python provides the array module to work with arrays. Unlike lists, arrays from this
module are restricted to holding elements of the same data type.

Importing the array Module:

Declaring an Array

 'i' is a typecode specifying the data type (signed integer in this case).
 The elements [10, 20, 30, 40, 50] are stored contiguously.

44
Common Typecodes in Arrays

Array Operations
1. Adding Elements
 append() → Adds an element at the end.
 insert() → Inserts an element at a specific index.
 extend() → Adds multiple elements from another array or list.

2. Removing Elements
 remove() → Removes the first occurrence of a specific value.
 pop() → Removes the element at a given index (or the last element by default).

45
3. Accessing Elements
 Indexing: Access specific elements using their index (0-based).
 Slicing: Retrieve a range of elements.

4. Iterating Over Arrays

Or using indices:

5. Other Useful Methods


 index(value) → Returns the index of the first occurrence of value.
 reverse() → Reverses the array in-place.

46

You might also like