Part 1 Handout Intro to Programming With Python
Part 1 Handout Intro to Programming With Python
TARKWA
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.
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
4
Step 5: Output the sum
2.) Flowcharts:
A graphical representation of the algorithm using shapes to represent steps and arrows for
flow.
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.
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
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.
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.
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.
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.
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.
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.
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
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.
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.
17
Type Checking with type()
Although Python is dynamically typed, you can still check the type of a variable using the
type() function
Common Operations: You can perform arithmetic operations like addition (+), subtraction
(-), multiplication (*), division (/), modulus (%), exponentiation (**), and integer division
(//).
18
Common Operations: Strings support concatenation (+), repetition (*), slicing, indexing,
and built-in methods like .upper(), .lower(), .strip(), .replace(), and .split() for manipulation.
Booleans are often used with comparison operators (==, !=, >, <, >=, <=) and logical
operators (and, or, not).
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).
20
To change the order of operations, you can use parentheses:
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.
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()
5) split() –
Splits the string into a list of substrings based on a specified delimiter (default is space).
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:
Output:
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
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:
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.
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.
extend(iterable): Adds multiple elements from another list (or any iterable) to the end.
28
clear(): Removes all elements from the list, making it empty.
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.
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.
Indexing:
Access individual elements using their index. Python uses zero-based indexing.
Slicing:
Retrieve a range of elements using slice notation start:stop:step.
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.
31
Repetition (*): Repeats the elements of a tuple.
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.
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).
update(): Adds multiple elements from an iterable (like a list, tuple, or another set).
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.
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.
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.
37
2. Accessing Elements
You can access dictionary values by referencing their keys.
3. Removing Elements
Using del Statement: Removes a key-value pair by key.
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.
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.
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.
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.
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.
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.
Or using indices:
46