Python
Actions in Python:
An algorithm must be expressed in Python as a sequence of
“actions”
Purpose of actions:
• Creating or modifying data: These actions take in data, perform
sequential, conditional, or repetitive execution on the data and
produce other data.
• Interacting with the environment: Our solutions will usually
involve interacting with the user or the peripherals of the
computer to take in (input) data or take out (output) data.
1
Python
Types of actions:
Expression: An expression (e.g., 3 + 4 * 5) specifies a calculation
which, when evaluated (performed), yields some data as a result.
An expression can consist of:
• basic data (integer, floating point, Boolean, etc.) or
container data (e.g., string, list, set, etc.).
• expressions involving operations among data and other
expressions.
• functions acting on expressions.
2
Python
Types of actions:
Statement: Unlike an expression, a statement does not return data
as a result. It can either be basic or compound.
• Basic statement: A basic statement can be, e.g., for
storing the result of an expression in a memory location
(an assignment statement for further use in subsequent
actions), deleting an item from a collection of data, etc.
Each statement has its special syntax that generally
involves a special keyword.
• Compound statement: Compound statements are
composed of statements, and control the execution of
those statements in some way.
3
Python
Naming and Printing Data
Variables: Name to data and use that name to access it
Printing data: Python provides the print() function to display data
items on the screen:
4
Python
Basic data in Python: Numbers
Integers (e.g., 73)
Floating point numbers (e.g., 73., 6.8e-6)
Complex numbers (e.g., 2-5j)
From Python version 3, integers do not have fixed-size representation,
and their size is only limited by available memory
5
Python
Basic data in Python: Numbers
As for the float type, Python uses the 64-bit IEEE 754 standard which
can represent numbers in the range
[2.2250738585072014E-308, 1.7976931348623157E+308].
6
Python
Basic data in Python: Numbers
abs(<Number>): Absolute value of the number
pow(<Number1>, <Number2>): Power
7
Python
Basic data in Python: Numbers
round(<FloatNumber>): Rounds the floating point number to the
closest integer
Functions from the math library: sqrt(), sin(), cos(), log(), etc
8
Python
Basic data in Python: Booleans
Python provides the bool data type which allows only two values:
True and False
Comparison operations
Logical operations
• 0 (the integer zero)
• 0.0 (the floating-point number zero)
• "" (the empty string)
• [] (the empty list)
• {} (the empty dictionary)
are interpreted as False.
9
Python
Basic data in Python: Booleans
With Boolean values, we can use the “not” (negation or inverse),
“and”, and “or” operations.
10
Python
Container data in Python: (str, tuple, list, dict, set)
String (str): A string can hold a sequence of characters or only a
single character. A string cannot be modified after creation.
List (list): A list can hold ordered sets of all data types in Python
(including another list). The elements of a list can be modified after
creation.
Tuple (tuple): The tuple type is very similar to the list type, but the
elements cannot be modified after creation (similar to strings).
Dictionary (dict): A very efficient data type that implements a
mapping from a set of numbers, Booleans, strings, and tuples to
any set of data in Python. Dictionaries are easily modifiable and
extendable
11
Python
Container data in Python: (str, tuple, list, dict, set)
Mutability Versus Immutability
Some container types are created as “frozen”. After creating
them, you can completely destroy them, but you cannot change
or delete their individual elements. This is called immutability.
Strings and tuples are immutable, whereas lists, dictionaries,
and sets are mutable. With a mutable container, it is possible to
add new elements and change or delete existing ones.
12
Python
Accessing Elements in Sequential Containers
string, list, and tuple, are called sequential containers
Index starts from 0 in Python
13
Python
Accessing Elements in Sequential Containers
string, list, and tuple, are called sequential containers
• Start index is first to be accessed.
• End index is where accessing stops (element at end index is
not accessed—that is, the end index is not inclusive).
• After element at [start] is accessed first, [start + increment] is
accessed next. This goes on until the accessed position is
equal to or greater than the end index.
• For negative indexing, a negative increment has to work from
the bigger index towards the lesser, so (start index > end index)
is expected. 14
Python
Accessing Elements in Sequential Containers
Number of elements: For all containers, len() is a built-in function
that returns the count of elements in the container that is given as
argument to it
Concatenation: String, tuple, and list data types can be combined
using the “+” operation
15
Python
Accessing Elements in Sequential Containers
Repetition: String, tuple, and list data types can be repeated using
the “*” operation
Membership: All containers can be checked for whether they
contain a certain item as an element using in and not in operations
16
Python
String in Python
A string is denoted by enclosing the character sequence
between a pair of quotes (’Example String’) or double quotes
("Example String").
A string surrounded with triple double quotes ("""Example
String""") allows you to have any combination of quotes and line
breaks within a sequence and Python will still view it as a single
entity.
"Hello World!"
’Hello World!’
’He said: "Hello World!" and walked towards the house.’
"A"
"""
Andrew said:
"Come here, doggy".
The dog barked in reply: ’woof’
17
"""
Python
String in Python
The backslash (\) is a special character in Python strings, also
known as the escape character. It is used in representing
certain, the so-called, unprintable characters: \t is a tab, \n is a
newline,etc
For example, \’ is the single quote character. ’It\’s raining’
therefore is a valid string and equivalent to "It’s raining".
18
Python
String in Python
19
Python
Examples with string in Python
20
Python
Examples with string in Python
21
Python
Examples with string in Python
22
Python
Examples with string in Python
23
Python
Examples with string in Python
24
Python
Examples with string in Python
In addition to using quotes for string creation, str() function can be
used to create a string from its argument
25
Python
Examples with string in Python
Evaluating a string:
Deletion and Insertion from/to Strings
26
Python
Examples with string in Python
27
Python
Examples with string in Python
28
Python
Lists in Python:
Lists are created by enclosing elements into a pair of brackets and
separating them with commas, e.g., ["this", "is", "a", "list"].
29
Python
Tuples in Python:
Tuples are created by enclosing elements into a pair of parentheses,
e.g., ("this", "is", "a", "tuple")
30
Python
Lists and Tuples in Python:
There is no restriction on the elements of lists and tuples: They
can be any data (basic or container); tuples can become list
members as well, or vice versa
31
Python
Lists and Tuples in Python:
Deletion from lists
32
Python
Lists and Tuples in Python:
Insertion into lists
33
Python
Lists and Tuples in Python:
Insertion into lists
34
Python
Lists and Tuples in Python:
Concatenation, repetition, and membership with lists and tuples:
35
Python
Lists and Tuples in Python:
How would you store the coefficient matrix of the following system
of equations?
36
Python
Dictionaries in Python:
A list, tuple, or string data type stores a certain element at each
numerical index. Similarly, a dictionary stores an element (value)
for each key (non-numeric). In other words, a dictionary is just a
mapping from keys to values
37
Python
Dictionaries in Python:
A dictionary is represented as key–value pairs, each separated by
a colon sign (:) and all enclosed in a pair of curly braces.
38
Python
Dictionaries in Python:
39
Python
Dictionaries in Python:
40
Python
Expressions in Python:
Expressions such as 3 + 4 describe calculation of an operation
among data. When an expression is evaluated, operations in the
expression are applied to data specified in expression using
operators and a resulting value is provided.
Operator
Operand
41
Python
Expressions in Python:
Operations:
• Arithmetic (addition, subtraction, multiplication, division,
exponentiation)
• logic (and, or, not)
• container (indexing, membership)
• comparison (less, less-than, equality, non-equality, greater,
greater-than)
42
Python
Expressions in Python:
43
Python
Expressions in Python:
• Python compares lists lexicographically, just like strings
• Comparison is done element by element, from left to right, until
a difference is found, or one list is exhausted
44
Python
Expressions in Python: Precedence and Associativity
• Operator Precedence tells us which operators should be
evaluated first in an expression
• Associativity determines the direction in which operators with
the same precedence are evaluated
Increasing precedence
45
Python
Expressions in Python: Precedence and Associativity
46
Python
Implicit and Explicit Type Conversion (Casting)
47
Python
Basic statements: Assignment Statement and Variables
• A variable is a placeholder (in memory) for information that can
be referenced and manipulated during program execution
• Variables act like containers that can store different types of
data values
• Unlike many programming languages, Python does not require
explicit type declaration - the type is automatically inferred
based on the assigned value
48
Python
Basic statements: Assignment Statement and Variables
Single assignments
Single assignments
49
Python
Basic statements: Assignment Statement and Variables
Multiple Assignments
Multiple Assignments
with Different Values
Multiple Assignments
with Different Values
50
Python
Basic statements: Assignment Statement and Variables
Swapping Values of
Variables
Alternatively
51
Python
Basic statements: Assignment Statement and Variables
8.0
3 3
52
Python
Basic statements: Variables and Aliasing
Aliasing in Python occurs when two variables refer to same data (or
object) in memory, essentially creating a second name for an
existing piece of data
53
Python
Basic statements: Variables and Aliasing
54
Python
Basic statements: Variables and Aliasing
• Aliasing can be problematic with mutable objects like lists,
where changes to one variable will affect the other
• For immutable objects like strings and integers, aliasing is
generally safe
• To avoid unintended modifications, you can use techniques like
cloning (creating a new copy) for mutable objects
55
Python
Basic statements: Naming Variables
• Programmers usually choose a name for a variable such that
the name signifies what the content will be.
• In Python, variable names may be arbitrarily long. They may
contain letters (from the English alphabet), as well as numbers
and underscores, but they must start with a letter or an
underscore.
• While using uppercase letters is allowed, bear in mind that
programmers reserve starting with an upper case to
differentiate a property (i.e., scope) of the variable
56
Python
Basic statements: Guidelines for Naming Variables
• It is a better practice to name variables that reflect the value
they are going to store.
57
Python
Basic statements: Guidelines for Naming Variables
• Use “Single Responsibility Principle”
58
Python
Basic statements: Guidelines for Naming Variables
• Variable names should be pronounceable, making them easier
to remember.
• Use i, j, k, m, n only for counting: Programmers implicitly
recognize such variables as holding integers (for historical
reasons).
• Avoid the single character variable l as it can be easily
confused with 1 (one).
59
Python
Basic statements: Guidelines for Naming Variables
• If you are using multiple words as a variable name, choose one
of the following:
Make all words lowercase, combine them using _ as separator;
e.g., highest_midterm_grade, shortest_path_distance_up_to_now.
Capitalize the first letter of each word, except for the first, and
combine all words directly without using a separator; e.g.,
highestMidtermGrade, shortestPathDistanceUpToNow
60
Python
Basic statements: Reserved names in Python
• Reserved names cannot be used as variable names
• It is possible to use the name of a built-in function as a variable
name (e.g., len = 20). This, however, loses access to such a
built-in function until the interpreter is restarted.
61
Python
Basic statements: Action Input/Output
62
Python
Basic statements: Pass statement
pass statement in Python is a null statement used as a placeholder
for future code implementation.
63
Python
Basic statements: Data packaged in libraries
Python, like many high-level programming languages, provides a
wide spectrum of actions and data predefined and organized in
“packages” that are called as libraries.
64
Python
Basic statements: Data packaged in libraries
To find out what is available
in a library or any data item,
you can use the dir() function
65
Python
Basic statements: Actions from interpreter
Explore quit(), exit(), Ctrl+D options when you work with interpreter
How will run a python file from its interpreter? Explore
python3 [Link]
cat [Link]
66
Python
Basic statements: Writing actions into a file
How will run a python file from its interpreter using command-line
arguments?
67