Python Tutorial
Python Installation and Distributions
Python Anaconda Distribution
Anaconda is a distribution of the Python and R programming languages for scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, etc.), that aims to simplify package management and deployment. The distribution includes data-science packages suitable for Windows, Linux, and macOS. It is developed and maintained by Anaconda, Inc., which was founded by Peter Wang and Travis Oliphant in 2012.
Python Anaconda Distribution uses conda
for package managing.
Anaconda Package Management: conda
conda
is Anaconda package management service that included in Anaconda environment.
We will discuss conda
later in Python PIP Chapter.
Python Official Distribution
Python Official Distribution is managed and released by Python.org. Typically, you can always find the latest version of Python on python.org. Latest version usually meaning more powerful but lack of stable and third-party packages and environment supported. Therefore, the stable one is the best. Update Python carefully.
Python Package Management: pip
pip
is Python package management service that included in Python environment.
We will discuss pip
later in Python PIP Chapter.
Python Environment Introduction
After you installed Python, you need to know how to run it.
Python has two basic modes: script and interactive. The normal mode is the mode where the scripted and finished .py
files are run in the Python interpreter. Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole.
- Python Script: Run in CLI Terminal
- Launch Python Interactive Session
- Run Python file
.py
, which saved complete Python code with noError
.
- Python Interactive Session: Run in Python IDLE, or third-party code editor like Visual Studio Code (VSCode)
- Run Python code, which could be one or more Python statements
CLI Terminal
In computing, a shell is a computer program which exposes an operating system’s services to a human user or other program. In general, operating system shells use either a command-line interface (CLI) or graphical user interface (GUI), depending on a computer’s role and particular operation. It is named a shell because it is the outermost layer around the operating system.
Command-line shells require the user to be familiar with commands and their calling syntax, and to understand concepts about the shell-specific scripting language (for example, bash).
Graphical shells place a low burden on beginning computer users, and are characterized as being easy to use. Since they also come with certain disadvantages, most GUI-enabled operating systems also provide CLI shells.
For MacOS user, open Other folder to launch Terminal. This manipulate is on Graphical shells.
Once you open Terminal, you can see a shell session. Now you have a Command-line shells.
Use CLI Terminal to Launch a Python Interactive Session
Type in python3
to launch Python Interactive Session
1 | python3 |
Use CLI Terminal to Run a Python File
Type in python3 [script.py]
to run a Python script named script.py
1 | python3 script.py |
Python Interactive Session
The symbols >>>
are called doctests. Doctests explain what the function does by showing actual Python code. The lines underneath the >>> show the expected output from running the above Python code.
You can run any Python code on Python Interactive Session.
1 | 'Hello Amber') print( |
doctest module
After you import A Layered Design Process, you can run code with >>>
in VSCode or Jupyter.
1 | import doctest |
1 | # This is a little piece of magic to help you test functions against |
Python File
When you open a Python file, you can see some Python comments and code.
- Comments are surrounded by docstring
#
: one line comment''' '''
or""" """
: multiple line comments
- Code is the main part of a Python script, so other than comments parts are code.
1 | # This is one line comment |
CLI & Python Interactive Session Shortcuts
Remember the following important and useful CLI Terminal Shortcuts could effectively save your time.
Other Keyboard
↑/↓
: Scroll through History of typed commandsTab
: Autocomplete command/file nameTab
more times: Show more potential matched files or command
Control
Ctrl-L
: Clear screenCtrl-C
: Abort current command/typingCtrl-Z
: Pause execution of the current jobCtrl-A
: Move to beginning of lineCtrl-E
: Move to end of lineCtrl-U
: Erase line to the leftCtrl-K
: Erase line to the rightCtrl-W
: Erase word to the leftCtrl-Y
: Yank/paste previously erased stringCtrl-R
: Reverse search of history
Command
Cmd-Z
: Undo the last operationCmd-R
: Redo the last operationCmd-X
: Cut the selection and store it in the clipboardCmd-C
: Copy the selection into the clipboardCmd-V
: Paste contents of clipboard at cursorCmd-+
: Zoom inCmd--
: Zoom outCmd-0
: Zoom 100%
Python Tutor
Python tutor is a website that allows you to write python code in your web browser and see it visualized step by step. Before we explain more, let’s experiment with it a little. First, head to the python tutor website
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
- Text Type:
str
- Numeric Types:
int
,float
,complex
- Sequence Types:
list
,tuple
,range
- Mapping Type:
dict
- Set Types:
set
,frozenset
- Boolean Type:
bool
- Binary Types:
bytes
,bytearray
,memoryview
Getting Data Type & Type Conversion
Getting Data Type
1 | type(<data>) |
Type Conversion
You can convert from one type to another with the int()
, float()
, and complex()
methods:
Note: You cannot convert complex numbers into another number type.
Python Numbers: int, float, complex
There are three numeric types in Python:
- int
- float
- complex
int
int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
1 | x = 1 |
float
Float, or “floating point number” is a number, positive or negative, containing one or more decimals.
1 | x = 1.0 |
complex (Optional)
Complex numbers are written with a j
as the imaginary part.
1 | x = 3+5j |
Python Strings: str
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
'hello'
is the same as "hello"
.
You can display a string literal with the print()
function.
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string.
Multiline Strings
You can assign a multiline string to a variable by using three quotes.
1 | ccp = """ The most crazy terrorist organization, |
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
1 | "Hello World!"[0] |
String Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
1 | "Hello World!"[0:5] |
Negative Indexing
Use negative indexes to start the slice from the end of the string
1 | "Hello World!"[-3:-1] # Notice : means [x, y) |
String Length
To get the length of a string, use the len()
function.
1 | len("Fxxk CCP") |
Check String
To check if a certain phrase or character is present in a string, we can use the keywords in
or not in
.
1 | '!' in "Hello World!" |
String Concatenation
To concatenate, or combine, two strings you can use the +
operator.
1 | print("Fxxk" + " CCP") |
String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
1 | age = 36 |
But we can combine strings and numbers by using the format()
method!
The format()
method takes the passed arguments, formats them, and places them in the string where the placeholders {}
are:
1 | age = 36 |
The format()
method takes unlimited number of arguments, and are placed into the respective placeholders.
1 | itemno = 567 |
You can use index numbers {0}
to be sure the arguments are placed in the correct placeholders. The number in {}
is index.
1 | quantity = 3 |
To make sure a string will display as expected, we can format the result with the format()
method.
String format()
The format()
method allows you to format selected parts of a string.
Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?
To control such values, add placeholders (curly brackets {}
) in the text, and run the values through the format()
method:
Add a placeholder where you want to display the price:
1 | age = 25 |
You can add parameters inside the curly brackets to specify how to convert the value:
Format the price to be displayed as a number with two decimals:
1 | age = 25 |
Check out all formatting types in W3School String format() Reference.
Multiple Values
If you want to use more values, just add more values to the format() method:
1 | name = "Zacks" |
Index Numbers
You can use index numbers (a number inside the curly brackets {0}
) to be sure the values are placed in the correct placeholders:
1 | name = "Zacks" |
Also, if you want to refer to the same value more than once, use the index number:
1 | name = "Zacks" |
Named Indexes
You can also use named indexes by entering a name inside the curly brackets {name}
, but then you must use names when you pass the parameter values like the following:
1 | Introduction = "I am {name}. {name} is {age:.2f} year's old, and live in {country}." |
1 | name = "Zacks" |
f-string
[Python String Formatting Best Practices]https://realpython.com/python-string-formatting/
Python 3.6 added a new string formatting approach called formatted string literals or “f-strings”. This new way of formatting strings lets you use embedded Python expressions inside string constants. Here’s a simple example to give you a feel for the feature:
1 | 'Zacks' name = |
=
specifier
Starting from Python 3.8, f-strings support =
specifier.
1 | name = 'Zacks' |
1 | name = Zacks, role = Senior Data Engineer |
inspect.cleandoc
inspect
— Inspect live objects
inspect.cleandoc(doc)
Clean up indentation from docstrings that are indented to line up with blocks of code.
All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.
1 | def func(): |
1 |
|
1 | from inspect import cleandoc |
1 | Hello, my name is Zacks. |
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \
followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes
1 | txt = "We are the so-called "Vikings" from the north." # Notice you cannot put extra " in a pair of ". |
Code | Result |
---|---|
\' |
Single Quote |
\\ |
Backslash |
\n |
New Line |
\r |
Carriage Return |
\t |
Tab |
\b |
Backspace |
\f |
Form Feed |
\ooo |
Octal value |
\xhh |
Hex value |
Builtin-Methods
Method name | Description |
---|---|
strip() |
The strip() method removes any whitespace from the beginning or the end |
lower |
The lower() method returns the string in lower case |
upper |
The upper() method returns the string in upper case |
replace() |
The replace() method replaces a string with another string: |
spilt |
The split() method splits the string into substrings if it finds instances of the separator |
1 | " Hello World! ".strip() |
String Methods
Here are other built-in method of string.
Note: All string methods returns new values. They do not change the original string.
Method | Description |
---|---|
capitalize() |
Converts the first character to upper case |
casefold() |
Converts string into lower case |
center() |
Returns a centered string |
count() |
Returns the number of times a specified value occurs in a string |
encode() |
Returns an encoded version of the string |
endswith() |
Returns true if the string ends with the specified value |
expandtabs() |
Sets the tab size of the string |
find() |
Searches the string for a specified value and returns the position of where it was found |
format() |
Formats specified values in a string |
format_map() |
Formats specified values in a string |
index() |
Searches the string for a specified value and returns the position of where it was found |
isalnum() |
Returns True if all characters in the string are alphanumeric |
isalpha() |
Returns True if all characters in the string are in the alphabet |
isdecimal() |
Returns True if all characters in the string are decimals |
isdigit() |
Returns True if all characters in the string are digits |
isidentifier() |
Returns True if the string is an identifier |
islower() |
Returns True if all characters in the string are lower case |
isnumeric() |
Returns True if all characters in the string are numeric |
isprintable() |
Returns True if all characters in the string are printable |
isspace() |
Returns True if all characters in the string are whitespaces |
istitle() |
Returns True if the string follows the rules of a title |
isupper() |
Returns True if all characters in the string are upper case |
join() |
Joins the elements of an iterable to the end of the string |
ljust() |
Returns a left justified version of the string |
lower() |
Converts a string into lower case |
lstrip() |
Returns a left trim version of the string |
maketrans() |
Returns a translation table to be used in translations |
partition() |
Returns a tuple where the string is parted into three parts |
replace() |
Returns a string where a specified value is replaced with a specified value |
rfind() |
Searches the string for a specified value and returns the last position of where it was found |
rindex() |
Searches the string for a specified value and returns the last position of where it was found |
rjust() |
Returns a right justified version of the string |
rpartition() |
Returns a tuple where the string is parted into three parts |
rsplit() |
Splits the string at the specified separator, and returns a list |
rstrip() |
Returns a right trim version of the string |
split() |
Splits the string at the specified separator, and returns a list |
splitlines() |
Splits the string at line breaks and returns a list |
startswith() |
Returns true if the string starts with the specified value |
strip() |
Returns a trimmed version of the string |
swapcase() |
Swaps cases, lower case becomes upper case and vice versa |
title() |
Converts the first character of each word to upper case |
translate() |
Returns a translated string |
upper() |
Converts a string into upper case |
zfill() |
Fills the string with a specified number of 0 values at the beginning |
Python Booleans
Booleans represent one of two values: True
or False
.
Boolean Values
In programming you often need to know if an expression is True
or False
.
You can evaluate any expression in Python, and get one of two answers, True
or False
.
When you compare two values, the expression is evaluated and Python returns the Boolean answer.
Evaluate Values and Variables
The bool()
function allows you to evaluate any value, and give you True
or False
in return,
Most Values are True
Almost any value is evaluated to True
if it has some sort of content.
Any string is True
, except empty strings.
Any number is True
, except 0.
Any list, tuple, set, and dictionary are True
, except empty ones.
Some Values are False
In fact, there are not many values that evaluates to False
, except empty values, such as ()
, []
, {}
, ""
, the number 0
, and the value None
. And of course the value False
evaluates to False
.
Functions can Return a Boolean
Python also has many built-in functions that returns a boolean value, like the isinstance()
function, which can be used to determine if an object is of a certain data type.
1 | x = 200 |
Short Circuiting
https://cs88-website.github.io/sp21/lab/lab01/#boolean-operators
What do you think will happen if we type the following into Python?
1 | 1 / 0 |
Try it out in Python! You should see a ZeroDivisionError
. But what about this expression?
1 | True or 1 / 0 |
It evaluates to True
because Python’s and
and or
operators short-circuit. That is, they don’t necessarily evaluate every operand.
And what about this expression?
1 | 1 / 0 or True |
Try it out in Python! You should see a ZeroDivisionError
.
And what is short-circuit? In my opinion, from left to right of the expression, which part satisfies True
or False
will return the result immediately and ignore the rest parts.
Operator | Evaluates from left to right until: | Example |
---|---|---|
AND |
The first “false-y” value | False and 1 / 0 evaluates to False |
OR |
The first “truth-y” value | True or 1 / 0 evaluates to True |
If and
and or
do not short-circuit, they just return the last value. This means that and
and or
don’t always return booleans when using truth-y and false-y values.
For example:
1 | True and 88 |
Here’s another little example:
1 | def divides(x, y): |
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations.
Operator | Name |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus |
** |
Exponentiation |
// |
Floor division |
Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator | Example | Same As |
---|---|---|
= |
x = 5 | x = 5 |
+= |
x += 3 | x = x + 3 |
-= |
x -= 3 | x = x - 3 |
*= |
x *= 3 | x = x * 3 |
/= |
x /= 3 | x = x / 3 |
%= |
x %= 3 | x = x % 3 |
//= |
x //= 3 | x = x // 3 |
**= |
x **= 3 | x = x ** 3 |
&= |
x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= |
x ^= 3 | x = x ^ 3 |
>>= |
x >>= 3 | x = x >> 3 |
<<= |
x <<= 3 | x = x << 3 |
Python Comparison Operators
Comparison operators are used to compare two values.
Operator | Name |
---|---|
== |
Equal |
!= |
Not equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Python Logical Operators
Logical operators are used to combine conditional statements.
Operator | Description | Example |
---|---|---|
and |
Returns True if both statements are true | x < 5 and x < 10 |
or |
Returns True if one of the statements is true | x < 5 or x < 4 |
not |
Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
Operator | Description | Example |
---|---|---|
is |
Returns true if both variables are the same object | x is y |
is not |
Returns true if both variables are not the same object | x is not y |
1 | a = [1, 2, 3] |
Here, although a
and c
have the same elements, they point to two different objects.
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object.
Operator | Description | Example |
---|---|---|
in |
Returns True if a sequence with the specified value is present in the object | x in y |
not in |
Returns True if a sequence with the specified value is not present in the object | x not in y |
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers.
Operator | Name | Description |
---|---|---|
& |
AND | Sets each bit to 1 if both bits are 1 |
^ |
XOR | Sets each bit to 1 if only one of two bits is 1 |
~ |
NOT | Inverts all the bits |
<< |
Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
>> |
Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
| |
OR | Sets each bit to 1 if one of two bits is 1 |
Python Collections
There are four collection data types in the Python programming language:
List
is a sequence which is ordered and changeable. Allows duplicate members.Tuple
is a sequence which is ordered and unchangeable. Allows duplicate members.Set
is a collection which is unordered and unindexed. No duplicate members.Dictionary
is a collection which is unordered, changeable and indexed. No duplicate members.
Ordered | Unordered | |
---|---|---|
changeable | List | Dictionary |
unchangeable | Tuple |
List
A list
is a collection which is ordered and changeable. In Python lists are written with square brackets.
Create a list
1 | l = [0, 1, 2, "list"] |
Access Items
The values in a list could be accessed by indexes
. The first value is at index 0; the last value is at index -1; “-“ means accessed the countdown value; “:” means the range of indexes.
1 | l = [0, 1, 2, "list"] |
1 | # List unpacking |
List Slicing
List slicing must start from left to right factors.
1 | l = [0, 1, 2, "list"] |
Change Item Value
1 | l = [0, 1, 2, "list"] |
You can change plural values in list, even exceed the length of the list.
1 | l = [0, 1, 2, 3] |
But you cannot using this method to directly add item.
1 | l = [0, 1, 2, 3] |
Check if Item Exists
To determine if a specified item is present in a list use the in
keyword.
1 | l = [0, 1, 2, "list"] |
List Length
len()
is function designed for getting the length of a list.
1 | l = [0, 1, 2, "list"] |
Add Items
append()
is the function designed for adding one value at the last of the list.
Add item through +
.
1 | l = [0, 1, 2, 3] |
Add item through append()
1 | l = [0, 1, 2, "list"] |
Add item from a list.
1 | l = [0, 1, 2, "list"] |
To add an item at the specified index, use the insert()
method.
1 | l = [0, 1, 2, "list"] |
Remove Item
The pop()
method removes the specified index, (or the last item if index is not specified).
1 | l = [0, 1, 2, "list"] |
The remove()
method removes the specified item.
1 | l = [0, 1, 2, "list"] |
The del
keyword removes the specified index.
1 | l = [0, 1, 2, "list"] |
The clear()
method empties the list.
1 | l = [0, 1, 2, "list"] |
Copy a List
You CANNOT copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy()
.
Copy the list and build a reference with it.
1 | # Create list areas |
Only copy the values of the list.
1 | # Create list areas |
Only copy the values of the list.
1 | # Create list areas |
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the +
operator.
1 | l1 = [0, 1, 2] |
You can use the extend()
method, which purpose is to add elements from one list to another list.
1 | l = [0, 1, 2, "list"] |
The list() Constructor
It is also possible to use the list()
constructor to make a new list.
1 | l = list(("apple", "banana", "cherry")) # note the double round-brackets |
Built-in functions
Function name | Description |
---|---|
len() | return the length of the list |
max() | return the maximum value of the list |
min() | return the minimum value of the list |
list() | change a tuple to list |
Built-in methods
Method name | Description |
---|---|
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |
List Comprehensions
The general syntax for a list comprehension is
1 | [<expression> for <element> in <sequence> if <conditional>] |
The syntax is designed to read like English: “Compute the expression for each element in the sequence if the conditional is true.”
1 | a = [8, 4, 16, 20] |
1 | # Python code to convert list of tuples into list |
1 | [i**2 for i in [1, 2, 3, 4] if i%2 == 0] |
is equivalent to
1 | l = [] |
List Comprehensions with If statements
No else
:
1 | [i for i in range(5) if i%2 == 0] |
Need else
:
1 | [i if i%2 == 0 else None for i in range(5)] |
Tuple
A tuple
is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
- The parentheses are optional when defining tuples, and programmers frequently omit them if parentheses don’t clarify the code.
Create a tuple
1 | l = [0, 1, 2] |
1 | t = (0) |
Access Tuple Items
1 | t = (0, 1, 2, "tuple") |
1 | # Tuple unpacking |
Check if Item Exists
1 | t = 0, 1, 2, "tuple" |
Tuple Length
1 | t = 0, 1, 2, "tuple" |
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely.
1 | t = (0, 1, 2) |
Join Two Tuples
To join two or more tuples you can use the +
operator:
1 | t1 = (0, 1, 2) |
Define a changeable tuple
The factors in a tuple is unchangeable but the value in the factor is changeable.
1 | l = [4, 5] |
The tuple() Constructor
It is also possible to use the tuple()
constructor to make a tuple.
1 | t = tuple(("apple", "banana", "cherry")) # note the double round-brackets |
Built-in functions
Function name | Description |
---|---|
len() | return the length of the tuple |
max() | return the maximum value of the tuple |
min() | return the minimum value of the tuple |
tuple() | change a list to tuple |
Built-in methods
Function name | Description |
---|---|
count() | Returns the number of times a specified value occurs in a tuple |
index() | Searches the tuple for a specified value and returns the position of where it was found |
Set
A set
is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
- A set is a data type for mutable unordered collections of unique elements. One application of a set is to quickly remove duplicates from a list.
Create a set
1 | s = {0, 1, 2} |
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
Change Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add()
method.
To add more than one item to a set use the update()
method.
1 | s = {0, 1, 2} |
Remove Item
To remove an item in a set, use the remove()
, or the discard()
method.
remove()
will raise an error if the item is not exist.discard()
will NOT raise an error if the item is not exist.
Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union()
method that returns a new set containing all items from both sets, or the update()
method that inserts all the items from one set into another:
1 | s1 = {0, 1, 2} |
Set Difference
Return the difference of two or more sets as a new set.
1 | s1 = {0, 1, 2} |
Set symmetric_difference
Return the symmetric difference of two sets as a new set.
1 | s1 = {0, 1, 2} |
Set symmetric_difference_update
Update a set with the symmetric difference of itself and another.
1 | s1 = {0, 1, 2} |
Set Intersection
Return the intersection of two sets as a new set.
1 | s1 = {0, 1, 2} |
Set Intersection update
Update a set with the intersection of itself and another.
1 | s1 = {0, 1, 2} |
Check is subset
Report whether another set contains this set.
1 | s1 = {0, 1, 2} |
Check is superset
Report whether this set contains another set.
1 | s1 = {0, 1, 2} |
Check is no intersection
1 | s1 = {0, 1, 2} |
The set() Constructor
It is also possible to use the set()
constructor to make a set.
1 | s = set(("apple", "banana", "cherry")) # note the double round-brackets |
Built-in method
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all the elements from the set |
copy() | Returns a copy of the set |
difference() | Returns a set containing the difference between two or more sets |
difference_update() | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item |
intersection() | Returns a set, that is the intersection of two other sets |
intersection_update() | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
pop() | Removes an element from the set |
remove() | Removes the specified element |
symmetric_difference() | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | inserts the symmetric differences from this set and another |
union() | Return a set containing the union of sets |
update() | Update the set with the union of this set and others |
Dictionary
A dictionary
is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
- keys:
int
,float
, orstr
Create a dictionary
1 | d = { |
1 | d = { |
Access Items
You can access the items of a dictionary by referring to its key name
, inside square brackets.
1 | d = { |
There is also a method called get()
that will give you the same result:
1 | d = { |
However, get()
returns None
while []
raises KeyError
:
1 | d = { |
You can use keys()
to print all of the keys of the dictionary.
1 | d = { |
Advanced get()
Example: Count the book title
1 | book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gatsby','hamlet','adventures','of','huckleberry','fin'] |
1 | book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gatsby','hamlet','adventures','of','huckleberry','fin'] |
Example: Count the fruit
You would like to count the number of fruits in your basket. In order to do this, you have the following dictionary and list of fruits. Use the dictionary and list to count the total number of fruits, but you do not want to count the other items in your basket.
1 | # You would like to count the number of fruits in your basket. |
Count all items
1 | # You would like to count the number of fruits in your basket. |
Example: Oscar
The following questions are based on data on Oscar Award Nominations for Best Director between the years 1931 to 2010. To start you off, we’ve provided a dictionary called “nominated” with the year (as key) and list of directors who were nominated in that year (as value). We’ve provided you with a different dictionary called “winners” with the year (as key) and list of directors who won the award in that year (as value).
Question 1
A. Create a dictionary that includes the count of Oscar nominations for each director in the nominations list.
B. Provide a dictionary with the count of Oscar wins for each director in the winners list.
1 | nominated = {1931: ['Norman Taurog', 'Wesley Ruggles', 'Clarence Brown', 'Lewis Milestone', 'Josef Von Sternberg'], 1932: ['Frank Borzage', 'King Vidor', 'Josef Von Sternberg'], 1933: ['Frank Lloyd', 'Frank Capra', 'George Cukor'], 1934: ['Frank Capra', 'Victor Schertzinger', 'W. S. Van Dyke'], 1935: ['John Ford', 'Michael Curtiz', 'Henry Hathaway', 'Frank Lloyd'], 1936: ['Frank Capra', 'William Wyler', 'Robert Z. Leonard', 'Gregory La Cava', 'W. S. Van Dyke'], 1937: ['Leo McCarey', 'Sidney Franklin', 'William Dieterle', 'Gregory La Cava', 'William Wellman'], 1938: ['Frank Capra', 'Michael Curtiz', 'Norman Taurog', 'King Vidor', 'Michael Curtiz'], 1939: ['Sam Wood', 'Frank Capra', 'John Ford', 'William Wyler', 'Victor Fleming'], 1940: ['John Ford', 'Sam Wood', 'William Wyler', 'George Cukor', 'Alfred Hitchcock'], 1941: ['John Ford', 'Orson Welles', 'Alexander Hall', 'William Wyler', 'Howard Hawks'], 1942: ['Sam Wood', 'Mervyn LeRoy', 'John Farrow', 'Michael Curtiz', 'William Wyler'], 1943: ['Michael Curtiz', 'Ernst Lubitsch', 'Clarence Brown', 'George Stevens', 'Henry King'], 1944: ['Leo McCarey', 'Billy Wilder', 'Otto Preminger', 'Alfred Hitchcock', 'Henry King'], 1945: ['Billy Wilder', 'Leo McCarey', 'Clarence Brown', 'Jean Renoir', 'Alfred Hitchcock'], 1946: ['David Lean', 'Frank Capra', 'Robert Siodmak', 'Clarence Brown', 'William Wyler'], 1947: ['Elia Kazan', 'Henry Koster', 'Edward Dmytryk', 'George Cukor', 'David Lean'], 1948: ['John Huston', 'Laurence Olivier', 'Jean Negulesco', 'Fred Zinnemann', 'Anatole Litvak'], 1949: ['Joseph L. Mankiewicz', 'Robert Rossen', 'William A. Wellman', 'Carol Reed', 'William Wyler'], 1950: ['Joseph L. Mankiewicz', 'John Huston', 'George Cukor', 'Billy Wilder', 'Carol Reed'], 1951: ['George Stevens', 'John Huston', 'Vincente Minnelli', 'William Wyler', 'Elia Kazan'], 1952: ['John Ford', 'Joseph L. Mankiewicz', 'Cecil B. DeMille', 'Fred Zinnemann', 'John Huston'], 1953: ['Fred Zinnemann', 'Charles Walters', 'William Wyler', 'George Stevens', 'Billy Wilder'], 1954: ['Elia Kazan', 'George Seaton', 'William Wellman', 'Alfred Hitchcock', 'Billy Wilder'], 1955: ['Delbert Mann', 'John Sturges', 'Elia Kazan', 'Joshua Logan', 'David Lean'], 1956: ['George Stevens', 'Michael Anderson', 'William Wyler', 'Walter Lang', 'King Vidor'], 1957: ['David Lean', 'Mark Robson', 'Joshua Logan', 'Sidney Lumet', 'Billy Wilder'], 1958: ['Richard Brooks', 'Stanley Kramer', 'Robert Wise', 'Mark Robson', 'Vincente Minnelli'], 1959: ['George Stevens', 'Fred Zinnemann', 'Jack Clayton', 'Billy Wilder', 'William Wyler'], 1960: ['Billy Wilder', 'Jules Dassin', 'Alfred Hitchcock', 'Jack Cardiff', 'Fred Zinnemann'], 1961: ['J. Lee Thompson', 'Robert Rossen', 'Stanley Kramer', 'Federico Fellini', 'Robert Wise', 'Jerome Robbins'], 1962: ['David Lean', 'Frank Perry', 'Pietro Germi', 'Arthur Penn', 'Robert Mulligan'], 1963: ['Elia Kazan', 'Otto Preminger', 'Federico Fellini', 'Martin Ritt', 'Tony Richardson'], 1964: ['George Cukor', 'Peter Glenville', 'Stanley Kubrick', 'Robert Stevenson', 'Michael Cacoyannis'], 1965: ['William Wyler', 'John Schlesinger', 'David Lean', 'Hiroshi Teshigahara', 'Robert Wise'], 1966: ['Fred Zinnemann', 'Michelangelo Antonioni', 'Claude Lelouch', 'Richard Brooks', 'Mike Nichols'], 1967: ['Arthur Penn', 'Stanley Kramer', 'Richard Brooks', 'Norman Jewison', 'Mike Nichols'], 1968: ['Carol Reed', 'Gillo Pontecorvo', 'Anthony Harvey', 'Franco Zeffirelli', 'Stanley Kubrick'], 1969: ['John Schlesinger', 'Arthur Penn', 'George Roy Hill', 'Sydney Pollack', 'Costa-Gavras'], 1970: ['Franklin J. Schaffner', 'Federico Fellini', 'Arthur Hiller', 'Robert Altman', 'Ken Russell'], 1971: ['Stanley Kubrick', 'Norman Jewison', 'Peter Bogdanovich', 'John Schlesinger', 'William Friedkin'], 1972: ['Bob Fosse', 'John Boorman', 'Jan Troell', 'Francis Ford Coppola', 'Joseph L. Mankiewicz'], 1973: ['George Roy Hill', 'George Lucas', 'Ingmar Bergman', 'William Friedkin', 'Bernardo Bertolucci'], 1974: ['Francis Ford Coppola', 'Roman Polanski', 'Francois Truffaut', 'Bob Fosse', 'John Cassavetes'], 1975: ['Federico Fellini', 'Stanley Kubrick', 'Sidney Lumet', 'Robert Altman', 'Milos Forman'], 1976: ['Alan J. Pakula', 'Ingmar Bergman', 'Sidney Lumet', 'Lina Wertmuller', 'John G. Avildsen'], 1977: ['Steven Spielberg', 'Fred Zinnemann', 'George Lucas', 'Herbert Ross', 'Woody Allen'], 1978: ['Hal Ashby', 'Warren Beatty', 'Buck Henry', 'Woody Allen', 'Alan Parker', 'Michael Cimino'], 1979: ['Bob Fosse', 'Francis Coppola', 'Peter Yates', 'Edouard Molinaro', 'Robert Benton'], 1980: ['David Lynch', 'Martin Scorsese', 'Richard Rush', 'Roman Polanski', 'Robert Redford'], 1981: ['Louis Malle', 'Hugh Hudson', 'Mark Rydell', 'Steven Spielberg', 'Warren Beatty'], 1982: ['Wolfgang Petersen', 'Steven Spielberg', 'Sydney Pollack', 'Sidney Lumet', 'Richard Attenborough'], 1983: ['Peter Yates', 'Ingmar Bergman', 'Mike Nichols', 'Bruce Beresford', 'James L. Brooks'], 1984: ['Woody Allen', 'Roland Joffe', 'David Lean', 'Robert Benton', 'Milos Forman'], 1985: ['Hector Babenco', 'John Huston', 'Akira Kurosawa', 'Peter Weir', 'Sydney Pollack'], 1986: ['David Lynch', 'Woody Allen', 'Roland Joffe', 'James Ivory', 'Oliver Stone'], 1987: ['Bernardo Bertolucci', 'Adrian Lyne', 'John Boorman', 'Norman Jewison', 'Lasse Hallstrom'], 1988: ['Barry Levinson', 'Charles Crichton', 'Martin Scorsese', 'Alan Parker', 'Mike Nichols'], 1989: ['Woody Allen', 'Peter Weir', 'Kenneth Branagh', 'Jim Sheridan', 'Oliver Stone'], 1990: ['Francis Ford Coppola', 'Martin Scorsese', 'Stephen Frears', 'Barbet Schroeder', 'Kevin Costner'], 1991: ['John Singleton', 'Barry Levinson', 'Oliver Stone', 'Ridley Scott', 'Jonathan Demme'], 1992: ['Clint Eastwood', 'Neil Jordan', 'James Ivory', 'Robert Altman', 'Martin Brest'], 1993: ['Jim Sheridan', 'Jane Campion', 'James Ivory', 'Robert Altman', 'Steven Spielberg'], 1994: ['Woody Allen', 'Quentin Tarantino', 'Robert Redford', 'Krzysztof Kieslowski', 'Robert Zemeckis'], 1995: ['Chris Noonan', 'Tim Robbins', 'Mike Figgis', 'Michael Radford', 'Mel Gibson'], 1996: ['Anthony Minghella', 'Joel Coen', 'Milos Forman', 'Mike Leigh', 'Scott Hicks'], 1997: ['Peter Cattaneo', 'Gus Van Sant', 'Curtis Hanson', 'Atom Egoyan', 'James Cameron'], 1998: ['Roberto Benigni', 'John Madden', 'Terrence Malick', 'Peter Weir', 'Steven Spielberg'], 1999: ['Spike Jonze', 'Lasse Hallstrom', 'Michael Mann', 'M. Night Shyamalan', 'Sam Mendes'], 2000: ['Stephen Daldry', 'Ang Lee', 'Steven Soderbergh', 'Ridley Scott', 'Steven Soderbergh'], 2001: ['Ridley Scott', 'Robert Altman', 'Peter Jackson', 'David Lynch', 'Ron Howard'], 2002: ['Rob Marshall', 'Martin Scorsese', 'Stephen Daldry', 'Pedro Almodovar', 'Roman Polanski'], 2003: ['Fernando Meirelles', 'Sofia Coppola', 'Peter Weir', 'Clint Eastwood', 'Peter Jackson'], 2004: ['Martin Scorsese', 'Taylor Hackford', 'Alexander Payne', 'Mike Leigh', 'Clint Eastwood'], 2005: ['Ang Lee', 'Bennett Miller', 'Paul Haggis', 'George Clooney', 'Steven Spielberg'], 2006: ['Alejandro Gonzaalez Inarritu', 'Clint Eastwood', 'Stephen Frears', 'Paul Greengrass', 'Martin Scorsese'], 2007: ['Julian Schnabel', 'Jason Reitman', 'Tony Gilroy', 'Paul Thomas Anderson', 'Joel Coen', 'Ethan Coen'], 2008: ['David Fincher', 'Ron Howard', 'Gus Van Sant', 'Stephen Daldry', 'Danny Boyle'], 2009: ['James Cameron', 'Quentin Tarantino', 'Lee Daniels', 'Jason Reitman', 'Kathryn Bigelow'], 2010: ['Darren Aronofsky', 'David O. Russell', 'David Fincher', 'Ethan Coen', 'Joel Coen', 'Tom Hooper']} |
Question 2
Provide a list with the name(s) of the director(s) with the most Oscar wins. We are asking for a list because there could be more than 1 director tied for the most Oscar wins.
1 | winners = {1931: ['Norman Taurog'], 1932: ['Frank Borzage'], 1933: ['Frank Lloyd'], 1934: ['Frank Capra'], 1935: ['John Ford'], 1936: ['Frank Capra'], 1937: ['Leo McCarey'], 1938: ['Frank Capra'], 1939: ['Victor Fleming'], 1940: ['John Ford'], 1941: ['John Ford'], 1942: ['William Wyler'], 1943: ['Michael Curtiz'], 1944: ['Leo McCarey'], 1945: ['Billy Wilder'], 1946: ['William Wyler'], 1947: ['Elia Kazan'], 1948: ['John Huston'], 1949: ['Joseph L. Mankiewicz'], 1950: ['Joseph L. Mankiewicz'], 1951: ['George Stevens'], 1952: ['John Ford'], 1953: ['Fred Zinnemann'], 1954: ['Elia Kazan'], 1955: ['Delbert Mann'], 1956: ['George Stevens'], 1957: ['David Lean'], 1958: ['Vincente Minnelli'], 1959: ['William Wyler'], 1960: ['Billy Wilder'], 1961: ['Jerome Robbins', 'Robert Wise'], 1962: ['David Lean'], 1963: ['Tony Richardson'], 1964: ['George Cukor'], 1965: ['Robert Wise'], 1966: ['Fred Zinnemann'], 1967: ['Mike Nichols'], 1968: ['Carol Reed'], 1969: ['John Schlesinger'], 1970: ['Franklin J. Schaffner'], 1971: ['William Friedkin'], 1972: ['Bob Fosse'], 1973: ['George Roy Hill'], 1974: ['Francis Ford Coppola'], 1975: ['Milos Forman'], 1976: ['John G. Avildsen'], 1977: ['Woody Allen'], 1978: ['Michael Cimino'], 1979: ['Robert Benton'], 1980: ['Robert Redford'], 1981: ['Warren Beatty'], 1982: ['Richard Attenborough'], 1983: ['James L. Brooks'], 1984: ['Milos Forman'], 1985: ['Sydney Pollack'], 1986: ['Oliver Stone'], 1987: ['Bernardo Bertolucci'], 1988: ['Barry Levinson'], 1989: ['Oliver Stone'], 1990: ['Kevin Costner'], 1991: ['Jonathan Demme'], 1992: ['Clint Eastwood'], 1993: ['Steven Spielberg'], 1994: ['Robert Zemeckis'], 1995: ['Mel Gibson'], 1996: ['Anthony Minghella'], 1997: ['James Cameron'], 1998: ['Steven Spielberg'], 1999: ['Sam Mendes'], 2000: ['Steven Soderbergh'], 2001: ['Ron Howard'], 2002: ['Roman Polanski'], 2003: ['Peter Jackson'], 2004: ['Clint Eastwood'], 2005: ['Ang Lee'], 2006: ['Martin Scorsese'], 2007: ['Ethan Coen', 'Joel Coen'], 2008: ['Danny Boyle'], 2009: ['Kathryn Bigelow'], 2010: ['Tom Hooper']} |
Change Values
You can change the value of a specific item by referring to its key name
.
1 | d = { |
You can updates the dictionary with the specified key-value pairs by using update()
.
1 | d = { |
Loop Through a Dictionary
You can loop through a dictionary by using a for
loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
1 | d = { |
You can also use the values()
function to return values of a dictionary.
1 | for x in d.values(): |
Loop through both keys and values, by using the items()
function.
1 | for x, y in d.items(): |
Check if Key Exists
To determine if a specified key is present in a dictionary use the in
keyword.
1 | d = { |
Dictionary Length
As same as List
.
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
1 | d = { |
Removing Items
The pop()
method removes the item with the specified key name.
1 | d = { |
The popitem()
method removes the last inserted item (in versions before 3.7, a random item is removed instead)
1 | d = { |
The del
keyword removes the item with the specified key name.
1 | d = { |
The clear() keyword empties the dictionary.
1 | d = { |
Copy a Dictionary
copy(): As same as list
.
Another way to make a copy is to use the built-in method dict()
.
1 | d = { |
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries
.
1 | myfamily = { |
Or, if you want to nest three dictionaries that already exists as dictionaries:
1 | child1 = { |
Or you can let a list
in the dict
:
1 | d = {"color": []} |
If you just add item instead of using append() method, you will change the list to the str.
1 | d = {"color": []} |
Extract value from a nested dictionary:
1 | # Create a dict named data; data has one key. |
Extract value one by one in a nested dictionary:
1 | # Create a dict named data; data has one key. |
The dict() Constructor
It is also possible to use the dict()
constructor to make a new dictionary.
1 | d = dict(brand="Ford", model="Mustang", year=1964) |
Dict Comprehension
1 | d = {i: i**2 for i in range(-4, 0)} |
Built-in methods
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and values |
get() | Returns the value of the specified key |
items() | Returns a list containing a tuple for each key value pair |
keys() | Returns a list containing the dictionary’s keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |
Python Conditions
If … Else
Truth Value Testing
Constant defined to be false:
None
andFalse
Zero of any numeric type
0
0.0
0j
Empty sequences and collections
""
()
[]
{}
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
- Equals:
a == b
- Not Equals:
a != b
- Less than:
a < b
- Less than or equal to:
a <= b
- Greater than:
a > b
- Greater than or equal to:
a >= b
hence conditions can be used in several ways, most commonly in “if statements” and loops.
An “if statement” is written by using the if
keyword.
1 | a = 7 |
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.
Note: Tab and Space are both OK. But Tab is the better choice.
1 | a = 7 |
Elif
The elif
keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.
1 | a = 7 |
Else
The else keyword catches anything which isn’t caught by the preceding conditions.
1 | a = 10 |
1 | a = 10 |
And
The and
keyword is a logical operator, and is used to combine conditional statements:
1 | a = 10 |
Or
The or
keyword is a logical operator, and is used to combine conditional statements:
1 | a = 10 |
Bad examples
1 | weather = "rain" |
1 | weather = "rain" |
Nested If
You can have if
statements inside if
statements, this is called nested if
statements.
1 | t = -10 |
Be careful writing expressions that use logical operators
if
statements cannot be empty, but if you for some reason have an if
statement with no content, put in the pass
statement to avoid getting an error.
1 | t = 10 |
Python While Loops
The while Loop
With the while
loop we can execute a set of statements as long as a condition is true.
Note: remember to increment i, or else the loop will continue forever.
1 | i = 1 |
The break Statement
With the break
statement we can stop the loop even if the while condition is true:
1 | i = 1 |
The continue Statement
With the continue
statement we can stop the current iteration, and continue with the next:
1 | i = 1 |
The else Statement
With the else
statement we can run a block of code once when the condition no longer is true:
1 | i = 1 |
Python For Loops
A for
loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for
keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for
loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Note: The for
loop does not require an indexing variable to set beforehand
1 | for i in [0, 1, 2]: |
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
1 | for i in "Fxxk CCP": |
The break Statement
With the break
statement we can stop the loop before it has looped through all the items:
1 | for i in range (0, 3): |
The continue Statement
With the continue
statement we can stop the current iteration of the loop, and continue with the next:
1 | for i in range (0, 3): |
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass
statement to avoid getting an error.
1 | for i in range (0, 3): # Notice this result is different from the continue statement |
The range() Function
To loop through a set of code a specified number of times, we can use the range()
function,
The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Note: The range(start=0, stop)
function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
1 | for i in range (0, 3): |
The range(start=0, stop, step=1)
function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(1, 10, 3):
1 | list(range(1, 10, 2)) |
1 | help(range) |
Else in For Loop
The else
keyword in a for
loop specifies a block of code to be executed when the loop is finished:
1 | for i in range(1, 10, 3): |
Nested Loops
A nested loop is a loop
inside a loop
.
The “inner loop” will be executed one time for each iteration of the “outer loop”:
1 | adj = ["red", "big", "tasty"] |
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
1 | def my_function(): |
Calling a Function
To call a function, use the function name followed by parenthesis:
1 | # A function returns a sentence |
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
1 | # A function prints hello name. |
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function’s perspective:
- A parameter is the variable listed inside the parentheses in the function definition.
- An argument is the value that are sent to the function when it is called.
Required Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
1 | # A function prints capitalized name |
Arguments are often shortened to args in Python documentations.
args are positional arguments.
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
1 | # A function prints capitalized name |
Arbitrary Arguments are often shortened to *args in Python documentations.
*args are positional arguments.
Keyword Arguments, kwargs
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
1 | # A function prints capitalized name with a title |
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
kwargs are NOT positional arguments.
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function, add two asterix: **
before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
1 | # A function prints capitalized name with a title |
Arbitrary Keyword Arguments are often shortened to *kwargs* in Python documentations.
*kwargs* are NOT positional arguments
Default Parameter Value
If we call the function without argument, it uses the default value:
1 | # A function prints capitalized name with a title and country |
Keyword-only Arguments
If we use keyword arguments, we cannot restrain what the user input.
Take the example from Default Parameter Value:
This function accept the unexpected parameter (gender).
1 | # A function prints capitalized name with a title and country |
We successfully import gener = "man"
to the function even it will not be executed. But it is still dangerous.
A keyword-only argument could help us restraining user input.
We can use *
to split the arguments. The arguments after *
are keyword-only arguments, which could have a default value.
This function prevents from the unexpected parameter (gender).
1 | # A function prints capitalized name with a title and country |
You can Also use *args to split the arguments:
1 | # A function prints capitalized name with a title and country |
Order of Arguments
Warning!!!
Basically, you must define a function in the following way to avoid SyntaxError: positional argument follows keyword argumen
:
1 | def function_name(positional arguments, keyword arguments): |
And the detailed order is:
- Positional arguments, arg
- Default arguments
- Arbitrary Arguments, *arg
- Keyword-only arguments
- Keyword arguments, kwargs
1 | # Notice in this example, country = "United States" is NOT a default argument; it is a Keyword-only arguments since it follows the *arg. |
Return Values
To let a function return a value, use the return
statement:
1 | # A function returns your bmi |
Return is one of the most important concepts! A deep learning could help us understand it
Here is a for
statement to print a series numbers in a range:
1 | for i in range(3): |
Let’s do the same thing in a function, then call it:
1 | # A function prints the values in a range one by one. |
You may understand that sometimes print()
and return()
all print the result on your screen:
1 | # A function RETURNS your bmi |
1 | # A function PRINTS your bmi |
However, if try to do the same thing in return
.
1 | # A function PRINTS the values in a range one by one. |
1 | # A function try to RETURN the values in a range one by one, but it doesn't work. |
This is weird, right? Why the function only print 0
on the screen? Because return
only runs once in a function! And everything after return
will be ignored!
1 | def hello_1(): |
From the official definition:return
may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else None
is substituted.
return
leaves the current function call with the expression list (or None
) as return value.
When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.
The pass Statement
function
definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass
statement to avoid getting an error.
1 | def my_function(): |
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
SUM example:
1 | # For loop: |
1 | # A function returns exponentiation |
Notice the following two functions are not the same!
1 | def sum_of_squares(n): |
1 | def sum_of_squares(n): |
Example
1 | def countdown(n): |
1 | def countdown(n): |
Why Recursion?
It’s tremendously useful when the problem is self-similar.
It’s no more powerful than iteration, but often leads to more concise & better code.
It’s more mathematical.
It’s embodies the beauty and joy of computing.
Example: Exponential operation
In Python, you can execute Exponential operation in a easy way:
1 | def iter_exp(x, n): |
In chapter Recursion, we have learned another function to return an exponential operation. However, this one mey consume less computing resource since it invoke function less times.
1 | # A function returns exponentiation |
Example: Factorials
1 | def iter_fact(n): |
1 | def fact(n): |
Example: Fibonacci numbers
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
$${\displaystyle F_{0}=0,\quad F_{1}=1,}$$
and
$${\displaystyle F_{n}=F_{n-1}+F_{n-2},}$$
for $n > 1$.
The beginning of the sequence is thus:
$${\displaystyle 0,;1,;1,;2,;3,;5,;8,;13,;21,;34,;55,;89,;144,;\ldots }$$
1 | def iter_fib(n): |
1 | def fib(n): |
Example: Reverse a string
1 | def reverse(s): |
Example: Minimum Number
1 | def first(s): |
Example: Quicksort
- A fairly simple to sorting algorithm
- Goal: Sort the list by breaking it into partially sorted parts – Pick a “pivot”, a starting item to split the list
– Remove the pivot from your list
– Split the list into 2 parts, a smaller part and a bigger part
– Then recursively sort the smaller and bigger parts
– Combine everything together: the smaller list, the pivot, then the bigger list
Example
Quick Sort
1 | def split(x, s): |
Example: Filter
1 | def iter_filter(f, seq): |
1 | def filter(f, seq): |
Example: Sum Difference
1 | def iter_sum_diffs(n): |
1 | def sum_diffs(n): |
Example: Insect Combinatorics
Consider an insect in an M by N grid. The insect starts at the bottom left corner, (0, 0), and wants to end up at the top right corner, (M-1, N-1). The insect is only capable of moving right or up. Write a function paths that takes a grid length and width and returns the number of different paths the insect can take from the start to the goal. (There is a closed-form solution to this problem, but try to answer it procedurally using recursion.)
For example, the 2 by 2 grid has a total of two ways for the insect to move from the start to the goal. For the 3 by 3 grid, the insect has 6 different paths (only 3 are shown above).
Solution Recursion
1 | def paths(m, n): |
Solution Math Combination
The question is equal to how many combinations of up
, right
, where the number of up = m-1
and the number of right = n-1
Permutations
There are basically two types of permutation:
- Repetition is Allowed: such as the lock above. It could be “333”.
- No Repetition: for example the first three people in a running race. You can’t be first and second.
Combinations
There are also two types of combinations (remember the order does not matter now):
- Repetition is Allowed: such as coins in your pocket (5,5,5,10,10)
- No Repetition: such as lottery numbers (2,14,15,27,30,33)
For example,
- paths(2, 2)
- m-1, n-1 = 1, 1
- 1 right & 1 up has TWO combinations: up, right; right up
- The math formula is: $C(n, k) = C(4, 2) = \frac{4!}{2!}$
1 | from math import factorial |
Example: Reduce
Write the recursive version of the function reduce
which takes
- reducer - a two-argument function that reduces elements to a single value
- seq - a sequence of values
- base - the starting value in the reduction. This is usually the identity of the reducer
1 | def iter_reduce(reducer, seq, base): |
1 | def reduce(reducer, seq, base): |
Example: Remove Last from Sequence
remove_last
creates a new list identical to the input list s
but with the last element in the sequence that is equal to x
removed.
1 | def remove_last(x, s): |
1 | def remove_last(x, s): |
Example: Create Number from Lists
Write a recursive function create_num_from_lsts
that creates a number with the elements from lst1
and lst2
as digits in that order.
1 | def iter_create_num_from_lsts(lst1, lst2): |
1 | def create_num_from_lsts(lst1, lst2): |
Example: Coin Change 2
A set of coins makes change for n
if the sum of the values of the coins is n
. For example, if you have 1-cent, 2-cent and 4-cent coins, the following sets make change for 7
:
- 7 1-cent coins
- 5 1-cent, 1 2-cent coins
- 3 1-cent, 2 2-cent coins
- 3 1-cent, 1 4-cent coins
- 1 1-cent, 3 2-cent coins
- 1 1-cent, 1 2-cent, 1 4-cent coins
Thus, there are 6 ways to make change for 7
. Write a function count_change
that takes a positive integer n
and a list of the coin denominations and returns the number of ways to make change for n
using these coins (Hint: You will need to use tree recursion):
Coin/Amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
2 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 |
5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
Remove 1, because any amount has 1 solution for coin = 1.
for example:
amount = 2
- 1: 1 + 1
- 2: 2
amount = 3
- 1: 1 + 1 + 1
- 1 & 2: 1 + 2
amount = 4
- 1: 1 + 1 + 1 + 1
- 2: 2 + 2
- 1 & 2: 1 + 1 + 2
amount = 5
- 1: 1 + 1 + 1 + 1 + 1
- 5: 5
- 1 & 2:
- 1 + 2 + 2
- 1 + 1 + 1 + 2
1 | def iter_count_change(amount, denominations): |
1 | def count_change(amount, denominations): |
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
1 | lambda [argument]: [expression] |
The expression is executed and the result is returned:
1 | x = lambda a : a + 10 |
Lambda functions can take any number of arguments:
1 | x = lambda a, b : a * b |
A lambda
expression by itself is not very interesting. As with any objects such as numbers, booleans, strings, we usually:
- assign lambda to variables (
foo = lambda x: x
) - pass them in to other functions (
bar(lambda x: x)
) - return them as the results of other functions (
return lambda x: x
) - return them as the results of other lambdas (
lambda x: lambda y: x + y
)
In the final example above, the outer lambda (lambda x
) takes in a value x
, and it
returns another lambda (lambda y
) that takes an argument y
and returns x+y
.
Difference between lambda
and def
While both lambda
and def
statements are related to functions, there are some differences.
lambda | def | |
---|---|---|
Type | lambda is an expression |
def is a statement |
Description | Evaluating a lambda expression does not create or modify any variables.
Lambda expressions just create new function objects. |
Executing a def statement will create a new function object and bind it to a variable in the current environment. |
Example |
|
|
If..else in Lambda
1 | lambda x: True if x % 2 == 0 else False |
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
1 | def myfunc(n): |
Use that function definition to make a function that always doubles the number you send in:
1 | def myfunc(n): |
Use lambda functions when an anonymous function is required for a short period of time.
Examples
1 | b = lambda x: lambda: x # Lambdas can return other lambdas! |
1 | d = lambda f: f(4) # They can have functions as arguments as well. |
1 | z = 3 |
1 | higher_order_lambda = lambda f: lambda x: f(x) |
1 | call_thrice = lambda f: lambda x: f(f(f(x))) |
1 | print_lambda = lambda z: print(z) # When is the return expression of a lambda expression executed? |
Python Classes and Object
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a “blueprint” for creating objects.
Create a Class
To create a class, use the keyword class
:
1 | # Create a class named MyClass, with a property named x: |
Create Object
Now we can use the class named myClass
to create objects:
1 | # Create an object named p1, and print the value of x: |
The init() Function
The examples above are classes
and objects
in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__()
function.
All classes have a function called __init__()
, which is always executed when the class is being initiated.
Use the __init__()
function to assign values to object properties, or other operations that are necessary to do when the object is being created:
Create a class named Person, use the init() function to assign values for name and age:
1 | class Person: |
Note: The __init__()
function is called automatically every time the class is being used to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
Let us create a method in the Person class:
Insert a function that prints a greeting, and execute it on the p1 object:
1 | class Person: |
Note: The self
parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
Notice the difference
1 | class Person: |
The self Parameter
The self
parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self
, you can call it whatever you like, but it has to be the first parameter of any function in the class:
Use the words tmp and abc instead of self:
1 | class Person: |
Modify Object Properties
You can modify properties on objects like this:
1 | p1.age = 18 |
Delete Object Properties
You can delete properties on objects by using the del keyword:
1 | del p1.age |
Delete Objects
You can delete objects by using the del keyword:
1 | del p1 |
The pass Statement
class
definitions cannot be empty, but if you for some reason have a class
definition with no content, put in the pass
statement to avoid getting an error.
1 | class Person: |
Built-in Proerties
Magic Methods start and end with “double underscores” __
__init__
: Called when making a new instance__add__
:+
operator__sub__
:-
operator__getitem__
:[]
operator__str__
: Called when we call print()__repr__
: Called in the interpreter
init example
1 | class BaseAccount: |
repr and str example
1 | class BaseAccount: |
Why do we need a class/object?
Imagine you are planning to make a program that returns weather of users’ specified location every day. Your first idea is creating a function, I guess:
Weather Program.py 1.0
1 | # Provide weather information based on location |
One day you want to add a function to provide more information, for example, humidity. You may consider change your old function:
Weather Program.py 1.1
1 | # Provide weather information based on location |
What if you need more functions? For example, the chance of rain? And how to show weather in 5 days? You’d better design a good structure for your program for future updating. Class is the best way to do this.
Let’s reproduce the basic function first:
Weather Program.py 2.0
1 | class Weather: |
Notice we did a very important step is def Summary(self)
, which is the function to invoke all functions above in self.myFunction()
way. It means we separate every function in different areas. And we can update them respectively.
Then we can try to add new functions:
Weather Program.py 2.1
1 | class Weather: |
Every time we add new functions, we only need to add a def myFunction():
, which are more readable and intuitive. Let’s try to show the weather information for 5 days. Notice how I can pass the parameter inner the class
.
Weather Program.py 3.0
1 | import datetime |
Finally, let’s make it to become a real Weather program!
1 | #!/usr/bin/env python3 |
I use an open source weather API to gather the weather information. Then I will recieve a request like this:
Demo request
1 | print(x['list'][0]) |
This is a nested dict
variable that transformed from a JSON
file. The only thing I need to do is extract the information I need then transfer them to a readable style.
Update:
1 | import requests |
Add function to class after its definitation
1 | class Calculator: |
1 | calculator = Calculator() |
1 | calculator.mean(l) |
Add a new function double
to Calculator
1 | def double(self, lst): |
1 | calculator.double(l) |
1 | dir(calculator) |
1 | ['__class__', |
Class Examples
Car
1 | # Car |
keyboard
We’d like to create a Keyboard
class that takes in an arbitrary number of Buttons and stores these Buttons
in a dictionary. The keys in the dictionary will be ints that represent the position on the Keyboard
, and the values will be the respective Button. Fill out the methods in the Keyboard
class according to each description, using the doctests as a reference for the behavior of a Keyboard
.
1 | # Keyboard |
T88ble
In this lab, you will implement a version of the Table object from Data 8, that we are calling T88ble
, appropriately pronounced T-88-bel. We aren’t going to make you implement every single function, but we have table.select()ed
the functions table.where(difficulty, are.below(insane))
and table.where(concepts, are.equal_to(relevant))
.
Notice that we are representing tables here as a list of rows.
Complete the num_rows
, num_cols
, and labels
functions according to the docstrings.
Complete the column
, select
, and with_column
functions according to the docstrings.
You might find the list.index(value)
function to be particularly useful for this problem.
Complete the where
function according to the docstring.
1 | # T88ble |
Person
Modify the following Person
class to add a repeat
method, which repeats the last thing said. If nothing has been said yet, you can have repeat
return a string of your choosing. See the doctests for an example of its use.
1 | # 00P |
Account
There are several things wrong with the following code! Debug the Account
class to satisfy the docstring.
1 | class Account(object): |
Vending Machine
Create a class called VendingMachine
that represents a vending machine for some product. A VendingMachine
object returns strings describing its interactions. See the doctest below for examples:
Here’s a quick explanation of some of the functions you need to implement.
restock
should update the stock and return the current stock.deposit
should add money to the balance and return the current balance, unless the stock is zero, then it should inform the user the stock is zero and return the money.vend
should either tell you how much more money needs to be deposited to buy a product, or sell you a product and return the change, or let you know the machine is out of stock.
Make sure your outputs match the doctest exactly!
1 | class VendingMachine: |
Arr88
In lab you created the T88ble, now you will create arr88, which are similar to numpy arrays from Data 8.
Complete the __len__
, and item functions according to the docstrings.
__len__
is a special attribute, like __init__
that allows us to call len on our Arr88s to get their length!
Complete the __add__
, __mul__
, and negate
functions according to the docstrings.
Keep an eye out for which functions mutate the Arr88 and which don’t!
__add__
and __mul__
are also special attributes, like __init__
and __len__
, that allow us to use + and * on our Arr88s to add/multiply them componentwise!
Complete the apply
function that returns a new list with the function applied to every element.
1 | class Arr88(): |
Python Inheritance
Introduction
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
Create a class named Person, with firstname
and lastname properties, and a
fullname` method:
1 |
|
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:
Create a class named Student, which will inherit the properties and methods from the Person class:
1 | class Person: |
Note: Use the pass
keyword when you do not want to add any other properties or methods to the class.
Now the Student class has the same properties and methods as the Person class.
Use the Student class to create an object, and then execute the fullname method:
1 | class Person: |
Add the init() Function
So far we have created a child class that inherits the properties and methods from its parent.
We want to add the __init__()
function to the child class (instead of the pass
keyword).
Note: The __init__()
function is called automatically every time the class is being used to create a new object.
Add the __init__()
function to the Student class:
1 | class Student(Person): |
When you add the __init__()
function, the child class will no longer inherit the parent’s __init__()
function.
Note: The child’s __init__()
function overrides the inheritance of the parent’s __init__()
function.
To keep the inheritance of the parent’s __init__()
function, add a call to the parent’s __init__()
function:
1 | class Person: |
If you did not inherit the Parent’s __init__
1 | class Person: |
Now we have successfully added the __init__()
function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__()
function.
Use the super() Function
Python also has a super()
function that will make the child class inherit all the methods and properties from its parent:
1 | class Person: |
1 | class Person: |
By using the super()
function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
Add Properties
Add a property called age to the Student class’s __init__()
:
1 | class Person: |
Add Methods
Add a method called welcome to the Student class:
1 | class Person: |
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.
1 |
|
Examples
Mint
Complete the Mint
and Coin
classes so that the coins created by a mint have the correct year and worth.
- Each
Mint
instance has ayear
stamp. Theupdate
method sets theyear
stamp to thecurrent_year
class attribute of the Mint class. - The
create
method takes a subclass ofCoin
and returns an instance of that class stamped with the mint’s year (which may be different fromMint.current_year
if it has not been updated.) - A
Coin
‘sworth
method returns thecents
value of the coin plus one extra cent for each year of age beyond 50. A coin’s age can be determined by subtracting the coin’s year from thecurrent_year
class attribute of the Mint class.
1 | class Mint: |
Quidditch
It’s time for the opening quidditch match of the season! We represent the various positions for players with the QuidditchPlayer
class and its subclasses. Every player begins with a base_energy
level, but every position requires a different proportion of energy. Fill in the energy
method for the Beater
, Chaser
, Seeker
, and Keeper
classes, according to their docstrings. In addition, fill in the __init__
method for the Chaser class.
1 | class QuidditchPlayer: |
Errors
It is often said that nothing in life is certain but death and taxes. For a programmer or data scientist, however, nothing is certain but encountering errors.
In Python, there are two primary types of errors, both of which you are likely familiar with: syntax errors and exceptions. Syntax errors occur when the proper structure of the language is not followed, while exceptions are errors that occur during the execution of a program. These include errors such as ZeroDivisionError, TypeError, NameError, and many more!
Under the hood, these errors are based in the concepts of object orientation, and all exceptions are class objects. If you’re interested in more detailed explanations of the structure of exceptions as well as how to create your own, check out this article from the Python documentation! In the meantime, we’ll implement our own version of an Error class
Complete the Error
, SyntaxError
, and ZeroDivisionError
classes such that they create the correct messages when called.
- The
SyntaxError
andZeroDivisionError
classes inherit from the Error class and add functionality that is unique to those particular errors. Their code is partially implemented for you. - The
add_code
method adds a new helpful message to your error, while thewrite
method should print the output that you see when an error is raised. - You can access the parent class methods using the super() function
1 | class Error: |
Checking account
We’d like to be able to cash checks, so let’s add a deposit_check
method to our CheckingAccount
class. It will take a Check object as an argument, and check to see if the payable_to
attribute matches the CheckingAccount
‘s holder. If so, it marks the Check as deposited, and adds the amount specified to the CheckingAccount
‘s total.
Write an appropriate Check
class, and add the deposit_check
method to the CheckingAccount
class. Make sure not to copy and paste code! Use inheritance whenever possible.
See the doctests for examples of how this code should work.
The Account
class has been provided.
1 | class Account(object): |
Python Iterators
Introduction
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__()
and __next__()
.
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
All these objects have a iter()
method which is used to get an iterator:
Return an iterator from a list, and print each value:
1 | l1 = [1, 2, 3] |
Even strings are iterable objects, and can return an iterator:
Strings are also iterable objects, containing a sequence of characters:
1 | s1 = "GUNDAM" |
Looping Through an Iterator
We can also use a for
loop to iterate through an iterable object:
1 | l1 = [1, 2, 3] |
1 | s1 = "GUNDAM" |
The for loop actually creates an iterator object and executes the next() method for each loop.
Create an Iterator
To create an object/class as an iterator you have to implement the methods __iter__()
and __next__()
to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__()
, which allows you do some initializing when the object is being created.
The __iter__()
method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
The __next__()
method also allows you to do operations, and must return the next item in the sequence.
Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):
1 | class MyNumbers: |
StopIteration
The example above would continue forever if you had enough next() statements, or if it was used in a for
loop.
To prevent the iteration to go on forever, we can use the StopIteration
statement.
In the __next__()
method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:
Stop the program after 20 iterations:
1 | class MyNumbers: |
Python Scope
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
The variable you used in a outside loop is NOT a local scope:
1 | del(i) |
A variable created inside a function is available inside that function:
1 | del(i) |
The Benefits of Non-Local Assignment
Python Particulars. This pattern of non-local assignment is a general feature of programming languages with higher-order functions and lexical scope. Most other languages do not require a nonlocal statement at all. Instead, non-local assignment is often the default behavior of assignment statements.
Python also has an unusual restriction regarding the lookup of names: within the body of a function, all instances of a name must refer to the same frame. As a result, Python cannot look up the value of a name in a non-local frame, then bind that same name in the local frame, because the same name would be accessed in two different frames in the same function. This restriction allows Python to pre-compute which frame contains each name before executing the body of a function. When this restriction is violated, a confusing error message results.
Non-local assignment is an important step on our path to viewing a program as a collection of independent and autonomous objects, which interact with each other but each manage their own internal state.
In particular, non-local assignment has given us the ability to maintain some state that is local to a function, but evolves over successive calls to that function.
This UnboundLocalError
appears because balance
is assigned locally in line 5, and so Python assumes that all references to balance must appear in the local frame as well. This error occurs before line 5 is ever executed, implying that Python has considered line 5 in some way before executing line 3. As we study interpreter design, we will see that pre-computing facts about a function body before executing it is quite common. In this case, Python’s pre-processing restricted the frame in which balance could appear, and thus prevented the name from being found. Adding a nonlocal statement corrects this error. The nonlocal statement did not exist in Python 2.
1 | def make_withdraw(balance): |
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Global variables are available from within any scope, global and local.
A variable created outside of a function is global and can be used by anyone:
1 | x = 5 |
Naming Variables
If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):
The function will print the local x, and then the code will print the global x:
1 | x = 5 |
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can use the global
keyword.
The global
keyword makes the variable global.
If you use the global
keyword, the variable belongs to the global scope:
1 | def myFunc(): |
Also, use the global
keyword if you want to make a change to a global variable inside a function.
To change the value of a global variable inside a function, refer to the variable by using the global keyword:
1 | x = 5 |
Python ADT
https://cs88-website.github.io/sp21/lab/lab04/#abstract-data-types
https://cs88-website.github.io/sp21/hw/hw04/#politican-adts
Usage
Data abstraction is a powerful concept in computer science that allows programmers to treat code as objects — for example, car objects, chair objects, people objects, etc. That way, programmers don’t have to worry about how code is implemented — they just have to know what it does.
Data abstraction mimics how we think about the world. For example, when you want to drive a car, you don’t need to know how the engine was built or what kind of material the tires are made of. You just have to know how to turn the wheel and press the gas pedal.
An abstract data type consists of two types of functions:
- Constructors: functions that build the abstract data type.
- Selectors: functions that retrieve information from the data type.
For example, say we have an abstract data type called definePolitician
. This definePolitician
object will hold the Politician’s name, and Politician’s party and Politician’s age. To create a definePolitician object, you’d use a constructor like
1 | <politician> = definePolitician('<name>', '<party>', <age>) |
Notice that we don’t need to know how these functions were implemented. We are assuming that someone else has defined them for us.
It’s okay if the end user doesn’t know how functions were implemented. However, the functions still have to be defined by someone. We’ll look into defining the constructors and selectors later in this discussion.
Example:
I defined an Abstract Data Type that can be reused.
Users could reconstruct or query the ADT data but ignore the data structure.
Imagine you need to define 100 politicians. Without ADT, you have to repeatly type {'name'='<name>', 'party'='<party>', 'age'=<age>}
.
1 | def definePolitician(name, party, age): |
Use lambda to define ADT.
1 | def definePolitician(name, party, age): |
Use class to simulate ADT.
1 |
|
Think if we can construct class through ADT method in order to reduce code.
Python Modules (Packages)
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py
:
Save the following code as Math.py
1 | def exp(b, n): |
Use a Module
Now we can use the module we just created, by using the import
statement:
Two ways to import a module:
1 | import Math |
OR
1 | from Math import exp |
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
Save the following code as tmp.py
.
1 | person = { |
1 | import tmp |
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as
keyword:
1 | import tmp as population |
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:
1 | import platform |
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The dir()
function:
List all the defined names belonging to the platform module:
1 | import Math |
Anaconda
By default, the Python interpreter will search for all installed built-in modules and third-party modules in the current working directory. The search path is stored in the path
variable of the sys
module.
1 | import platform |
Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, etc.), that aims to simplify package management and deployment. Package versions are managed by the package management system conda. The Anaconda distribution includes data-science packages suitable for Windows, Linux, and MacOS. Click here to Download Anaconda, and choose 64-Bit Command Line Installer
.
Then run the installer in your shell, the installer version may be different:
1 | bash Anaconda3-2019.10-MacOSX-x86_64.sh |
Before install Anaconda.
After install Anaconda.
1 | import platform |
Anaconda integrates abundant packages for data science, which means you do not need to install them one by one. However, if you want to add another path including some packages to your python and the path is not your current .py
file path, there are two ways to reach your target.
Add a temporary path
Replace /tmp
to your path.
1 | import sys |
Add a permanent path
https://bic-berkeley.github.io/psych-214-fall-2016/using_pythonpath.html
name
To avoid running executable statements in a script when it’s imported as a module in another script, include these lines in an if __name__ == "__main__"
block. Or alternatively, include them in a function called main() and call this in the if main
block.
Whenever we run a script like this, Python actually sets a special built-in variable called __name__
for any module. When we run a script, Python recognizes this module as the main program, and sets the __name__
variable for this module to the string "__main__"
. For any modules that are imported in this script, this built-in __name__
variable is just set to the name of that module. Therefore, the condition if __name__ == "__main__"
is just checking whether this module is the main program.
Standard Library
csv
: very convenient for reading and writing csv filescollections
: useful extensions of the usual data types includingOrderedDict
,defaultdict
andnamedtuple
random
: generates pseudo-random numbers, shuffles sequences randomly and chooses random itemsstring
: more functions on strings. This module also contains useful collections of letters likestring.digits
(a string containing all characters which are valid digits).re
: pattern-matching in strings via regular expressionsmath
: some standard mathematical functionsos
: interacting with operating systemsos.path
: submodule ofos
for manipulating path namessys
: work directly with the Python interpreterjson
: good for reading and writing json files (good for web work)
Third-Party Libraries
There are tens of thousands of third-party libraries written by independent developers! You can install them using pip, a package manager that is included with Python 3. pip is the standard package manager for Python, but it isn’t the only one. One popular alternative is Anaconda which is designed specifically for data science.
To install a package using pip, just enter “pip install” followed by the name of the package in your command line like this: pip install package_name
. This downloads and installs the package so that it’s available to import in your programs. Once installed, you can import third-party packages using the same syntax used to import from the standard library.
Using a requirements.txt
File
Larger Python programs might depend on dozens of third party packages. To make it easier to share these programs, programmers often list a project’s dependencies in a file called requirements.txt. This is an example of a requirements.txt file.
1 | beautifulsoup4==4.5.1 |
Each line of the file includes the name of a package and its version number. The version number is optional, but it usually should be included. Libraries can change subtly, or dramatically, between versions, so it’s important to use the same library versions that the program’s author used when they wrote the program.
You can use pip to install all of a project’s dependencies at once by typing pip install -r requirements.txt
in your command line.
Useful Third-Party Packages
Being able to install and import third party libraries is useful, but to be an effective programmer you also need to know what libraries are available for you to use. People typically learn about useful new libraries from online recommendations or from colleagues. If you’re a new Python programmer you may not have many colleagues, so to get you started here’s a list of packages that are popular with engineers at Udacity.
- IPython - A better interactive Python interpreter
- requests - Provides easy to use methods to make web requests. Useful for accessing web APIs.
- Flask - a lightweight framework for making web applications and APIs.
- Django - A more featureful framework for making web applications. Django is particularly good for designing complex, content heavy, web applications.
- Beautiful Soup - Used to parse HTML and extract information from it. Great for web scraping.
- pytest - extends Python’s builtin assertions and unittest module.
- PyYAML - For reading and writing YAML files.
- NumPy - The fundamental package for scientific computing with Python. It contains among other things a powerful N-dimensional array object and useful linear algebra capabilities.
- pandas - A library containing high-performance, data structures and data analysis tools. In particular, pandas provides dataframes!
- matplotlib - a 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments.
- ggplot - Another 2D plotting library, based on R’s ggplot2 library.
- Pillow - The Python Imaging Library adds image processing capabilities to your Python interpreter.
- pyglet - A cross-platform application framework intended for game development.
- Pygame - A set of Python modules designed for writing games.
- pytz - World Timezone Definitions for Python
Python Datetime
Python Dates
A date in Python is not a data type of its own, but we can import a module named datetime
to work with dates as date objects.
Import datetime
module and show its functions
1 | import datetime |
Import datetime
module and display the current date:
1 | import datetime |
Date Output
When we execute the code from the example above the result will be:
2020, 2, 5, 15, 33, 8, 732931
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime
module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Return the year and name of weekday:
1 | import datetime |
Creating Date Objects
To create a date, we can use the datetime()
class (constructor) of the datetime
module.
The datetime()
class requires three parameters to create a date: year, month, day.
The datetime()
class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0
, (None
for timezone).
Create a date object:
1 | import datetime |
The strftime() Method
The datetime
object has a method for formatting date objects into readable strings.
The method is called strftime()
, and takes one parameter, format
, to specify the format of the returned string:
1 | import datetime |
A reference of all the legal format codes:
Directive | Description | Example |
---|---|---|
%a | Weekday, short version | Wed |
%A | Weekday, full version | Wednesday |
%w | Weekday as a number 0-6, 0 is Sunday | 3 |
%d | Day of month 01-31 | 31 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month as a number 01-12 | 12 |
%y | Year, short version, without century | 18 |
%Y | Year, full version | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 00-12 | 05 |
%p | AM/PM | PM |
%M | Minute 00-59 | 41 |
%S | Second 00-59 | 08 |
%f | Microsecond 000000-999999 | 548513 |
%z | UTC offset | +0100 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 365 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%x | Local version of date | 12/31/18 |
%X | Local version of time | 17:41:00 |
%% | A % character | % |
Time calculation
Time calculation
1 | import datetime |
Stopwatch
1 | import datetime |
Yesterday, Today, and Tomorrow
1 | import datetime |
Python JSON
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
JSON in Python
Python has a built-in package called json
, which can be used to work with JSON data.
Import the json module:
1 | import json |
Parse JSON - Convert from JSON to Python
If you have a JSON string, you can parse it by using the json.loads()
method.
The result will be a Python dictionary.
Convert from JSON to Python:
1 | import json |
Convert from Python to JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps()
method.
Convert from Python to JSON:
1 | import json |
You can convert Python objects of the following types, into JSON strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
Convert Python objects into JSON strings, and print the values:
1 | import json |
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Convert a Python object containing all the legal data types:
1 | import json |
Format the Result
The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
The json.dumps()
method has parameters to make it easier to read the result:
Use the indent parameter to define the numbers of indents:
1 | json.dumps(x, indent=4) |
You can also define the separators, default value is (,
, :
), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:
Use the separators parameter to change the default separator:
1 | json.dumps(x, indent=4, separators=(". ", "= ")) |
Order the Result
The json.dumps()
method has parameters to order the keys in the result:
Use the sort_keys parameter to specify if the result should be sorted or not:
1 | json.dumps(x, indent=4, sort_keys=True) |
Writing JSON to a File
Scott Robinson (August 17, 2016). Reading and Writing JSON to a File in Python
The easiest way to write your data in the JSON format to a file using Python is to use store your data in a dict
object, which can contain other nested dicts
, arrays
, booleans
, or other primitive types like integers
and strings
. You can find a more detailed list of data types supported here.
The built-in json
package has the magic code that transforms your Python dict
object in to the serialized JSON string.
1 | import json |
After importing the json
library, we construct some simple data to write to our file. The important part comes at the end when we use the with
statement to open our destination file, then use json.dump to write the data
object to the outfile
file.
Any file-like object can be passed to the second argument, even if it isn’t an actual file. A good example of this would be a socket, which can be opened, closed, and written to much like a file. With JSON being popular throughout the web, this is another use-case you may encounter.
A slight variation on the json.dump
method that’s worth mentioning is json.dump, which returns the actual JSON string instead of sending it directly to a writable object. This can give you some more control if you need to make some changes to the JSON string (like encrypting it, for example).
Reading JSON from a File
On the other end, reading JSON data from a file is just as easy as writing it to a file. Using the same json
package again, we can extract and parse the JSON string directly from a file object. In the following example, we do just that and then print out the data we got:
1 | import json |
json.load is the important method to note here. It reads the string from the file, parses the JSON data, populates a Python dict
with the data and returns it back to you.
Just like json.dump
, json.load
has an alternative method that lets you deal with strings directly since many times you probably won’t have a file-like object that contains your JSON. As you probably guessed, this method is json.load. Consider the case where you’re calling a REST GET endpoint that returns JSON. This data comes to you as a string, which you can then pass to json.loads
directly instead.
Python RegEx
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions.
Import the re
module:
1 | import re |
RegEx Functions
The re
module offers a set of functions that allows us to search a string for a match:
Function | Description |
---|---|
findall |
Returns a list containing all matches |
search |
Returns a Match object if there is a match anywhere in the string |
split |
Returns a list where the string has been split at each match |
sub |
Replaces one or many matches with a string |
We will try re.findall
function first. Then learn the other three functions.
Metacharacters
Metacharacters are characters with a special meaning:
Character | Description | Example |
---|---|---|
[] |
A set of characters; Or a set for punctuations. | "[a-e]" |
\ |
Signals a special sequence(can also be used to escape special characters) | "\d" |
. |
Any character (except newline character) | "Pa..y" |
^ |
Starts with | "^The" |
$
| Ends with | "2020[.]$" |
* |
Zero or more occurrences | "isx*" |
+ |
One or more occurrences | "ine+" |
? |
Zero or one occurrence | "ab?" |
{} |
Exactly the specified number of occurrences | "om{2} -> omm"; "os{m, n}" |
| |
Either or | "Chi|Com" |
() |
Capture and group | "(ine)(se)*";"(ab|bc)" |
1 | import re |
Special Sequences \
A special sequence is a \
followed by one of the characters in the list below, and has a special meaning:
Character | Description | Example |
---|---|---|
\A |
Returns a match if the specified characters are at the beginning of the string | "\AThe" |
\b |
Returns a match where the specified characters are at the beginning or at the end of a word | r"\bThe" r"2020[.]\b" |
\B |
Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word | r"\BChi" r"hi\B" |
\d |
Returns a match where the string contains digits (numbers from 0-9) | "\d" |
\D |
Returns a match where the string DOES NOT contain digits | "\D" |
\s |
Returns a match where the string contains a white space character | "\s" |
\S |
Returns a match where the string DOES NOT contain a white space character | "\S" |
\w |
Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) | "\w" |
\W |
Returns a match where the string DOES NOT contain any word characters | "\W" |
\Z |
Returns a match if the specified characters are at the end of the string | "2020[.]\Z" |
1 | import re |
Sets []
A set is a set of characters inside a pair of square brackets []
with a special meaning:
Set | Description |
---|---|
[arn] |
Returns a match where one of the specified characters (a , r , or n ) are present |
[a-n] |
Returns a match for any lower case character, alphabetically between a and n |
[^arn] |
Returns a match for any character EXCEPT a , r , and n |
[0123] |
Returns a match where any of the specified digits (0 , 1 , 2 , or 3 ) are present |
[0-9] |
Returns a match for any digit between 0 and 9 |
[0-5][0-9] |
Returns a match for any two-digit numbers from 00 and 59 |
[a-zA-Z] |
Returns a match for any character alphabetically between a and z , lower case OR upper case |
[+] |
In sets, + , * , . , | , () , $ ,{} has no special meaning, so [+] means: return a match for any + character in the string |
1 | import re |
RegEx in Python
When you have imported the re
module, you can start using regular expressions and combine them together:
1 | import re |
The findall() Function
The findall()
function returns a list containing all matches.
1 | import re |
The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
1 | import re |
The search() Function
The search()
function searches the string for a match, and returns a Match object if there is a match.
If there is more than one match, only the first occurrence of the match will be returned:
1 | import re |
If no matches are found, the value None
is returned:
1 | import re |
The split() Function
The split()
function returns a list where the string has been split at each match:
1 | import re |
You can control the number of occurrences by specifying the maxsplit
parameter:
1 | import re |
The sub() Function
The sub() function replaces the matches with the text of your choice:
1 | import re |
You can control the number of replacements by specifying the count
parameter:
1 | import re |
Backreference
A backreference in regular expressions is a way to match the same text that was previously matched by a capturing group. In regular expressions, capturing groups are defined using parentheses, and are used to extract a specific part of the input string that matches the pattern. A backreference is defined using the syntax “\n”, where “n” is the number of the capturing group that it references. For example, if the regular expression pattern is “(\w+)\s\1”, and the input string is “hello world hello”, the match will be “hello hello”. The first capturing group “(\w+)” matches the first occurrence of “hello”, and the backreference “\1” matches the same text again.
Example of adding :
to every word
1 | s = """OverallQual 0.573994 |
1 | OverallQual 0.573994 |
1 | s1 = re.sub(r"^", "- ", s, flags=re.MULTILINE) |
1 | - OverallQual 0.573994 |
1 | s2 = re.sub(r"\b([a-zA-Z]+)\b", r"\1:", s1, re.MULTILINE) |
1 | - OverallQual: 0.573994 |
How to do backreference in VSCode? Using $&
indead of \1
.
Match Object
A Match Object is an object containing information about the search and the result.
Note: If there is no match, the value None
will be returned, instead of the Match Object.
Do a search that will return a Match Object:
1 | import re |
The Match object has properties and methods used to retrieve information about the search, and the result:
.span()
returns a tuple containing the start-, and end positions of the match..string
returns the string passed into the function.group()
returns the part of the string where there was a match
Print the position (start- and end-position) of the first match occurrence.
The regular expression looks for any words that starts with an upper case “P”:
1 | import re |
Print the string passed into the function:
1 | import re |
Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case “P”:
1 | import re |
Note: If there is no match, the value None
will be returned, instead of the Match Object.
The match() function
match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a Match object, or None if no match was found.
1 | import re |
The finditer() function
finditer(pattern, string, flags=0)
Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a Match object.
Empty matches are included in the result.
The complie() function
2 way to use it.
1 | zipcode = re.compile(r'\d{5}') |
flags
- re.I re.IGNORECASE: ignore the uppercase and lowercase letter
- re.M re.MULTILINE: let ^ match the start of every row.
- re.S re.DOTALL: let . match all of the characters. By defult, . will ignore /n.
Method
Attribute of match object
.string
: reutrn the orginal string.re
: pattern object.pos
: start position of the string.endpos
: end position of the string.group(0)
: return the matched string.start()
: the first matched position.end()
: the end matched position.span()
: return (.start(), .end())
1 | import re |
Greedy matching vs. Optimal matching
1 | import re |
Why Python returns “Python” instead of “P”, “Py”, “Pyt”, “Pyth”, or “Pytho”?
By defult, Python returns the longest result which we called Greedy matching.
Try to output the shortest result:
1 | m = re.search("^P.*?", "Python") |
*?
: 0 or more occurances, optimal matching+?
: 1 or more occurances, optimal matching??
: 0 or one occurance, optimal matching{m, n}?
: from m to n occurances, optimal matching
Classic RegEX
1 | ^[A-Za-z]+$ # Returns a match where the string contains any word characters (characters from a to Z) |
Python PIP
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
What is a Package?
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Check if PIP is Installed
Navigate your command line to the location of Python’s script directory, and type the following:
Check PIP version:
1 | pip --version |
Install PIP
If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/
Download a Package
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python’s script directory, and type the following:
Download a package named “camelcase”:
1 | pip install camelcase |
Now you have downloaded and installed your first package!
Using a Package
Once the package is installed, it is ready to use.
Import camelcase
package into your project then use it.
1 | import camelcase |
Find Packages
Find more packages at https://pypi.org/.
Remove a Package
Use the uninstall command to remove a package:
Uninstall the package named “camelcase” and press y
:
1 | pip uninstall camelcase |
List Packages
Use the list
command to list all the packages installed on your system:
List installed packages:
1 | pip list |
Python Try Except
The try
block lets you test a block of code for errors.
The except
block lets you handle the error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try
statement:
The try
block will generate an exception, because x
is not defined:
1 | try: |
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
This statement will raise an error, because x
is not defined:
1 | print(x) |
Accessing Error Messages
1 | try: |
For example:
1 | try: |
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:
Print one message if the try block raises a NameError
and another for other errors:
1 | try: |
Else
You can use the else
keyword to define a block of code to be executed if no errors were raised:
1 | try: |
Finally
The finally
block, if specified, will be executed regardless if the try block raises an error or not.
1 | try: |
This can be useful to close objects and clean up resources:
1 | try: |
The program can continue, without leaving the file object open.
Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise
keyword.
Raise an error and stop the program if x is lower than 0:
1 | x = -1 |
The raise
keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
1 | x = "hello" |
Infinte program
An infinite WRONG program:
Notice the 14th line.
1 | def hexo(x): |
The RIGHT code
Notice the 14th line.
1 | def hexo(x): |
The full version (must contain exit option!)
1 | import os |
Python User Input
User Input
Python allows for user input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than Python 2.7.
Python 3.x uses the input()
method.
Python 2.7 uses the raw_input()
method.
The following example asks for the username, and when you entered the username, it gets printed on the screen:
Python 3.x
1 | username = input("Enter username:") |
Note: Python stops executing when it comes to the input()
function, and continues when the user has given some input.
Python Keywords
Keyword | Description |
---|---|
and | A logical operator |
as | To create an alias |
assert | For debugging |
break | To break out of a loop |
class | To define a class |
continue | To continue to the next iteration of a loop |
def | To define a function |
del | To delete an object |
elif | Used in conditional statements, same as else if |
else | Used in conditional statements |
except | Used with exceptions, what to do when an exception occurs |
False | Boolean value, result of comparison operations |
finally | Used with exceptions, a block of code that will be executed no matter if there is an exception or not |
for | To create a for loop |
from | To import specific parts of a module |
global | To declare a global variable |
if | To make a conditional statement |
import | To import a module |
in | To check if a value is present in a list, tuple, etc. |
is | To test if two variables are equal |
lambda | To create an anonymous function |
None | Represents a null value |
nonlocal | To declare a non-local variable |
not | A logical operator |
or | A logical operator |
pass | A null statement, a statement that will do nothing |
raise | To raise an exception |
return | To exit a function and return a value |
True | Boolean value, result of comparison operations |
try | To make a try...except statement |
while | To create a while loop |
with | Used to simplify exception handling |
yield | To end a function, returns a generator |
assert
Definition and Usage
The assert
keyword is used when debugging code.
The assert
keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.
You can write a message to be written if the code returns False, check the examples below.
1 | x = "hello" |
1 | x = "hello" |
Python Built in Functions
Function | Description |
---|---|
abs() | Returns the absolute value of a number |
all() | Returns True if all items in an iterable object are true |
any() | Returns True if any item in an iterable object is true |
ascii() | Returns a readable version of an object. Replaces none-ascii characters with escape character |
bin() | Returns the binary version of a number |
bool() | Returns the boolean value of the specified object |
bytearray() | Returns an array of bytes |
bytes() | Returns a bytes object |
callable() | Returns True if the specified object is callable, otherwise False |
chr() | Returns a character from the specified Unicode code. |
classmethod() | Converts a method into a class method |
compile() | Returns the specified source as an object, ready to be executed |
complex() | Returns a complex number |
delattr() | Deletes the specified attribute (property or method) from the specified object |
dict() | Returns a dictionary (Array) |
dir() | Returns a list of the specified object's properties and methods |
divmod() | Returns the quotient and the remainder when argument1 is divided by argument2 |
enumerate() | Takes a collection (e.g. a tuple) and returns it as an enumerate object |
eval() | Evaluates and executes an expression |
exec() | Executes the specified code (or object) |
filter() | Use a filter function to exclude items in an iterable object |
float() | Returns a floating point number |
format() | Formats a specified value |
frozenset() | Returns a frozenset object |
getattr() | Returns the value of the specified attribute (property or method) |
globals() | Returns the current global symbol table as a dictionary |
hasattr() | Returns True if the specified object has the specified attribute (property/method) |
hash() | Returns the hash value of a specified object |
help() | Executes the built-in help system |
hex() | Converts a number into a hexadecimal value |
id() | Returns the id of an object |
input() | Allowing user input |
int() | Returns an integer number |
isinstance() | Returns True if a specified object is an instance of a specified object |
issubclass() | Returns True if a specified class is a subclass of a specified object |
iter() | Returns an iterator object |
len() | Returns the length of an object |
list() | Returns a list |
locals() | Returns an updated dictionary of the current local symbol table |
map() | Returns the specified iterator with the specified function applied to each item |
max() | Returns the largest item in an iterable |
memoryview() | Returns a memory view object |
min() | Returns the smallest item in an iterable |
next() | Returns the next item in an iterable |
object() | Returns a new object |
oct() | Converts a number into an octal |
open() | Opens a file and returns a file object |
ord() | Convert an integer representing the Unicode of the specified character |
pow() | Returns the value of x to the power of y |
print() | Prints to the standard output device |
property() | Gets, sets, deletes a property |
range() | Returns a sequence of numbers, starting from 0 and increments by 1 (by default) |
repr() | Returns a readable version of an object |
reversed() | Returns a reversed iterator |
round() | Rounds a numbers |
set() | Returns a new set object |
setattr() | Sets an attribute (property/method) of an object |
slice() | Returns a slice object |
sorted() | Returns a sorted list |
@staticmethod() | Converts a method into a static method |
str() | Returns a string object |
sum() | Sums the items of an iterator |
super() | Returns an object that represents the parent class |
tuple() | Returns a tuple |
type() | Returns the type of an object |
vars() | Returns the __dict__ property of an object |
zip() | Returns an iterator, from two or more iterators |
enumerate()
Definition and Usage
The enumerate()
function takes a collection (e.g. a tuple) and returns it as an enumerate object.
The enumerate()
function adds a counter as the key of the enumerate object.
Syntax
1 | enumerate(iterable, start) |
Parameter Values
Parameter | Description |
---|---|
iterable | An iterable object |
start | A Number. Defining the start number of the enumerate object. Default 0 |
Example: Save each index and element from a enumerate object in a new list
1 | letters = ['a', 'b', 'c', 'd'] |
Example: Get each index and element from a enumerate object
1 | letters = ['a', 'b', 'c', 'd'] |
Example: Extract index and element from a enumerate object and calculate them
1 | l = [0, 1, 2, 3] |
Example: Specify a number as start index
1 | letters = ['a', 'b', 'c', 'd'] |
Example: Use enumerate
to modify the cast
list so that each element contains the name followed by the character’s corresponding height. For example, the first element of cast
should change from “Barney Stinson” to “Barney Stinson 72”.
1 | cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"] |
map()
Higher order functions fit into a domain of programming known as “functional” or “functional form” programming, centered around this idea of passing and returning functions as parameters and arguments. In class, you learned the command map
that is a fundamental example of higher order functions.
Let’s take a closer look at how map
works. At its core, map
applies a function to all items in an input list. It takes in a function as the first parameter and a series of inputs as the second parameter.
1 | map(function_to_apply, list_of_inputs) |
1 | help(map) |
A potentially easier way to think about map is to draw an equivalent with a list comprehension! Given the func
(function to apply) and inputs
(list of inputs), a map is similar to this:
1 | [func(x) for x in inputs] |
Keep in mind that the map
function actually returns a map object, not a list
. We need to convert this object to a list
by passing it into the list()
function.
Let’s do a Python Tutor example to understand how map works.
Open Python Tutor in a new tab.
This code should already be there:
1 | INCR = 2 |
So what’s happening here? In the first 3 lines, we’re defining a function inc
which increments an input x by a certain amount, INCR
.
Notice that INCR
is defined once in the Global frame. This is a nice review of how Python resolves references when there are both local and global variables. When the inc
method executes, python needs to find the value INCR
. Since the INCR
variable isn’t declared locally, within the inc
function, Python will look at the parent frame, the frame in which inc
was declared, for the value of INCR
. In this case, since the inc
function was declared in the Global frame, the global INC
variable value will be used.
The second function, mymap
, is an example of how map works in the form of a list comprehension! Notice that mymap
takes in a function as its first argument and a sequence as its second. Just like map, this list comprehension runs each element of seq through the fun method.
As you run through the program in Python Tutor, notice how the list comprehension in mymap
will repeatedly call the inc function. The functional anatomy of how map works is exactly encapsulated by the mymap
function.
We defined mymap(fun, seq)
function and inc(X)
. But how to use map
function to directly apply all of the elements to inc(x)
?
1 | INCR = 2 |
Also, you can use built-in function and apply all elements to the function.
For example, convert all int
in a list to str
.
1 | list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) |
filter()
The filter
keyword is similar in nature to map
with a very important distinction. In map
, the function we pass in is being applied to every item in our sequence. In filter
, the function we pass in filters the elements, only leaving the elements for which the function returns true. For example, if I wanted to remove all negative numbers from a list, I could use the filter
function to identify values that are greater than or equal to 0, and filter out the rest.
1 | help(filter) |
1 | def isPositive(number): |
You can also define a filter to grab the elements that satisfy more complex conditions:
1 | def isGreaterThan(numbers, condition): |
reduce()
Apply a function of two arguments cumulatively to the items of a sequence
or iterable, from left to right, so as to reduce the iterable to a single
value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates((((1+2)+3)+4)+5)
. If initial is present, it is placed before the items
of the iterable in the calculation, and serves as a default when the
iterable is empty.
1 | reduce(function, iterable[, initial]) -> value |
1 | from functools import reduce |
Let’s say I wanted to calculate the product of the square roots of a list of numbers. The non-reduce version of this code would look something along the lines of this:
1 | product = 1 |
Here’s the reduce version
1 | from functools import reduce |
initial=1
is required here, becuase we are calculating $\sqrt{4} \times \sqrt{9} \times \sqrt{16} \times \sqrt{25} \times \sqrt{36} = 720$.
If there is no initial=1
, we are in actual calculating $4 \times \sqrt{9} \times \sqrt{16} \times \sqrt{25} \times \sqrt{36} = 1440$
Therefore, the above version is as same as the no-initial version shown below:
1 | from functools import reduce |
Noitce we don’t have initial but have 1
as the 1st element in the list numbers
.
So the process of calculation is $1 \times \sqrt{4} \times \sqrt{9} \times \sqrt{16} \times \sqrt{25} \times \sqrt{36} = 720$.
Combine reduce and map
For example, convert str
to int
1 | from functools import reduce |
map(char2num, s)
first get all digit from DIGITS
, like [1, 2, 3, 4, 5, 6, 7, 8, 9]
.
The regular method without reduce
looks like this:
1 | l = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
OR:
1 | l = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
zip()
Definition and Usage
The zip()
function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
Syntax
1 | zip(iterator1, iterator2, iterator3 ...) |
Parameter Values
Parameter | Description |
---|---|
iterator1, iterator2, iterator3 ... | Iterator objects that will be joined together |
Examples
1 | a = ("John", "Charles", "Mike") |
1 | a = ("John", "Charles", "Mike") |
1 | l_1 = [0, 1, 2, 3] |
zip() source algorithm:
1 | list_1 = [0, 1] |