Python Notes
Python Notes
Arithmetic Operators
A type is a set of values and operations that can be performed on those values.
int:integer
For example: 3, 4, 894, 0, -3, -18
float: floating point number (an approximation to a real number)
For example: 5.6, 7.342, 53452.0, 0.0, -89.34, -9.5
When multiple operators are combined in a single expression, the operations are
evaluated in order of precedence.
Operator Precedence
** highest
- (negation)
*, /, //, %
+ (addition), - (subtraction) lowest
Errors
A syntax error occurs when we an instruction with invalid syntax is executed. For
example:
>>> 3) + 2 * 4
SyntaxError: invalid syntax
A semantic error occurs when an instruction with invalid semantics is executed. For
example:
>>> 89.4 / 0
Traceback (most recent call last):
File "", line 1, in
89.4 / 0
ZeroDivisionError: float division by zero
For the purpose of this course, you may think of computer memory as a long list of
storage locations where each location is identified with a unique number and each
location houses a value. This unique number is called a memory address. Typically,
we will write memory addresses as a number with an "id" as a prefix to distinguish
them from other numbers (for example, id201 is memory address 201).
Variables are a way to keep track of values stored in computer memory. A variable is
a named location in computer memory. Python keeps variables in a separate list from
values. A variable will contain a memory address, and that memory address contains
the value. The variable then refers to the value. Python will pick the memory
addresses for you.
Terminology
Variables
Assignment statements
Variable names
When we trace this in the visualizer and click button Forward twice, this is the result:
Notice that y's value did not change during this step.
Built-in Functions
Function Call
Terminology:
Function dir
Python has a set of built-in functions. To see the list of built-in functions,
run dir(__builtins__):
>>> dir(__builtins__)< br/> ['ArithmeticError', 'AssertionError',
'AttributeError', 'BaseException', 'BufferError', 'BytesWarning',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception',
'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',
'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning',
'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all',
'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr',
'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr',
'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter',
'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash',
'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range',
'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted',
'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Function help
To get information about a particular function, call help and pass the function as the
argument. For example:
>>> help(abs)
Help on built-in function abs in module builtins:
abs(...)
abs(number) -> number
Optional arguments
In the description of function pow below, the square brackets around [, z] indicate
that the third argument is optional:
>>> help(pow)
Help on built-in function pow in module builtins:
pow(...)
pow(x, y[, z]) -> number
Defining Functions
Function Definitions
def function_name(parameters):
body
return statement
Function Calls
Function calls are expressions and the result can be stored in a variable.
function_name(arguments)
We usually save our Python programs in ".py" files. A file can contain multiple
function definitions and other statements. Before calling a function from a ".py" file in
the shell in IDLE, you need to first execute Run -> Run Module, or else the shell will
not recognize the function call.
String Literal
A string literal is a sequence of characters. In Python, this type is called str. Strings
in Python start and end with a single quotes (') or double quotes ("). A string can be
made up of letters, numbers, and special characters. For example:
>>> 'hello'
'hello'
>>> 'how are you?'
'how are you?'
>>> 'short- and long-term'
'short- and long-term'
If a string begins with a single quote, it must end with a single quote. The same
applies to double-quoted strings. You can not mix the type of quotes.
Escape Sequences
To include a quote within a string, use an escape character (\) before it. Otherwise
Python interprets that quote as the end of a string and an error occurs. For example,
the following code results in an error because Python does not expect anything to
come after the second quote:
>>> storm_greeting = 'wow, you're dripping wet.'
SyntaxError: invalid syntax
The escape sequence \' indicates that the second quote is simply a quote, not the end
of the string:
>>> storm_greeting = 'Wow, you\'re dripping wet.'
"Wow, you're dripping wet."
The * and + operands obey by the standard precedence rules when used with strings.
Function print
Python has a built-in function named print that displays messages to the user. For
example, the following function call displays the string "hello":
>>> print("hello")
hello
In the output above, notice that hello is displayed without the quotation marks. The
quotes are only for Python's internal string formatting and are not seen by the user.
The print function may also be called with a mathematical expression for an
argument. Python evaluates the mathematical expression first and then displays the
resulting value to the user. For example:
>>> print(3 + 7 - 3)
7
Finally, print can take in more than one argument. Each pair of arguments is
separated by a comma and a space is inserted between them when they are displayed.
For example:
>>> print("hello", "there")
hello there
An example of return:
>>> def square_return(num):
return num ** 2
>>> answer_return = square_return(4)
>>> answer_return
16
When a print function call is executed, the argument(s) are evaluated to produce
memory address(es).
An example of print:
>>> def square_print(num):
print("The square of num is", num ** 2)
>>> answer_print = square_print(4)
The square num is 16
>>> answer_print
>>>
Function input
The function input is a built-in function that prompts the user to enter some input. The
program waits for the user to enter the input, before executing the subsequent
instructions. The value returned from this function is always a string. For example:
>>> input("What is your name? ")
What is your name? Jen
'Jen'
>>> name = input("What is your name? ")
What is your name? Jen
>>> name
'Jen'
>>> location = input("What is your location? ")
What is your location? Toronto
>>> location
'Toronto'
>>> print(name, "lives in", location)
Jen lives in Toronto
>>> num_coffee = input("How many cups of coffee? ")
How many cups of coffee? 2
>>> num_coffee
'2'
Operations on strings
Triple-quoted strings
We have used single- and double- quotes to represent strings. The third string format
uses triple-quotes and a triple-quoted string can span multiple lines. For example:
>>> print(''' How
are
you?''')
How
are
you?
Escape Sequences
Python has a special character called an escape character: \. When the escape
character is used in a string, the character following the escape character is treated
differently from normal. The escape character together with the character that follows
it is an escape sequence. The table below contains some of Python's commonly used
escape sequences.
Escape
Name Example Output
Sequence
\n newline (ASCII linefeed - print('''How How
are are
LF) you?''') you?
3 4
\t
tab (ASCII horizontal tab - print('3\t4\t5') 5
TAB)
print('\\') \
\\ backslash (\)
print('don\'t') don't
\' single quote (')
print("He He says,
\" double quote (") says, \"hi\".") "hi".
area(base, height)
(number, number) -> number
1. Examples
o What should your function do?
o Type a couple of example calls.
o Pick a name (often a verb or verb phrase): What is a short answer to
"What does your function do"?
2. Type Contract
o What are the parameter types?
o What type of value is returned?
3. Header
o Pick meaningful parameter names.
4. Description
o Mention every parameter in your description.
o Describe the return value.
5. Body
o Write the body of your function.
6. Test
o Run the examples.
The problem:
1. Examples
2. >>> convert_to_celsius(32)
3. 0
4. >>> convert_to_celsius(212)
5. 100
6.
7. Type Contract
8. (number) -> number
9.
10.Header
11. def convert_to_celsius(fahrenheit):
12.
13.Description
14. Return the number of Celsius degrees equivalent to fahrenheit
degrees.
15.
16.Body
17. return (fahrenheit - 32) * 5 / 9
18.
19.Test
20. Run the examples.
21.
Putting it all together:
def convert_to_celsius(fahrenheit):
''' (number) -> number
>>> convert_to_ccelsius(32)
0
>>> convert_to_celsius(212)
100
'''
Function Reuse
Calling functions within other function definitions
>>> perimeter(3, 4, 5)
12
>>> perimeter(10.5, 6, 9.3)
25.8
'''
return side1 + side2 + side3
>>> semiperimeter(3, 4, 5)
6.0
>>> semiperimeter(10.5, 6, 9.3)
12.9
'''
return perimeter(side1, side2, side3) / 2
The approach: Pass calls to function area as arguments to built-in function max.
max(area(3.8, 7.0), area(3.5, 6.8))
def convert_to_seconds(num_hours):
""" (int) -> int
Return the number of seconds there are in num_hours hours.
"""
minutes = convert_to_minutes(num_hours)
seconds = minutes * 60
return seconds
seconds = convert_to_seconds(2)
Python defines the first two functions, creates objects for them in the heap, and, in the
stack frame for the main program, creates variables that refer to those function
objects.
After that, it executes the assignment statement on line 16. The right-hand side of the
assignment statement is a function call so we evaluate the argument, 2, first. The
frame for convert_to_seconds will appear on the call stack. The parameter, num_hours,
will refer to the value 2.
We now see that there are two variables called num_hours in the call stack; one is
in convert_to_minutes and the other is in convert_to_seconds.
The next line of code Python executes is minutes = num_hours * 60. However, which
instance of num_hours will be used? Python always uses the variable in the current
stack frame. With an assignment statement, if the variable does not exist in the current
stack frame, Python creates it. So, once num_hours * 60 is evaluated,
variable minutes is created in the current stack frame.
The last line of the function is return minutes. Once this statement is complete,
Python will return to the frame just underneath the top of the call stack.
So, Python is going to produce the value 120, remove the current stack frame, create a
new variable called minutes in the stack frame for convert_to_seconds, and store the
memory adress of 120 in that variable.
Python then executes seconds = minutes * 60. Python evaluates the right-hand side,
which produces 7200, and stores the memory address of that value in variable seconds.
Since this variable does not exist yet, Python creates it in the current stack
frame.
Next is a return statement. Like we saw above, that is going to return control back to
the the main module.
Once the frame for convert_to_seconds is removed, the assignment statement on line
16 (which has been paused a long time!) is completed, and a new variable seconds is
created in the stack frame for the main program.
In addition to evaluating the expression and yielding its value, return also erases the
stack frame on top of the call stack.
The Python type bool has two values: True and False.
Comparison operators
The comparison operators take two values and produce a Boolean value.
equal to == 3 == 4 False
Logical operators
There are also three logical operators that produce Boolean values: and, or, and not.
and and (80 >= 50) and (70 <= 50) False
The and operator produces True if and only if both expressions are True.
As such, if the first operand is False, the second condition will not even be checked,
because it is already known that the expression will produce False.
The or operator evaluates to True if and only if at least one operand is True.
As such, if the first operand is True, the second condition will not even be checked,
because it is already known that the expression will produce True.
The not operator evaluates to True if and only if the operand is False.
Double-negation can be simplified. For example, the expression not not (4 == 5) can
be simplified to 4 == 5.
The order of precedence for logical operators is: not, and, then or. We can override
precedence using parentheses and parentheses can also be added to make things easier
to read and understand.
For example, the not operator is applied before the or operator in the following code:
>>> grade = 80
>>> grade2 = 90
>>> not grade >= 50 or grade2 >= 50
True
Parentheses can be added to make this clearer: (not grade >= 50) or (grade2 >= 50)
Builtin function str takes any value and returns a string representation of that value.
>>> str(3)
'3'
>>> str(47.6)
'47.6'
int
Builtin function int takes a string containing only digits (possibly with a leading
minus sign -) and returns the int that represents. Function int also
converts float values to integers by throwing away the fractional part.
>>> int('12345')
12345
>>> int('-998')
-998
>>> int(-99.9)
-99
If function int is called with a string that contains anything other than digits,
a ValueError happens.
>>> int('-99.9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-99.9'
float
Builtin function float takes a string containing only digits and zero or one decimal
points (possibly with a leading minus sign -) and returns the float that represents.
Function float also converts int values to floats.
>>> float('-43.2')
-43.2
>>> float('432')
432.0
>>> float(4)
4.0
If function float is called with a string that can't be converted, a ValueError happens.
>>> float('-9.9.9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '-9.9.9'
Python contains many functions, but not all of them are immediately available as
builtin functions. Instead of being available as builtins, some functions are saved in
different modules. A module is a file containing function definitions and other
statements.
We may also define our own modules with our own functions.
import
In order to gain access to the functions in a module, we must import that module.
For example, we can import the Python module math and call the function sqrt from
it:
import math
In addition to importing Python's modules, we can also import the modules that we
write. For example, to use the functions from triangle.py (from the video) in another
module, we would import triangle. A module being imported should be in the same
directory as the module importing it.
The if statement
If statements can be used to control which instructions are executed. Here is the
general form:
if expression1:
body1
[elif expression2: 0 or more clauses
body2]
[else: 0 or 1 clause
bodyN]
A note on None
When execution of a function body ends without having executed a return statement,
the function returns value None. The type of None is NoneType.
Pre-condition: 0.0 <= scheduled_time < 24.0 and 0.0 <= estimated_time <
24.0
if scheduled_time == estimated_time:
return 'on time'
In the shell:
Because the type of None is NoneType, not str, this breaks the Type Contract. To fix
this, we would need to complete the rest of the function.
No if Required
It is common for new programmers to write code like the following:
def is_even(num):
""" (int) -> bool
Return whether num is even.
"""
if num % 2 == 0:
return True
else:
return False
This works, but is stylistically questionable. It's also more typing and reading than is
necessary!
num % 2 == 0 already produces True or False, so that expression can be used with
the return statement:
def is_even(num):
""" (int) -> bool
Return whether num is even.
"""
return num % 2 == 0
Structuring if Statements
if-elif vs. if-if
The if statement condition (grade1 >= 50) evaluates to True, so the body associated
with the if is executed and then the if exits. The elif condition is not even evaluated
in this case.
It is possible for if statements to appear one after another in a program. Although they
are be adjacent to each other, they are completely independent of each other and it is
possible for the body of each if to be executed. For example:
grade1 = 70
grade2 = 80
In the program above, the condition associated with the first if statement (grade1 >=
50) produces True, so the body associated with it is executed. The condition associated
with the second if statement (grade2 >= 50) also produces True, so the body
associated with it is also executed.
Nested ifs
The statement above can be simplified by removing some of the nesting. The
message 'Bring your umbrella!' is printed only when both of the if statement
conditions are True. The message 'Wear your snow boots and winter coat!' is
printed only when the outer if condition is True, but the inner if condition is False.
The following is equivalent to the code above:
if precipitation and temperature > 0:
print('Bring your umbrella')
elif precipitation:
print('Wear your snow boots and winter coat!')