The Python Keywords:
and as assert break class continue
def del elif else except exec
finally for from global if inport
in is lambda nonlocal not or
pass raise return try while with
yield True False None
Avariable is a name that refers to a value.
Note: Don‟t name a variable with Python keywords
An assignment statement in a function creates a local variable, or a temporary
variable which only exists inside the function and you cannot use it outside.
y = x * x
The variable y is a local variable and it only exists while the function square is being executed – we call
this its lifetime. When the execution of the function terminates (returns), the local variables are
Formal parameters are also local and act like local variables.
All the variables that are defined as local variables.
An expression is a combination of values, variables, operators, and calls to functions
Note: Expressions need to be evaluated; if you ask Python to print an expression, the interpreter will evaluate
the expression and display the result
Astatement is an instruction that the Python interpreter can execute.
e.g.Assignment Statements, While Statements, For Statements, If Statements, Import Statements…
Assignment Statements: Create new variables and also give them values to refer to
It links a name, on the left hand side of the operator, with a value, on the right.
Notes: „n = 17‟reads
„n is assigned 17‟
or „n gets the value 17‟
or „n is a reference to the object 17‟
or „n refers to the object 17‟
Don‟t say „n equals 17‟
The assignment token, „=‟, should not be confused with equality, „==‟.
Reassignment and Updating Variables:
x = 1
x = 2 # This is reassignment
x = 1 # initialize x before updating variables
x = x + 1 # This is updating variables
# updating a variable by adding 1 is called an increment or bumping a variable
# subtracting 1 is called a decrement
y = 1
y = y -1
The input function allows the user to provide a prompt string
input(„Message that will be shown in the screen‟)
Note: the input function returns a string value no matter what the user inputs.
int (integer), str (string), bool (boolean), float, list, tuple, object
Primitive Data Type:
int, float and bool are considered to be simple or primitive data types because
their values are not composed of any smaller parts. They cannot be broken down.
Collection Data Type:
Types that are comprised of smaller pieces are called collection data types, like strings and lists.
Helps evaluating what class a value falls into.
Type Conversion Functions:
The functions int(), float() and str() will (attempt to) convert their arguments into
types int, float and str respectively.
# int() doesn‟t round to the closest int
isinstance(object, class) Return whether an object is an instance of a class or of a
isinstance(object, type) Return whether an object is of a type or not.
isinstance(object, tuple) isinstance(x, (A, B, …)) is a shortcut for isinstance(x, A)
or isinstance(x, B) or …
>>> isinstance(1, int)
Special tokens that represent computations
i.e. +, -, /, //(asterisk -> multiplica, **)(exponentiatio, ( )(parenthesis -> grouping)……
Values the operator works on
The division operator, „/‟, always evaluates to a floating point result;
The integer division, „//‟, gives the biggest integer which is smaller than the result
e.g. >>> 7 / 4
>>> 7 // 4
>>> 7 % 4
The modulus operator, or the remainder operator, works on integers and yields the
remainder when the first operand is divided by the second.
Note: a == a//b*b + a%b
check whether one number is divisible by another – if x % y is 0, x is divisible by y;
extract the right-most digit(s) from a number
>>> 123 % 10
>>> 123 % 100
Order of Operations:
the order of evaluation depends on the rules of precedence (the same one in math).
i.e. ** > (* = /) > (+ = -)
note: the right-most ** gets done first. E.g. 2**3**2 = 2**(3**2)
Anamed sequence of statements that belong together.
def name(parameters): #The header line
statements #The code block
In the def, the parameter list is more specifically known as the formal parameters. When we
use the function, we provide values to the formal parameters; these values, called arguments
or actual parameters, are passed to the function by the user.
The triple-quoted string after the function header used as documentation of functions.
It is retrievable at runtime with the expression .__doc__
The „return y‟above is a return statement.
The return statement not only causes the function to return a value, but it also returns the flow
of control back to the place in the program where the function call was made.
Note: If we accidentally used print where we mean return, the function will return the value None by
To make a function run we need a function call, or a function invocation. Function calls
contain the name of the function to be executed followed by a list of values, called arguments,
which are assigned to the parameters in the function definition.
Functions that return values.
E.g. range(), int(), abs(), max()…
Abuilt-in function for computing the absolute value of a number.
Take in more than one arguments (values or expressions) and return the
>>> max(7, 11, 3*11)
Note: max() also works on lists of values.
The Accumulator Pattern:
The pattern of iterating the updating of a variable.
runningtotal = 0
# we need a variable to remember the ‘running total’
# It should be initialized with a value of zero
for counter in range(x):
# the iteration is performed x times
runningtotal = runningtotal + x # the variable, runningtotal, is referred to the accumulator
The process of breaking a problem into smaller subproblems.
Note: functions can call other functions
An important computer science problem solving technique.
E.g. Assume we want to write a function to draw a square. The generalization step is to realize that a
square is just a special kind of rectangle.
The Flow of Execution:
1 def pow(b, p): # (1)
2 y = b ** p
3 return y
5 def square(x):
6 a = pow(x, 2)
7 return a
9 n = 5
10 result = square(n) #(2)
11 print(result) #(3)
The order in which these lines of code are processed in Python:
1, 5, 9, 10, 6, 2, 3, 7, 11
Note: (1)Python must at least process the function headers before skipping over the functions
(2)Python will not execute the functions until after they are called
(3)Python must execute the function square before moving on to line 11
Type errors most often occur when an expression tries to combine two objects with
types that should not be combined.
„‟, or “”, is still considered to be a string. It is simply a sequence of zero
characters. Strings are Immutable
In Python you are not allowed to modify the individual characters in the
>>> greeting = „Hello, Cinny‟
>>> greeting = „O‟ # ERROR!
TpyeError: „str‟does not support item assignment
#You can achieve your goal in this way
>>> greeting = „Hello, Cinny‟
>>> new_greeting = „O‟+ greeting[1:]
Operations on Strings:
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. But
the „+‟and „*‟operators do work with strings.
joining the two operands by linking them end-to-end
Note: The space is part of the string and I necessary to produce the space between the concatenated
>>> „big‟+ „apples‟
>>> „big‟+ „ apples‟
>>> print(„big‟+ „ apples‟)
Repetition (*) :
one of the operands has to be a string and the other has to be an integer
Note: the repetition is done before the concatenation
>>> „Go‟* 3
>>> „You‟+ „ Go‟* 3
„You Go Go Go‟
to see if two strings are the same or to put words in lexicographical order
(similar to the alphabetical order in a dictionary, except that all the uppercase letters come before all the
lowercase letter.) >>> „Dog‟< „Doghouse‟
>>> „dog‟< „Dog‟
>>> „dog‟< „Doghouse‟
ord(char) and chr(int):
Each character in Python is assigned unique integer value so that Python can
compare them to find their order („A‟is 65, „B‟is 66, „5‟is 53).
You can find out the so called ordinal value for a given character using a
character function called ord(char).
And chr(int) can converts integers into their character equivalent.
Note: the space character has an ordinal value (32). Even though you don‟t see it, it‟s an actual
len(): returns the number of characters in a string.
index 0 1 2 3 4
H e l l o
index -5 -4 -3 -2 -1
The indexing operator, x[index], selects a single character from a string. The
characters are accessed by their position or index value.
Note: Indexing returns a string
x[index] The expression in brackets is called an index. An index specifies a member of
an ordered collection. It can be any integer expression so long as it evaluates to a valid
index value. Slice Operator:
A substring of a string is called a slice. string[n:m] returns the part of the string
from the n‟th character to the m‟th character, including the first but excluding the
last - [n,m).
in and not in operators:
Test if one string is a substring of another
Note: a string is a substring of itself; the empty string is a substring of any other string
Strings are also objects. Each string instance has its own attributes and methods.
upper(): a method that can be invoked on any string object to create a new string in