Lecture Notes
Lecture Notes
[Link] qi9tndw
Week01 Syllabus
Week02 Introduction to Python
Natural Languages vs. Programming Languages
A language is a tool for expressing and recording thoughts.
Computers have their own language called
machine language. Machine languages are created
by humans, no computer is currently capable of
creating a new language. A complete set of known
commands is called an instruction list (IL).
Elements of a Language
• Alphabet is a set of symbols to build words of
a certain language.
• Lexis is a set of words the language o ers its
users.
• Syntax is a set of rules used to determine if a
certain string of words forms a valid sentence.
• Semantics is a set of rules determining if a
certain phrase makes sense.
Compilation Interpretation
Python Goals
• an easy and intuitive language just as powerful
as those of the major competitors
• open source, so anyone can contribute
to its development
• code that is as understandable as plain English
• suitable for everyday tasks, allowing for short
development times
[Link]
s q
[Link] i z
las in-c
fi
Week02 Introduction to Python
Function Name
A function can cause some e ect
or evaluate a value, or both.
[Link]
Argument
• Positional arguments
• Keyword arguments
fi
ff
Week02 Introduction to Python
Literals
A literal is data whose values are determined by the literal
itself. Literals are used to encode data and put them into code.
[Link]
•String
•Integer
•Float
•Complex
•Boolean
•Binary
•Octal
•Hexadecimal
•Scienti c Notation
fi
Week02 Introduction to Python
Basic Operators
An operator is a symbol of the programming language, which is
able to operate on the values.
Multiplication Division
Integer Float
Float Float
Float Float
Float Float
Modulo Addition
Integer Integer
Float Float
Float
Float
Week02 Introduction to Python
Operator Priorities
An operator is a symbol of the programming language, which is
able to operate on the values.
[Link]
• + (unary)
• - (unary)
• ** (right-sided binding)
• *
• /
• //
• % (left-sided binding)
• + (binary)
• - (binary)
Week02 Introduction to Python
Variables
Variables are symbols for memory addresses.
[Link]
Week02 Introduction to Python
Identi er Names
For variables, functions, classes etc. we use identi er names.
We must obey some rules and we should follow some naming
conventions.
• Names are case sensitive.
• Names can be a combination of letters, digits, and
underscore.
• Names can only start with a letter or underscore,
can not start with a digit.
• Keywords can not be used as a name.
s q u i z
s
[Link]
-cla in
fi
fi
Week02 Introduction to Python
Your First Homework
Week01/info_ rstname_lastname.py
A string variable with the name student_id that contains
your student id.
A string variable with the name full_name that contains
your full name.
Week02/types_ rstname_lastname.py
An integer with the name: my_int
A oat with the name: my_ oat
A boolean with the name: my_bool
A complex with the name: my_complex
fl
fi
fi
fl
Week02 Introduction to Python
Your First Homework
Week03 Introduction to Python
Equality & Identity & Comparison
Equality
Left- or Right-sided?
+, - unary
** binary
Comparison Chaining *, /, //, % binary
+, - binary
!=, == binary
Conditional Execution
if statement
Ternary Operator
Week03 Introduction to Python
Loops
• The program generates a random
number between 1 and 10.
• The user is asked to guess the
QUESTION
number.
• The user is given feedback if the
guess is too low or too high.
• The user is asked to guess again
until the correct number is guessed.
number.
• The program prints the numbers
from 0 to n-1.
s
[Link]
s q u iz
cla in-
Raising Exceptions
P 3 10 7
PE
Multiple Type Hints for Arguments ( > Python 3.10 )
o n 3.10
>P y t h
Lambda Functions
Function Docstrings
7
PEP 25
fi
fi
Week04 Introduction to Python
Docstrings PEP 257
A docstring is a string literal that occurs as the rst statement in
a module, function, class or method de nition. Such a docstring
becomes the __doc__ special attribute of that object.
One-line Docstrings
Multi-line Docstrings
E P 45 7
P
*args and **kwargs
fi
Week04 Introduction to Python
Function Attributes PEP 232
Functions already have a number of attributes such as __doc__,
__annotations__, __defaults__, etc. Like everything in Python,
functions are also objects, therefore, user can add a dictionary as
attributes by using get / set methods to __dict__.
Week04 Introduction to Python
Function Attributes PEP 232
Functions already have a number of attributes such as __doc__,
__annotations__, __defaults__, etc. Like everything in Python,
functions are also objects, therefore, user can add a dictionary as
attributes by using get / set methods to __dict__.
Week04 Introduction to Python
Nested Scopes PEP 227
Function objects can have methods. These methods can be used
as inner functions and can be useful for encapsulation.
s q ui z
-cla s
[Link]
in
Week04 Introduction to Python
Week04/functions_ rstname_lastname.py
custom_power custom_equation
A lambda function A function returns oat
Two parameters (x and e) Five integer parameters (x, y, a, b, c)
x is positional-only x is positional-only with default value 0
e is positional-or-keyword y is positional-only with default value 0
x has the default value 0 a is positional-or-keyword with default value 1
e has the default value 1 b is positional-or-keyword with default value 1
Returns x**e c is keyword-only with default value 1
Function signature must include all annotations
Docstring must be in reST format.
Returns (x**a + y**b) / c
fn_w_counter Examples
A function returns a tuple of an int
and a dictionary
Function must count the number of
calls with caller information
Returning integer is the total number
of calls
Returning dictionary with string keys
and integer values includes the caller
( _ _name_ _ ) as key, the number of
call coming from this caller as value.
Week04/decorators_ rstname_lastname.py
performance
A decorator which measures the performance of functions and also saves
some statistics.
Has three attributes: counter, total_time, total_mem
Attribute counter stores the number of times that the decorator has been
called.
Attribute total_time stores the number of total time that the functions
took.
Attribute total_mem stores the total memory in bytes that the functions
consumed.
fl
fi
fi
Week05 Asynchronous Programming with Python
The problems in computer programming can be categorized
based on the primary source of their performance
bottlenecks.
I/O-bound Problems
While solving an I/O-bound problem, the system spends a
signi cant amount of time waiting for input/output
operations.
Subcategories can be Disk I/O (reading or writing to a hard
drive) and Network I/O (waiting for data from a remote
server).
The solutions often involve asynchronous programming,
caching, or optimizing the I/O operations.
CPU-bound Problems
For CPU-bound problems, computational processing is the
bottleneck.
Speeding up the computation requires either a faster CPU
or optimizing the computation itself.
Parallel processing, algorithm optimization, or o oading
computations to other systems or specialized hardware (like
GPUs) are common strategies to overcome these problems.
Memory-bound Problems
Problems where the primary constraint is the system’s
memory.
Solutions can involve optimizing data structures, utilizing
external memory storage, or employing algorithms that are
more memory-e cient.
fi
ffi
ffl
Week05 Asynchronous Programming with Python
return
Regular functions returning a speci ed value back to the
caller and terminates the function’s execution.
Once the function returns a value using return, its state
lost. Subsequent calls to the function start the execution
from the beginning of the function.
Used to compute a value and return it to caller immediately.
yield
Used in special functions known as generators. Produces a
series of values for iteration using a lazy evaluation
approach (values are generated on-the- y, not stored in
memory).
When a function using the yield keyword is called, it returns
a generator object without even beginning execution of the
function.
Upon calling next(), the function runs until it encounters the
yield keyword. The function’s execution is paused, and the
yielded value is returned. Subsequent calls to next() resume
the function’s execution immediately after the last yield
statement.
Once all values have been yielded, the generator raises a
StopIteration exception.
s q
[Link]
a s uiz
cl in-
Week05/awaitme_ rstname_lastname.py
awaitme
A decorator which turns any function into a coroutine.
It must pass all the arguments to the function properly.
If function returns any value, so the decorator returns it.
Context Manager
[Link]
Week06 Asynchronous Programming with Python
Time to go asynchronous!
Asynchronous
Context Manager
[Link]
Week06 Asynchronous Programming with Python
s q
[Link]
a s uiz
cl in-
Week06/timer_ rstname_lastname.py
Timer
Create a class Timer that measures the time taken
by the block of code it manages.
Timer class must be a context manager.
The class must have two public attributes start_time
and end_time, which are for the starting and the ending
times, respectively.
Good Luck
for your midterm!
fi
fi
Week07 Multithread Programming with Python
................. 1
. .. x
(area of circle) (constant)
=
(area of square) 4
(inner points)
estimated value of π = 4 ×
(total points)
Creating Threads
From a Function From a Class
with Arguments
Synchronization
Daemon Threads
Week07 Multithread Programming with Python
.1...............
.............
................. 1
. .. x
s q u i z
s
[Link]
-cla in
Week07/threaded_ rstname_lastname.py
threaded
Create a decorator that creates n number of threads
from a function
Decorator must accept an integer argument: n
The decorator must create, start and then nally
synchronize the threads by waiting them to nish
................. 1
. .. x
(area of circle) (constant)
=
(area of square) 4
(inner points)
estimated value of π = 4 ×
(total points)
Embarrassingly Parallel
A problem type, which its solution requires very little or
even no e ort to parallelize. The key point is that there
is no need of communication between the tasks.
Atomic Part
ff
Week08 Multithread Programming with Python
Atomic Part
Convert Atomic Operation to Thread
Condition to nalize
the solution
The maximum
number of
threads to run
simultaneously
Creator Thread for Atomic Operations
Unpredictable Results
Time
Compiler Explorer Never overlaps with each other
[Link]
Week08 Multithread Programming with Python
Time
count = 0
Lock
Without a Mutex
Time
count = 0
Lock
count = 1
count = 1
count = 2
count = 1
count = 2
Lock
count = 2
count = 2
count = 3
count = 2
Using Locks
count = 2
count = 3
count = 3
count = 3
count = 3
count = 3 Now
it is
count = 4
count = 4 safe
count = 4
count = 4
but
very
count = 5
slow!
9 increments s s q u iz
[Link]
Deadlock Deadlock
When two or more
threads are waiting on
each other to release
locks, causing an
in nite waiting state.
Semaphore
A semaphore is used to
limit the number of
threads accessing a
shared resource. A
counter that decreases
when a thread acquires
it and increases when a
thread releases it.
Barrier
It ensures that multiple
threads reach a certain
point in execution
before any of them
proceed.
Condition
It is used for
synchronization by
communicating
between threads
fi
ff
Week09 Thread Synchronization
Synchronization Concepts
Synchronization ensures that threads coordinate their
actions e ectively when accessing shared resources.
Without proper synchronization, issues like race
conditions, deadlock, and inconsistent data states
can arise, leading to unpredictable program behavior.
Deadlock Semaphore
When two or more
threads are waiting on
each other to release
locks, causing an
in nite waiting state.
Semaphore
A semaphore is used to
limit the number of
threads accessing a
shared resource. A
counter that decreases
when a thread acquires
it and increases when a
thread releases it.
Barrier
It ensures that multiple
threads reach a certain
point in execution
before any of them
proceed.
Condition
It is used for
synchronization by
communicating
between threads
fi
ff
Week09 Thread Synchronization
Synchronization Concepts
Synchronization ensures that threads coordinate their
actions e ectively when accessing shared resources.
Without proper synchronization, issues like race
conditions, deadlock, and inconsistent data states
can arise, leading to unpredictable program behavior.
Deadlock Barrier
When two or more
threads are waiting on
each other to release
locks, causing an
in nite waiting state.
Semaphore
A semaphore is used to
limit the number of
threads accessing a
shared resource. A
counter that decreases
when a thread acquires
it and increases when a
thread releases it.
Barrier
It ensures that multiple
threads reach a certain
point in execution
before any of them
proceed.
Condition
It is used for
synchronization by
communicating
between threads
fi
ff
Week09 Thread Synchronization
Synchronization Concepts
Synchronization ensures that threads coordinate their
actions e ectively when accessing shared resources.
Without proper synchronization, issues like race
conditions, deadlock, and inconsistent data states
can arise, leading to unpredictable program behavior.
Deadlock Condition
When two or more
threads are waiting on
each other to release
locks, causing an
in nite waiting state.
Semaphore
A semaphore is used to
limit the number of
threads accessing a
shared resource. A
counter that decreases
when a thread acquires
it and increases when a
thread releases it.
Barrier
It ensures that multiple
threads reach a certain
point in execution
before any of them
proceed.
Condition
It is used for
synchronization by
communicating
between threads
fi
ff
Week09 Thread Synchronization
From Function
From Class
Pass Arguments Creating Processes
q u i z
[Link]
s
🙋 Good luck, see you again in -clas
r/YmkRr7SKE4
fl