Created to be general-purpose, high-level programming language.
A "fun to use" language, hence named after Monty Python’s Flying Circus
Combines "remarkable power with very clear syntax" and provides a large and comprehensive standard library
Multi-paradigm programming language permitting several styles:
Application domains: web development, database access,
desktop GUIs, education, scientific and numeric computing, network programming, game and 3D graphics
help()
, e.g. help(sum)
will tell you how to use the Python function called sum
A convenient option when using Python is to use ipython
It is a slightly changed interpreter, containing multiple tweaks and modifications to make your life easier.
help/ documentation:
?
behind a function is an alias for help()
, e.g.: sum?
is the same as help(sum)
.??
behind a function shows the source code of the functionipython notebook
in the terminal, this will:2 + 2
4
(50 - 5*6)/4
5
7/3
2.3333333333333335
7 // 2
3
Operator | Operation |
---|---|
+ | plus |
- | minus |
* | multiplication |
/ | division |
** | power (not ^ as in some other languages) |
% | moldulo (remainder of integer division) |
== | equal to (do not mix up with =) |
!= | not equal |
> | greater than |
< | smaller than |
>= | greater than or equal to |
<= | smaller than or equale to |
If you want more complex operations (e.g. sin
, sqrt
, log
), you’ll need to use math
or numpy
. More on that later.
The priority between operators is the same as you’d expect mathematically. From highest to lowest precedence:
Operator | Operation |
---|---|
() | Terms in backets |
** | Exponentiation |
+x, -x | Unary plus and minus |
*, /, % | Multiply, divide, modulo |
+, - | Addition and subtraction |
<=, <, >, >= | Comparison operators |
==, != | Equality operators |
not, or, and | Logical operators |
There are other operators that you will encounter later, check the Python Library Reference for the complete precedence table.
=
) is used to assign a value to a variable (again, be careful to not confuse with testing for equality ==
)width = 20
pi = 3.14
message = 'I have a bad feeling about this'
A value can be assigned to several variables simultaneously:
x = y = z = 20
x
20
y
20
z
20
Variables must be “defined” (assigned a value) before they can be used, or an error will occur:
n
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-fe13119fb084> in <module>() ----> 1 n NameError: name 'n' is not defined
Variables are manipulated and combined with operators, forming “expressions”.
width = 20
height = 5
width * height
100
More complex operations are provided by functions. For example, the absolute value of a number:
abs(-3)
3
abs()
is an example of a function.abs
”), followed by parentheses. They can take some input (here a number), do something with them and create some output (here it returns the absolute value of the number).help(abs)
or abs?
to see what any function does exactly.abs()
function!)Lets write a very simple function to calculate the area of a rectangle given as: $Area = width * height$
def area(width, height):
'''Calculates the area of a rectangle'''
return width * height
# Let's use the function!
area(10,5)
50
If you type something into python by mistake and python can’t understand then that’s a syntax error.
n = 50 - 5*6)/4
File "<ipython-input-3-af371d7d80f2>", line 1 n = 50 - 5*6)/4 ^ SyntaxError: invalid syntax
^
under the mistake.Sometimes the grammar of your code is right and python knows what it should do, but you’ve asked it to do something impossible. This is called a runtime error.
n = 0
1 / n
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-64-158600a3143e> in <module>() 1 n = 0 ----> 2 1 / n ZeroDivisionError: integer division or modulo by zero
even_number
to contain an even number, and the variable zero
to contain the number 0.even_number = 57
sample_size = '20'
Errors in code are called bugs, and getting rid of them is called debugging. We will teach you how to debug throughout the course.
Variables in Python are “typed”. Every variable has a given type, which you can check by writing type(varname)
.
a = 10
b = 20.0
c = "It's just a flesh wound!"
type(a)
int
type(b)
float
type(c)
str
Directly combining variables of different types usually creates a TypeError
. Python can automatically convert some of them, e.g. int
to float
.
(Python is dynamically strongly typed)
a / b
0.5
a + c
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-71-ca57d551b7f3> in <module>() ----> 1 a + c TypeError: unsupported operand type(s) for +: 'int' and 'str'
import math
Functions of imported modules can be accessed with a .
, such as:
math.sqrt(3)
1.7320508075688772
You can import specific definitions from a module, e.g.:
from math import sqrt
sqrt(5)
2.23606797749979
You can also import all the definitions from a specific module, e.g.:
from math import *
This way is, however, disencouraged because it clutters your namespace (an exception might be build-in modules, like math). If two modules that you import have a function that has the same name, you cannot be sure which function you are calling, nor can readers of your code! As an example:
help(sqrt)
Help on built-in function sqrt in module math: sqrt(...) sqrt(x) Return the square root of x.
If we import the numpy
package which comes with a sqrt()
function as well, we overwrite the old definition:
from numpy import *
sqrt?
If you do not want to write out module names to access their functions, you can import an entire module by importing it with an alias. A better way of importing the numpy
module is:
import numpy as np
from math import *
sqrt?
np.sqrt?
Write formulae to convert:
celsius = 37
fahrenheit = celsius * (9/5) + 32
fahrenheit
98.60000000000001
lb = 77.161
kg = lb / 2.2046
kg
35.0
But what if we wanted to calculate fahreheit or kilograms with different values? We would have to change the values by hand every time. Instead we can write functions for the conversion:
def celsius_to_fahrenheit(celsius):
'''Converts celsius to fahrenheit'''
return celsius * (9.0/5) + 32
celsius_to_fahrenheit(38)
100.4
def pound_to_kilogram(lb):
'''Converts pounds to kilogram'''
return lb / 2.2046
pound_to_kilogram(10)
4.535970244035199
"\ "
"doesn\'t"
"doesn't"
certain characters are "invisible", e.g. use "\n"
to indicate the end of a line
The print
statement produces a more readable output for strings, e.g.
hello = "This is a rather long string containing\n several lines of text just as you would do in C. \n Whitespace at beginning of the line is significant."
print hello
This is a rather long string containing several lines of text just as you would do in C. Whitespace at beginning of the line is significant.
a = "dorota"
len(a)
6
b = "dorota "
len(b)
7
b + a
'dorota dorota'
word = 'Help'
word[1]
'e'
word[0:2]
'He'
word[-2]
'l'
Omitting a slice index means "start from beginning" or "end with (inlcuding) the last index":
word[-2:]
'lp'
word[:-2]
'He'
Python strings cannot be changed - assigning to an indexed position in the string results in an error:
word[0] = 'x'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-59-d89b9f9f38d7> in <module>() ----> 1 word[0] = 'x' TypeError: 'str' object does not support item assignment
list1 = ["first", "second", "third"]
list2 = [1, 2, 3]
list3 = ["pi", 3.1415926, "answer", 42]
emptyList = []