Dr Niall Madden
School of Mathematical and Statistical Sciences
University of Galway
These notebook include material written by Dr Tobias Rossmann
The Jupyter server is still not quite working. So, I've posted these notes to a public server: BINDER.
Try the link:
To get started, you can use web version, such as
Eventually, if you have a suitable computer, you should install it. I recommend the Anaconda distribution.
Primarily, we will use Jupyter notebooks. More about this later. But you can access at
We can do standard arithmetic, e.g., using
+, -, *, / for the usual arithmetic operations,
// for floor division,
% for the modulus (remainder) operation,
** for exponentiation. That is 2**3 means 23.
These are called binary operators, because they involve two operands (numbers, in this case).
{note}
Can you think of any operators that are not binary?
Python has several data types to represent and work with numerical values. The ones we are most interested in are
int.float.The type of a Python object can be determined with the type() function:
type(1234)
int
type(3.14159)
float
For more, see Section 1.3 of Think Python
When you add two ints, the result is an int. And when you add two float, the result is a float. But it is also possible to have expressions that combine both int and `float.
This is mixed arithmetic
We say int is narrower than float, because every int can be converted exactly to a float.
When needed, the “narrower” type is upgraded to the wider one.
Here int is narrower than float, which is narrower than complex.
print(3 + 4) # addition
print(3 - 4) # subtraction
print(3 * 4) # multiplication
print(3 / 4) # division
print(3 ** 4) # exponentiation
7 -1 12 0.75 81
type(3*4)
int
type(3/4)
float
print(3.0 + 4) # adding a float and an int gives a float
7.0
float(3)
3.0
Usually, operations on two numbers of the same type result in a third number of that same type.
Division of ints, however results in a float, if the corresponding fraction is not an integer.
If the integer quotient is required, Python provides floor division (//) as a separate operation.
The corresponding remainder can be computed with the modulus operator %.
print(17 // 3) # integer quotient
print(17 % 3) # the remainder: 17 mod 3
print(divmod(17, 3)) # quotient and remainder in one
5 2 (5, 2)
print((16) % 3) # 16 = 3*5 +1
print((-16)% 3) # -16 = -18 +2 = 3*(-6)+2
1 2
math Library¶Python comes with many additional modules that extend its basic functionality.
One fundamental module is the math library.
It needs to be imported before it can be used in a program.
Here we compute √2
import math
math.sqrt(2)
1.4142135623730951
math library contains many useful mathematical constants andadditional functions:
| Python | Mathematics | English |
|--|--|--|
| pi | π | an approximation of the number π |
| e | e | an approximation of Euler's number e |
| abs(x) | |x| | the absolute value of x
| sqrt(x) | √x | the square root of x |
| sin(x) | sin(x) | the sine of x |
| cos(x) | cos(x) | the cosine of x |
| tan(x) | tan(x) | ... |
| asin(x) | sin−1(x) | the inverse sine of x |
| acos(x) | cos−1(x) | ... |
| atan(x) | tan−1(x) | ... |
| log(x) | ln(x) | the natural (base e) logarithm of x |
| log10(x) | log10(x) | the base 10 logarithm of x |
| exp(x) | ex | the exponential of x |
| ceil(x) | ⌈x⌉ | the smallest integer ≥x |
| floor(x) | ⌊x⌋ | the largest integer ≤x |
print(math.pi, math.floor(math.pi))
can have and what operations it supports.
Python has three built-in data types for representing numerical values: int, float and complex.
floats are (only) approximations to real numbers.
ints can be arbitrarily large.
addition (+), subtraction (-), multiplication (*),
division (/), and exponentiation (**).
//)and remainder (%).
More functions: see the math library.
In some situations, Python automatically converts numbers from one data type
to another.
int, float, complex) functions can be used, too.print('Hello, how are you?') # Using single quotes
print("Hello, how are you?") # Using double quotes
print("I'm fine, thanks for asking") # note we use can put single quotes inside double
print('Excuse me: I said "hello"')
So what is going on here?
We'll learn that print is a function in Python, and the parentheses are used to indicate this, and also enclose the argument. Soon we will learn how to write our own functions.
The stuff between the quotes is called a string. The next section is all about strings.
The # symbols denote a comment. Python ignores everything on the rest of the line: the comments just provide information and context for the reader.
Any program that is not too boring has to store data and manipulate it.
The simplest way of storing data is to assign it a name, using the = symbol.
a = 12.34 # we use "=" for assignment, never equality
b = 1.04
c = a-b # Compute 12.34-1.04, and store the result in c
print(a,'-', b, '=', c )
a = -1234
print(a)
In that example, we would call a, b, and c VARIABLES, which just means that can take on any value we like, and that value can be changed at a later time.
We can also store strings as variables:
message = "This is my first string."
print(message)
type(message)
""" This is a comment too """
Variable names can be as long as you like. They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but (according to the textbook) it is conventional to use only lower case for variables names.
You also can't use certain reserved words in the language (more later on this).
Try to choose variable names that are meaningful (this leads to self-documenting code).
The underscore character, _, can appear in a name. It is often used in names with multiple words, such as your_name or airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error.
cs102_class_size = 58 # OK
2223_cs102_class_size = 58 # OK
Finished here on Wednesday</span
Most of the time, these classes are focused on the fundamentals of programming in Python, starting from scratch. A down-side of this, is that it takes some time before we get to the fun stuff.
So, once per week, I'll give a short piece of Python code with fun/silly/interesting results, but not explained in detail.
This week, we'll make a word-cloud of your holiday desinations. The code
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
df = pd.read_excel ("2223-CS102-CS103-where.xlsx", na_filter = False);
VacationList = " ".join(cat for cat in df.Vacation)
VacationCloud = WordCloud().generate(VacationList)
plt.imshow(VacationCloud), plt.show()
str (which is short for string).") or single quotes (')."double"
'single'
print("double", 'single')
type("double")
Text processing is an important feature of many programming languages: many types of data and problems a program can deal with are text-based.
We will now discuss strings and some operations they support. This will allow us to easily build powerful text-processing applications in Python.
The number of characters in a string is its length.
It can be obtained by calling the len function with the string as its argument.
len("python")
The individual characters making up a string
can be accessed through their position in the string, using
an index inside a pair of square brackets ([ ... ]).
message = "Hello, there!"
print("message[0]=", message[0]) # Count from zero!
print("message[1]=", message[1])
print("message[1]=", message[12]) # 13 characters, so last one is [0]
print("message[1]=", message[13]) # this one does not exist
A character is simply a string of length 1.
Indices begin with 0 and end at length-1.
Negative indices can be used: they count from the back of the string.
message[-1]
Square brackets can also be used to extract certain substrings of length bigger than 1 (so-called slices). Here two positional indices are needed: one marks the beginning and the other marks the end of the substring, separated by a colon (:).
message[0:5]
message[7:12]
Note how the substring starts at the first position and stops just short of the second position.
In this way, the difference (12−7) of the two indices is the length of the substring (5).
Negative indices can also be used for slicing.
If any of the indices is omitted, it defaults to the beginning (0) or to the end (−1) of the string.
message[:7] # if you omit the start index, it is treated as zero
message[7:] # if you omit the end index, it is treated as the end
message[:] # a copy of the complete string
Slices support a third argument, called step or stride.
message[::2]
Again, negative values are supported.
message[::-1]
Strings can be 'added' to each other and 'multiplied' by natural numbers (on either side).
+ operator can be used toglue two or more strings together into a new one.
"Hello " + "world!"
"'ello " * 3
There are many methods for string manipulations.
"ATCGACTGATCGATCGTACGAT".count("AT")
"ATCGACTGATCGATCGTACGAT".find("ACT")
"ATCGACTGATCGATCGTACGAT".lower()
"ATCGACTGATCGATCGTACGAT".replace("AT", "at")
"A Title".center(20)
"a little string".upper()
' '.join('spread')
string module contains further useful string manipulation operations.A Python program is traditionally composed of the characters in a fixed set of 128 symbols, called the ASCII code (from 1968!).
A modern extension of ASCII is Unicode.
The ASCII code is based on the symbols that are found on the original US keyboards.
Each character corresponds to an integer between 0 and 127.
32 48 0 64 @ 80 P 96 ` 112 p 33 ! 49 1 65 A 81 Q 97 a 113 q 34 " 50 2 66 B 82 R 98 b 114 r 35 # 51 3 67 C 83 S 99 c 115 s 36 $ 52 4 68 D 84 T 100 d 116 t 37 % 53 5 69 E 85 U 101 e 117 u 38 & 54 6 70 F 86 V 102 f 118 v 39 ' 55 7 71 G 87 W 103 g 119 w 40 ( 56 8 72 H 88 X 104 h 120 x
41 ) 57 9 73 I 89 Y 105 i 121 y
42 * 58 : 74 J 90 Z 106 j 122 z
43 + 59 ; 75 K 91 [ 107 k 123 {
44 , 60 < 76 L 92 \ 108 l 124 |
45 - 61 = 77 M 93 ] 109 m 125 }
46 . 62 > 78 N 94 ^ 110 n 126 ~
47 / 63 ? 79 O 95 _ 111 o 127 DEL
The Python functions ord ("ordinal") and chr ("character") convert between
a character and its numerical (ASCII) value:
ord returns the ASCII value of a character
chr returns the character for a given ASCII value
ord('A')
chr(65)
Strings are sequences of characters.
Characters are themselves strings of length 1.
String literals are enclosed in single (') or double (") quotes.
There are built-in operations for concatenation (+), repetition (*), indexing ([]), slicing ([:]) and length (len).
Internally, characters are represented by numerical codes. The functions ord and chr convert between the two representations.
String objects support many useful string manipulation functions.
Additional string methods are defined in modules such as the string module.
Python programs operate on values of objects with types such as int or str.
Values can be assigned to variables for later (re)use.
Literals are representations of fixed values.
Literals and variables can be combined using operators (e.g. + or *) and other ingredients (e.g. function calls) to form expressions.
# The value represented by the literal 1234 is assigned to the variable x
x = 1234
y = 5678 # val of literal 5678 is assigned to variable y
# By combining literals and variables, we may form expressions
5*x - y + 2
Types of values include integers as above, or strings:
'y' + "".join(x*17 for x in "eah") # We'll explain this next week!
FAO 1BGG1, here is a random DNA sequences:
import random
"".join("AGCT"[random.randint(0,3)] for _ in range(72))
These are examples of some of the types of objects that a Python program can deal with. Different types are stored in different digital formats but we won't worry about this here.
The fragments of Python code that describe the values (and that often look like mathematical formulae) are called expressions.
Expressions have values.
The simplest kind of an expression is a literal (like the number 17 or an explicit string "hello!"). The value of a literal is what you expect.
the sum of two numbers, or the sum of a product and a quotient, ...
The process of deriving a value from an expression is called evaluation
This is a major part of what the Python interpreter does!
(12 * 3) + (15 // 5)
3 * 13
Earlier we learned:
x = (12 * 3) + (15 // 5)
x
It is important to note that the value of the expression on the right is first calculated, and then the result stored in the variable on the left.
print('x=',x)
x = x + 1
print('x=',x)
Variable names are examples of things called identifier.
import) have a special meaning in Python and cannot be used as identifiers.textTexttExTThe complete list of keywords in Python is as follows.
import keyword
print(keyword.kwlist)
Or, in a more readable table:
| | | | |
|:-:|:-:|:-:|:-:|
|False|class|from|or|
|None|continue|global|pass|
|True|def|if|raise|yield|
|and|del|import|return|
|as|elif|in|try|
|assert|else|is|while|
| async | except|lambda|with|
| await | finally | nonlocal | yield|
|break| for | not |
We will encounter many (but not all) of these later on.
A program deals with values of different types.
Expressions are fragments of code that represent data values.
Literals are expressions that explicitly describe a specific value, e.g. "hello", or 3.1415.
Operators (like +) are used to combine expressions into larger expressions.
Values can be assigned to variables.
Each variable has a name consisting of letters, digits and underscores, but not starting with a digit and different from any keyword.
Variables can be part of expressions. Upon evaluation, their current values are substituted into the expression.
Over time, a variable can be assigned different values.
Project Jupyter exists to develop open-source software, open-standards, and services for interactive computing across dozens of programming languages.
Jupyter notebooks are interactive documents that combine Python code and text.
Modern (2015–) and actively developed.
Popular in several branches of science.
https://jupyter.nuigalway.ie
To access the server: go to https://jupyter.nuigalway.ie, enter your student ID, and choose any password. Make sure you remember it. We can change it later, but it is tedious.
You can also try Jupyter here: https://jupyter.org/try Warning. You need to save notebooks on your device if you want to reuse them later.
At each time, the notebook is either in edit mode or in command mode.
Some keyboard shortcuts:
Esc: switch to command mode
Enter: switch to edit mode (from command mode)
Shift-Enter: run cell, switch to command mode, selects cell below
More: use the Help menu!
Some keyboard shortcuts supported in command mode:
Enter switches to edit mode.
Shift-Enter runs the cell, then selects the cell below.
Up selects the cell above.
Down selects the cell below.