Python Introduction (Basics)#
Note
A recording of this can be found here.
Simple Variables#
Types#
We use Python’s build-in type() function to get the type of an object.
Integers#
17 + 25
42
type(17 + 25)
int
Floats#
17.0 + 25.0
42.0
type(17.0 + 25.0)
float
type(17 + 25.0)
float
type(17 / 25)
float
Complex#
17 + 42j
(17+42j)
type(17 + 42j)
complex
Assignments#
When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable. Until the value is changed or the variable deleted, the character x behaves like the value 1.
a = 17 # assign an integer number
print( type(a) )
<class 'int'>
b = 25. # assign a float number
print( type(b) )
<class 'float'>
c = 17 + 25j # assign a complex number
print( type(c) )
<class 'complex'>
print( c.real ) # access real
print( c.imag ) # and imaginary part of a complex number
17.0
25.0
Warning
Variable names are case sensitive!
d = 17
D = 25
print( d + D )
42
Explicit Conversions#
e = int(17.0)
print( type(e) )
<class 'int'>
f = float(17)
print(f)
17.0
g = complex(17)
print(g)
(17+0j)
A variable is more like a container to store the data in the computer’s memory, the name of the variable tells the computer where to find this value in the memory. For now, it is sufficient to know that the notebook has its own memory space to store all the variables in the notebook. As a result of the previous example, you will see the variable “x” and “y” in the memory. You can view a list of all the variables in the notebook using the magic command %whos.
%whos
Variable Type Data/Info
-------------------------------
D int 25
a int 17
b float 25.0
c complex (17+25j)
d int 17
e int 17
f float 17.0
g complex (17+0j)
Multi-variable Assignments#
a, b, c = 17, 25.0, 17+25j
print( "a = ", a )
print( "b = ", b )
print( "c = ", c )
a = 17
b = 25.0
c = (17+25j)
a = b = c = 17
print( "a = ", a )
print( "b = ", b )
print( "c = ", c )
a = 17
b = 17
c = 17
Assignment Operators#
a = 17
print("a =", a)
a += 25
print( a )
a *= 2
print( a )
a = 17
42
84
Lists & Dictionaries#
Let’s see a more versatile ordered sequential data structure in Python - Lists. The way to define it is to use a pair of brackets [ ], and the elements within it are separated by commas. A list could hold any type of data: numerical, or strings or other types. For example:
a = [1, 2, 3, 4]
print( "a = ", a )
a = [1, 2, 3, 4]
b = [1.2, 2, "hello", 3 + 4j]
print( "b = ", b )
b = [1.2, 2, 'hello', (3+4j)]
Can be accessed via “positions” / indices:
print( "a[0] = ", a[0] ) # NOTE: Counting starts at 0 !!!
print( "a[2] = ", a[2] )
print( "b[2] = ", b[2] )
a[0] = 1
a[2] = 3
b[2] = hello
Dictionaries are unordered sets of objects, which indexed by keys (like associative arrays), which could be a string, number or even tuple (but not list). A dictionary is a key-value pairs, and each key maps to a corresponding value. It is defined by using a pair of braces { }, while the elements are a list of comma separated key:value pairs (note the key:value pair is separated by the colon, with key at front and value at the end).
a = dict({
"ind1" : "val1",
"ind2" : "val2",
"ind3" : "val3",
})
print( "a =", a )
a = {'ind1': 'val1', 'ind2': 'val2', 'ind3': 'val3'}
print( "a[\"ind3\"] = ", a["ind3"] )
a["ind3"] = val3
These keys can be anything:
a = dict({
123 : "val1",
"hey" : 42.23423,
27j : 23.3 + 237j,
False : True,
})
print( "a = ", a )
a = {123: 'val1', 'hey': 42.23423, 27j: (23.3+237j), False: True}
print( "a[27j] = ", a[27j] )
print( "a[False] = ", a[False] )
a[27j] = (23.3+237j)
a[False] = True
Get all keys and all values of a dict:
print( "all keys of a: ", a.keys() )
print( "all values of a:", a.values() )
all keys of a: dict_keys([123, 'hey', 27j, False])
all values of a: dict_values(['val1', 42.23423, (23.3+237j), True])
Get length of lists / dicts:
a = [1, 2, 3, 4]
b = {'a':1, 'b':2, 'c':3} # short version without dict( ... )
print( "length of a:", len(a) )
print( "length of b:", len(b) )
length of a: 4
length of b: 3
Danger
Simple copies of lists and dicts behave “special” ! (see “Views & Copies” in Numpy Introduction as well)
a = [1, 2, 3] # define a simple list
b = a # and a copy of it
print( "a:", a)
print( "b:", b)
a: [1, 2, 3]
b: [1, 2, 3]
now edit first element of a
a[0] = 100
print( "a:", a)
print( "b:", b)
a: [100, 2, 3]
b: [100, 2, 3]
… although we edited \(a\) only, \(b\) is changed as well!
Hint
USE THE COPY METHOD INSTEAD!
a = [1, 2, 3]
b = a.copy()
a[0] = 100
print( "a:", a)
print( "b:", b)
a: [100, 2, 3]
b: [1, 2, 3]
Membership operators of lists and dicts#
a = [1, 2, 3, 4]
b = {'a':1, 'b':2, 'c':3} # short version without dict( ... )
print( "Is 4 in a?", 4 in a )
Is 4 in a? True
print( "Is 4 in b?", 4 in b.values() )
Is 4 in b? False
Control Statements#
if / else / elseif:#
Warning
Note the indentation!
a = 17
b = 25
if(a < b):
print("a is greater than b")
a is greater than b
User-input example#
pi = 3.14159265359
piUser = 3.14159
if( abs(piUser - pi) < 0.001 ):
print(" Very good guess!")
elif( abs(piUser - pi) < 0.01 ):
print(" Yeah, that's about right ...")
else:
print(" Really? I don't think so!")
Very good guess!
For Loops#
Most simple example using Python’s range() function:
for a in range(5):
print(a)
0
1
2
3
4
for a in range(0, 5):
print(a)
0
1
2
3
4
for a in range(1, 5):
print(a)
1
2
3
4
for a in range(1, 5, 2):
print(a)
1
3
But we can also iterat through lists:
b = [0, 2, 4.4, 6, 8]
for a in b:
print(a)
0
2
4.4
6
8
cityList = ["Nijmegen", "Utrecht", "Amsterdam"]
for city in cityList:
print(city)
Nijmegen
Utrecht
Amsterdam
And we can also iterate through a dicts:
b = {"a":0, "b":2, "c":4, "d":6, "e":8}
for index, value in b.items():
print(index, ":", value)
a
: 0
b : 2
c : 4
d : 6
e : 8
While Loops#
Simple example:
a = 0
while(a < 5): # ... it does not stop as long as this condition is False
print(a)
a += 1
0
1
2
3
4
Defining Functions#
Let’s define an own function – with a single argument:
def myFunction(name):
print('Hi '+name+', nice to "meet" you!')
myFunction('Malte')
#myFunction('Mr. Roesner')
Hi Malte, nice to "meet" you!
Define a function – with a single argument and a single return value:
def mySquare(x):
return x**2.0
b = mySquare(42)
print( b )
1764.0
def myCube(x):
return x**3.0
b = myCube(42)
print( b )
74088.0
Define a function – with a two arguments and a single return value:
def myProduct(x, y):
return x * y
b = myProduct(4, 3)
print( b )
12
Define a function – with a two arguments and two return values:
def myAddSub(x, y):
return x+y, x-y
b = myAddSub(4, 2)
print( b )
(6, 2)
b, c = myAddSub(4, 2)
print( b )
print( c )
6
2
Note
The return “value” can also be a function!
def myFunc(n):
if(n == 2):
return mySquare # returns mySquare() function!
if(n == 3):
return myCube # returns myCube() function!
squareFunc = myFunc(2)
cubeFunc = myFunc(3)
print( squareFunc(12) )
print( cubeFunc(3) )
144.0
27.0
Importing Modules#
Import and use the math module:
import math
print( math.sqrt(9) )
3.0
Let’s give the imported module a name:
import math as m
print( m.sqrt(42) )
6.48074069840786
Sometimes we want to important only a single function from a module:
from math import sqrt
print( sqrt(42) )
6.48074069840786
Error and Exception Handling#
import math
print( math.sqrt(-42) )
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[55], line 2
1 import math
----> 2 print( math.sqrt(-42) )
ValueError: expected a nonnegative input, got -42.0
To catch errors and stop the program smoothly, we can use the try-except statements:
import sys
import math
try:
print( math.sqrt(-42) )
except:
print("Oh boy, we have an unexpected error:", sys.exc_info()[0])
Oh boy, we have an unexpected error: <class 'ValueError'>
Or use the complex-math (cmath) module for that …
import cmath
print( cmath.sqrt(-42) )
6.48074069840786j
Other Practical Modules#
Numpy: Fast numerical arrays for Python
Scipy: Extensive scientific library for such tasks as linear algebra, Fourier transforms, random number generation and optimization (least squares fitting for example)
Matplotlib: 2d and 3d plotting
See Also#
https://scipy-lectures.org/intro/language/python_language.html
stackoverflow, news groups, mailing lists, etc.
Books by Mark Lutz:
Learning Python, O’Reilly Media, 2013
Programming Python, O’Reilly Media, 2010