2.4. Lecture 3: Python 1¶
Before this class you should:
Read Think Python:
Preface;
Chapter 1: The way of the program;
Chapter 2: Variables, expressions and statements; and
Chapter 3: Functions
Before next class you should:
Read Think Python:
Chapter 5: Conditionals and recursion;
Chapter 6: Fruitful functions; and
Chapter 7: Iteration
Note Taker: Ricardo Murray
Today’s Class:
Introduction to virtual lab resource and Jupyter Notebooks
Introduction to Python3 and Jupyter Basics
2.4.1. Introduction¶
“Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to combine remarkable power with very clear syntax, and its standard library is large and comprehensive. Its use of indentation for block delimiters is unique among popular programming languages.” – Wikipedia
Some features of Python:
Interpreted Language - the code is executed line by line at runtime allowing for dynamic and interative development without the need for sepearte compiliation setup.
Strict Syntax - emphasizes readability and clarity, utilizing indentations, and whitesapce to delineate code blocks.
Indentation - in a unique way utilises identation to identify codeblocks.
“Batteries Included” - comes with a standard library of extensive modules and packages.
Dynamic types - allowing variables to change types during runtime. No need for explicit type definitions.
Mixes, object-oreinted, and functional programming - integrates element sof object oriented and functional programming paradigms.
The “IPython” interactive shell is recommended for any kind of interactive code! For this class we use the Jupyter Notebook in the JupyterLab environment.
2.4.2. JupyterLab¶
We learnt the steps to enter the virtual lab through the link found on CourseLink, course outline page Course website. To access the virtual lab, you must be on-campus or connected to the VPN.
There are two main folders of concern in the virtual:
- public - here you find useful class materials and the .rst files for our
class website. You can also find today’s lecture material under the notebooks folder.
- work - students can use this folder to create and store their own python
projects such as their labs or exercise problems. Simple hit the blue plus sign to create a ‘new launcher’, then create a new python notebook to begin work. PLEASE END SERVER, WHEN NOT USING.
Jupyter Basics
Key Concepts:
Notebooks are divided into cells. Some cells are “Markdown” cells containing formatted text. Other cells contain regular Python code which can be run.
To execute a cell, click on it and hit
Shift + Enter
. Its output prints below.To add a new cell hit the
+
button. Pressa
to add a new cell above orb
to add a new cell below.New cells are default to code type. Hit
m
to change cell to a Mardown cell.Edit mode is enabled by pressing
Enter
on a cell. Now you can type in a cell.Command mode is enabled by hitting
Esc
or clicking outside a cell. There are some keyboard shortcuts available in this mode. For exampleCtrl(Cmd) + Shift + C
to open a command palette.
2.4.3. Coding in Python¶
All in class examples are accessible on the Python 1a and Python 1b Jupyter Noteboks on the virtual lab. This section will then simply higlight the key talking points presented in lecture.
2.4.3.1. The first program¶
Initial python program, it displays the string, ‘Hello, world!’ as shown below:
print('Hello, world!') # prints text
2.4.3.2. Arithmetic operators¶
Python provides operators, in the form of the following operators:
40 + 2 # adition
43 - 1 # subtraction
6 * 7 # multiplicattion
84 / 2 # float division - produces a floating point value
20 % 5 # modulus operator
6**2 # exponent
6 ^ 2 # XOR operator
By default, division ‘/’ in python produces a floating point value. Instead the ‘//’ operator can be used to produce an integer quotient.
2.4.3.3. Values and types¶
A value is a fundamental piece of data that a program works with like a number or letter. They include different types of data or data types, some of which include: 5 is an integers, 5.0 is a floating point, 5,00,00 is a tuple and ‘Hello, World!’ is a string.
If you are not sure what type a value has, use type(value)
and the intepreter will
tell you.
2.4.3.4. Assignment statements¶
An assignment statement creates a new variable and gives it a value. In Python, a variable is a named storage location that holds a value as shown in the bellow assignment statement:
age = 84
name = 'Casper'
It is important to note that variable names should be choosen with some meaningfulness, based on its purpose in a program. Varaible names can be as long and one would like. They can contain numbers and letters but cannot begin with numbers.
The underscore character, _, can also be used in variable names, often appearring in
between words like your_car
.
If a chosen variable name is illegal, the compiler will return a syntax error. Any use of Python keywords or special symbols in a variable name is illegal.
class = 'Modeling Complex Systems'
This returns a syntax error because ‘class’ is a keyword. To find the Python keywords use the following command:
help('keywords')
2.4.3.5. Expressions and statements¶
An expression is a combination of combination of values, varibales, and operators that is evaluated by the interpreter and results in a single value. Expressions can be considered as basic building blocks for any computation in Python. They can be as simple as a single variable or as complex as a combination of functions.Example of expressions:
42
n
n / 2
A statement, on the other hand, is a line of code that performs some action. Statements are made up of expressions but are generally executable. Example of statements:
x = 24 #assignment statement
print(n) #display statement
2.4.3.6. Script mode¶
- When working in Python, there are two modes by which we can interact with the interpreter.
Interactive mode, this way you can interact directly with the interpreter. This is a good way to get started and can be used to test bits of code easliy. Interactive mode will interpret and return the value from expresiions.
Script mode is an alternative to interactive mode. You must first dave your code in a file called a script and then run the interpreter in script mode to execute the script. Python script are saved as
.py
. Script mode only will not display the result of an expression unless a statement is given which wraps some expression theprint()
function.
In JupyterLab Notebooks, the default mode is interactive. This make it a great place to run and test bits of code. To enter script mode on Jupyterlab one must use
%% script python
. For example:%% script python miles = 26.2 miles * 1.16
The result of this expression will not be displayed as we are in script mode (as indicated by the first line of code above).
2.4.3.7. Order of operations¶
In Python, expressions which contain more than one operator are evaluated based on the order of operation.
It follows the PEDMAS or BEDMAS rules from mathematics, i.e. in order of precedence: Parentheses-> exponentiation->multiplication or division->addition or subtraction
2.4.3.8. String operations¶
Mathematical operation cannot be performed on strings, i.e.you cannot add, subtract, multiply, or divide one string with a another.
The +
operator however, performs string concatenation.
first = 'Call' second = 'of' third = 'Duty' first + second + third #returns 'CallofDuty' string
Similary one can use the .append()
function to concatonate strings. More on this later.
The *
operator performs repition on strings. For example:
'Ha' * 3 #returns 'HaHaHa'
Note: string concatenation varies from addition because of additions commutative property i.e. for any two numbers ‘a’ and ‘b’, ‘a + b’ is equal to ‘b + a’.
2.4.4. Function calls¶
Functions are reusable and self contained blocks of code that performs a specific task or set of tasks (more on this later).
Funtions can be called as seen earlier like:
type(42)
Where function “type()” returns the data type of 42 which is an integer. Function calls can be used to make code more succint. Calling an already defined function can reduce the complexity and length of ones code.
2.4.4.1. Math Functions¶
The math
module (file containing collection of functions) in Python provides most familiar
math functions. Before using the functions in this module we must us an import statement:
import math
#imports math module to enable use of math functions.
math #creates an object named math
The module object contains functions and variables defined in the math module. To access a function you must use dot notation which looks like:
decibels = 10 * math.log10(ratio)
# <module name> + dot + <function name>
See the Python 1b notebook on in the course repository for more examples on math
functions.
2.4.4.2. Composition¶
A useful feature in Python is the ability to compose expressions and functions within statements. You can also call functions within other functions know as nested function. For example:
x = math.sin(degrees / 360.0 * 2 * math.pi)
2.4.4.3. Adding new functions¶
The programmer can also create their own special functions know as function definition, which specifies the name of a new function and gives a sequnce of sttements.
For example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
Defining a fucntion creates a function object which has type function
and can be called within
other functions, for example:
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics() #function called and thus executed.
2.4.4.4. Parameters and arguments¶
Some functions require arguments, such as math.sin
or math.pow
. Inside the function, the argument is
assigned to a variable called parameters. Variables can also be used as arguments.
import math
x = math.sin(degrees / 360.0 * 2 * math.pi)
More examples of these are given in the Python 1b notebook in the coure repository.
2.4.4.5. Variables and parameters are local¶
Variables created inside of a function is known as local variables, i.e. it can only be called within the function.
2.4.4.6. Fruitful and void functions¶
Functions which return a result are known as fruitful functions such as the math functions which usually calculate some value which the function returns.
Functions which perform an action but do not return a value are known as void function.
2.4.3.9. Comments¶
As your program gets larger, it is good practice to add notes which help explain in natural langauge what the program is doing. These notes are refered to as comments and they begin with
#
symbol: