All content here is under a Creative Commons Attribution CC-BY 4.0 and all source code is released under a BSD-2 clause license.
Please reuse, remix, revise, and reshare this content in any way, keeping this notice.
This tutorial covers several topics that are important to the beginning Python user, especially if you are coming from using another programming language.
print(...)
function sends output to the screen. It is useful for debugging.print(...)
function can use 'strings' or "strings", in other words with single or double quotes.Print the following text to the screen:
Hi, my name is _____
Now try this:
The Python language was created by Guido van Rossum in the 1980's when he worked at the Centrum Wiskunde & Informatica in Amsterdam. Yes, he's from the Netherlands, but has moved to the US and worked for Google, but now at Dropbox.
You can verify the above by typing just the following two commands separately in Python:
credits
copyright
print('Hi, my name is Kevin.')
Hi, my name is Kevin.
long_string = """If you really want to write paragraphs,
and paragraphs of text, you do it with the triple quotes. Try it"""
print(long_string)
long_string
will be printed. Does Python put a line break where you expect it?
You can also create longer strings in Python using the bracket construction. Try this:
print('Here is my first line.',
'Then the second.',
'And finally a third.',
'But did you expect that?')
The reason for this is stylistic. Python, unlike other languages, has some recommended rules, which we will introduce throughout these modules. One of these rules is that you don't exceed 79 characters per line. It helps to keep your code width narrow: you can then put two or three code files side-by-side on a widescreen monitor.
Python also has escape characters. Discover it:
print('\')
print('\\')
The "\" on its own is an escape character. Google that term. What are the escape characters for:
print('The files are in C:\Data\dirnew\excel')
.print('The files are in C:\temp\newdir\excel')
.Why does it create such an unexpected mess?
There are two different ways to quickly fix the code to show what is intended. Try using escape characters first; we will show a more efficient way later.
We already saw above how a variable was created: long_string = """ .... """
.
You've done this plenty of times in other programming languages; almost always with an "=". We prefer to refer to "=" as the "assignment" operator; not "equals".
What goes on the left hand side of the assignment must be a 'valid variable name'.
Which of the following are valid variables, or valid ways to create variables in Python?
my_integer = 3.1428571
_my_float = 3.1428571 # variables like this have a special use in Python
__my_float__ = 3.1428571 # variables like this have a special use in Python
€value = 42.95
cost_in_€ = 42.95
cost_in_dollars = 42.95
42.95 = cost_in_dollars
dollar.price = 42.95
favourite#tag = '#like4like'
favourite_hashtag = '#일상'
x = y = z = 1
a, b, c = 1, 2, 3 # tuple assignment
a, b, c = (1, 2, 3)
i, f, s = 42, 12.94, 'spam'
from = 'my lover'
raise = 'your glass'
pass = 'you shall not'
fail = 'you will not'
True = 'not False'
pay day = 'Thursday'
NA = 'not applicable' # for R users
a = 42; # for MATLAB users: semi-colons are never required
A = 13 # like most languages, Python is also case-sensitive
What's the most interesting idea/concept you learned from this?
In the software editor you are using, is there a space where you can see the variable's current value? [This is called the Watch window in most graphical editors]
Each variable you create has a type
, which is automatically detected based on what is on the right hand side of the "=" sign. This is similar to MATLAB, but very different from C++ where you require this type of code:
int a, b; // first declare your variables
float result;
a = 5; // then you get to use them
b = 2;
result = a / b; // you will get an unexpected value if you had defined "result" as "int"
In Python you have dynamic typing, where you simply write:
a, b = 5, 2
result = a / b
and Python figures out the most appropriate type from the context.
Run those 2 lines of Python code. Then add this below. What is the output you see?
type(a)
type(result)
Each variable always has a type. Usually you know what the type is, because you created the variable yourself at some point.
But on occasion you use someone else's code and you get back an answer that you don't know the type of. Then it is useful to check it with the type(...)
function.
Try these lines in Python:
type(99)
type(99.)
type(9E9)
type('It\'s raining cats and dogs today!') # How can you rewrite this line better?
type(r'Brexit will cost you £8E8. Thank you.')
type(['this', 'is', 'a', 'vector', 'of', 7, 'values'])
type([])
type(4 > 5)
type(True)
type(False)
type(None)
type({'this': 'is what is called a', 'dictionary': 'variable!'})
type(('this', 'is', 'called', 'a', 'tuple'))
type(())
type(None)
type(print) # anything that can be assigned to a variable name can be 'type checked'
You can convert most variables to a string, as follows: str(...)
Try these conversions to make sure you get what you expect:
str(45)
type(str(45))
str(92.5)
str(None)
str(print)
The next step is to perform some calculations with the variables.
The standard expressions exist in Python:
Operation | Symbol |
---|---|
Addition | + |
Subtraction | - |
Multiplication | * |
Division | / |
Power of | ** |
Modulo | % |
Please note: "power of" is not with the ^ operator, and can mislead you. Try this:
print(2 ^ 4)
print(2**4)
If you are not familiar with the modulo operator, you can use it as follows: if you have a variable x
and you want to check if it is exactly divisible by, for example, a number 5, then you can check if the modulus, the remainder, is zero.
x % 5
7 % 5
evaluates to 2, since there's a remainder of 2 when 7 is divided by 510 % 5
evaluates to 0, since there's no remainder after 10 is divided by 5Given the above, use Python as a calculator to find the values of these expressions:
If a = 5
and b = 9
a / b
a * b
The distance $d$ travelled by an object falling for time $t$, given in seconds, is $$d=\frac {1}{2}gt^{2}$$ where $g$ is the gravitational constant = $9.8\, \text{m.s}^{-2}$. Calculate the distance that you will travel in free-fall gravity in 10 seconds:
t = ____ # seconds
d = ____ # meters
print('The distance fallen is ' + str(d) + ' meters.')
Try it now the other way around: the time taken for an object to fall is: $$ t= \sqrt {\frac {2d}{g}}$$
We will introduce the sqrt
function in the next section, but you can also calculate square root using a power of 0.5, as in $\sqrt{x} = x^{0.5}$.
Using that knowledge, how long will it take for an object to fall from the top of the building you are currently in:
# Creates a string value in variable 'd'. Verify that it is a string type.
d = input('The height of the building, in meters, which I am currently in is: ')
d = float(d) # convert the string variable to a floating point value
t = ____ # seconds
# You might also want to investigate the "round" function at this point
# to improve the output for variable t.
print('The time for an object to fall from a building',
'of ' + str(d) + ' meters tall is ' + str(t) + \
' seconds.')
You wish to automate your workflow to write a standardized statistical report. It should appear as follows on the screen:
There were 4 outliers detected in the data set using Grubbs' test at the 99% confidence level. These outliers will not be used in the subsequent calculations. The regression trend of 45.9 mg/day was detected for this product, with a p-value of 0.00341. This indicates that there is an important rising trend over time.
The 5 pieces in bold should be replaced with variables, so the above paragraph can be automatically written in the future with different variable values.
Write the Python code, creating the 5 variables. Print your paragraph of text to the screen. The last variable can either be 'rising' or 'falling'. (In the next class we will see how you can use an if-else statement to write 'rising'
or 'falling'
depending on the sign of the regression slope.
Python, like other languages, has the order of operations rules (same as the PEMDAS rules you might have learned in school):
So what is the result of these statements?
a = 1 + 3 ** 2 * 4 / 2
b = 1 + 3 ** (2 * 4) / 2
c = (1 + 3) ** 2 * 4 / 2
While it is good to know these rules, the general advice is to always use brackets to clearly show your actual intention.
Never leave the reader of your code guessing: someone will have to maintain your code after you; including yourself, a few years later 😉
Write code for the following:
Divide the sum of a and b by the product of c and d, and store the result in x.
The above operators return results which are either int
or float
.
There are another set of operators which return *bool*ean values: True
or False
. We will use these frequently when we make decisions in our code. For example:
if __<condition> __ then __<action>__
We cover if-statements in the next module.
But for now, try out these <condition>
statements:
3 < 5
5 < 3
4 <= 4
4 <= 9.2
5 == 5
5. == 5 # float on the left, and int on the right. Does it matter?
5. != 5 # does that make sense?
True != False
False < True
Related to these operators are some others, which you can use to combine up: and
and not
and or
Try these out. What do you get in each case?
True and not False
True and not(False)
True and True
not(False) or False
In the quadratic equation $$ax^2 + bx + c=0$$ the short-cut solution is given by $$ x= -\frac{b}{2a}$$ but only if $b^2 - 4ac=0$ and $a \neq 0$.
Verify if you can use this short-cut solution for these combinations:
a=3, b=-1, c=2 # use tuple-assignment to create these 3 variables in 1 line of code
a=0, b=-1, c=2
a=3, b=6, c=3
Write the single line of Python code that will return True
if you can use the shortcut, or False
if you cannot.
You will certainly need to calculate logs, exponentials, square roots, or require the value of $e$ or $\pi$ at some point.
In this last section we get a bit ahead, and load a Python library to provide this for us. Libraries - we will see later - are a collection of functions and variables that pre-package useful tools. Libraries can be large collections of code, and are for special purposes, so they are not loaded automatically when you launch Python.
In MATLAB you can think of Toolboxes as being equivalent; in R you have Packages; in C++ and Java you also use the word Library for the equivalent concept.
In Python, there are several libraries that come standard, and one is the math
library. Use the import
command to load the library. The math
library can be used as follows:
import math
radius = 3 # cm
area_of_circle = math.pi * radius**2
print('The area of the circle is ' + str(area_of_circle))
Now that you know how to use the math
library, it is worth searching what else is in it:
All built-in Python libraries are documented in the same way. Searching this way usually brings up the link near the top. Make sure you look at the documentation for Python version 3.x.
Now that you have the documentation ready, use functions from that library to calculate:
a = 3.7
b = 3.7
c = -2.9
d = 100
e = 100
math
library to calculate this!]<put your code here>
print('The true value of 9! is ' + ___ + ', while the Stirling approximation is ' + ___)
g
= $2\pi$ radians is indeed 1.0where the time $t$ is in years.
# IGNORE this. Execute this cell to load the notebook's style sheet.
from IPython.core.display import HTML
css_file = './images/style.css'
HTML(open(css_file, "r").read())