Python Basics
Python Basics
jean-claude.feltes@education.lu
1. Python installation
On Linux systems, Python 2.x is already installed.
To download Python for Windows and OSx, and for documentation see http://python.org/
It might be a good idea to install the Enthought distribution Canopy that contains already the very useful modules
Numpy, Scipy and Matplotlib:
https://www.enthought.com/downloads/
Display version:
>>>help()
Welcome to Python 2.7!
...
help>
Help commands:
modules:
available modules
keywords:
list of reserved Python keywords
quit:
leave help
To get help on a keyword, just enter it's name in help.
LTAM-FELJC
jean-claude.feltes@education.lu
Supported operators:
Operator
Example
Explication
25/5 = 5, remainder = 0
84/5 = 16, remainder = 4
+, *, /
add, substract,
multiply, divide
modulo
25 % 5 = 0
84 % 5 = 4
**
exponent
2**10 = 1024
//
floor division
84//5 = 16
In the first example, 35 and 6 are interpreted as integer numbers, so integer division is used and
the result is an integer.
This uncanny behavior has been abolished in Python 3, where 35/6 gives 5.833333333333333.
In Python 2.x, use floating point numbers (like 3.14, 3.0 etc....) to force floating point division!
Another workaround would be to import the Python 3 like division at the beginning:
>>> from
>>> 3/4
0.75
Builtin functions:
>>> hex(1024)
'0x400'
>>> bin(1024)
'0b10000000000'
Expressions:
>>> (20.0+4)/6
4
>>> (2+3)*5
25
LTAM-FELJC
jean-claude.feltes@education.lu
4. Using variables
To simplify calculations, values can be stored in variables, and and these can be used as in
normal mathematics.
>>> a=2.0
>>> b = 3.36
>>> a+b
5.359999999999999
>>> a-b
-1.3599999999999999
>>> a**2 + b**2
15.289599999999998
>>> a>b
False
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
5. Mathematical functions
Mathematical functions like square root, sine, cosine and constants like pi etc. are available in
Python. To use them it is necessary to import them from the math module:
>>> from math import *
>>> sqrt(2)
1.4142135623730951
Note:
There is more than one way to import functions from modules. Our simple method imports all functions available in
the math module. For more details see appendix.
LTAM-FELJC
jean-claude.feltes@education.lu
A good choice is also Geany, a small freeware editor with syntax colouring, from which you can directly start your
script.
Take care:
7. A simple program
This small program calculates the area of a circle:
from math import *
d = 10.0
A = pi * d**2 / 4
print "diameter =", d
print "area = ", A
# diameter
8. User input
In the above program the diameter is hard coded in the program.
If the program is started from IDLE or an editor like Geany, this is not really a problem, as it is
easy to edit the value if necessary.
In a bigger program this method is not very practical.
This little program in Python 2.7 asks the user for his name and greets him:
s = raw_input("What is your name?")
print "HELLO ", s
What is your name?Tom
HELLO Tom
LTAM-FELJC
jean-claude.feltes@education.lu
Take care:
The raw_input function gives back a string, that means a list of characters. If the input will be
used as a number, it must be converted.
a new object d is created. As we have given it a floating point value (10.0) the object is of type
floating point. If we had defined d = 10, d would have been an integer object.
In other programming languages, values are stored in variables. This is not exactly the same as an object, as an
object has "methods", that means functions that belong to the object.
For our beginning examples the difference is not important.
Description
Example
Integer
int
a=5
Float
float
b = 3.14
Complex
complex
Complex number
c = 3 + 5j
c= complex(3,5)
Character
chr
d = chr(65)
d = 'A'
d = "A"
String
str
Now we can modify our program to calculate the area of a circle, so we can input the diameter:
""" Calculate area of a circle"""
from math import *
d = float(raw_input("Diameter: "))
A = pi * d**2 / 4
print "Area = ", A
Diameter: 25
Area = 490.873852123
LTAM-FELJC
jean-claude.feltes@education.lu
Note:
The text at the beginning of the program is a description of what it does. It is a special comment
enclosed in triple quote marks that can spread over several lines.
Every program should have a short description of what it does.
0
1
2
3
.....
98
99
100
READY!
sqrt(i)
0.0
1.0
1.41421356237
1.73205080757
9.89949493661
9.94987437107
10.0
The syntax is :
while <condition> :
<....
block of statements
...>
The block of statements is executed as long as <condition> is True, in our example as long as i
<= 100.
Take care:
Don't forget to indent the block that should be executed inside the while loop!
The indentation can be any number of spaces ( 4 are standard ), but it must be consistent for the
whole block.
Avoid endless loops!
In the following example the loop runs infinitely, as the condition is always true:
i = 0
while i<= 5 :
print i
LTAM-FELJC
jean-claude.feltes@education.lu
True if x = 3
x!=5
x<5
x>5
x<=5
x>=5
Note:
i = i +1 can be written in a shorter and more "Pythonic" way as i += 1
It is possible to test more than one condition using the elif statement:
s = raw_input ("Input your name: ")
if s == "Tom":
print "Hello ", s
elif s == "Carmen":
print "I'm so glad to see you ", s
elif s == "Sonia":
print "I didn't expect you ",s
else :
print "Hello unknown"
Note the indentation and the ":" behind the if, elif and else statements!
LTAM-FELJC
jean-claude.feltes@education.lu
13. Tuples
In Python, variables can be grouped together under one name. There are different ways to do this,
and one is to use tuples.
Tuples make sense for small collections of data, e.g. for coordinates:
(x,y) = (5, 3)
coordinates = (x,y)
print coordinates
dimensions = (8, 5.0, 3.14)
print dimensions
print dimensions[0]
print dimensions[1]
print dimensions[2]
(5, 3)
(8, 5.0, 3.14)
8
5.0
3.14
Note:
The brackets may be omitted, so it doesn't matter if you write x, y or (x, y)
LTAM-FELJC
jean-claude.feltes@education.lu
The number of elements can be determined with the len (length) function:
a=[0,1,2]
print len(a)
3
The elements of a list can be accessed one by one using an index:
mylist
print
print
print
black
red
orange
# 0...10
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
r2 = range(5,16)
print r2
# 5...15
# [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
r3 = range(4,21,2)
print r3
# 4...20 step 2
# [4, 6, 8, 10, 12, 14, 16, 18, 20]
r4 = range(15, 4, -5)
print r4
# 15....5 step -5
# [15, 10, 5]
Take care:
A strange (and somewhat illogical) detail of the range function is that the end value is
excluded from the resulting list!
LTAM-FELJC
jean-claude.feltes@education.lu
10
""" for floating point numbers use linspace and logspace from numpy!"""
import numpy as np
r5 = np.linspace(0,2,9)
print r5
[ 0.
0.25
0.5
0.75
1.
1.25
1.5
1.75
2.
The next example gives 9 logarithmically spaced values between 100 = 102 and 1000 = 103:
r6 = np.logspace(2, 3, 9)
print r6
[
100.
421.69650343
133.35214322
562.34132519
177.827941
749.89420933
237.13737057
1000.
]
316.22776602
Sam
Pit
Misch
0.0
1.0
1.41421356237
1.73205080757
2.0
Notes:
Python's for loop is somewhat different of the for ... next loops of other programming languages. in
principle it can iterate through anything that can be cut into slices. So it can be used on lists of numbers, lists of text,
mixed lists, strings, tuples etc.
In Python the for ... next construction is often not to be missed, if we think in a "Pythonic" way.
Example: if we need to calculate a lot of values, it is not a good idea to use a for loop, as this is very time
consuming. It is better to use the Numpy module that provides array functions that can calculate a lot of values in
one bunch (see below).
LTAM-FELJC
jean-claude.feltes@education.lu
11
The list(enumerate (....)) function gives back a list of tuples cv that contain each an index (the
numbering) and the colour value as text. If we print this we see
[(0, 'black'), (1, 'brown'), (2, 'red'), (3, 'orange'), (4, 'yellow'), (5,
'green'), (6, 'blue'), (7, 'violet'), (8, 'grey'), (9, 'white')]
Now we iterate on this, so we get the different tuples one after the other.
From these tuples we print c[0], the index and c[1], the colour text, separated by a tab.
So as a result we get:
0
1
2
...
8
9
black
brown
red
grey
white
19. Functions
It is a good idea to put pieces of code that do a clearly defined task into separate blocks that are
called functions. Functions must be defined before they are used.
Once they are defined, they can be used like native Python statements.
A very simple example calculates area and perimeter of a rectangle:
# function definitions
def area(b, h):
""" calculate area of a rectangle"""
A = b * h
return A
def perimeter(b, h):
""" calulates perimeter of a rectangle"""
P = 2 * (b+h)
return P
LTAM-FELJC
jean-claude.feltes@education.lu
12
One good thing about functions is that they can be easily reused in another program.
Notes:
Functions that are used often can be placed in a separate file called a module. Once this module is imported
the functions can be used in the program.
LTAM-FELJC
jean-claude.feltes@education.lu
21. Diagrams
Once you have calculated the many function values, it would be nice to display them in a
diagram. This is very simple if you use Matplotlib, the standard Python plotting library.
Matplotlib can be found here: http://matplotlib.org/downloads
The following program calculates the values of a function and draws a diagram:
from numpy import linspace, sin, exp, pi
import matplotlib.pyplot as mp
13
LTAM-FELJC
jean-claude.feltes@education.lu
Notes:
There are two ways to use Matplotlib: a simple functional way that we have just used, and a more
complicated object oriented way, that allows for example to embed a diagram into a GUI.
14
LTAM-FELJC
jean-claude.feltes@education.lu
15
23. Appendix
Importing functions from a module
Three ways to import functions:
1.
the simplest way: import everything from a module
advantage: simple usage e.g. of math functions
disadvantage: risk of naming conflicts when a variable has the same name as a module function
from numpy import *
print sin(pi/4)
2.
import module under an alias name that is short enough to enhance code clarity
advantage: it is clear to see which function belongs to which module
import numpy as np
print np.sin(np.pi/4)
3.
import only the functions that are needed
advantage: simple usage e.g. of math functions
naming conflict possible, but less probable than with 1.
disadvantage: you must keep track of all the used functions and adapt the import statement if a
new function is used
from numpy import linspace, sin, exp, pi
print sin(pi/4)