Professional Documents
Culture Documents
(EGR2313)
LECTURE week 2 : Python Basics
Amir A. Bature
aabature.ele@buk.edu.ng
Nabila Ahmad Rufa’i
narufai.ele@buk.edu.ng
Department of Electrical Engineering
Bayero University, Kano
2021
1
Week 2 Lecture:
Python Basics
1. Installation/IDE
2. Operations and Libraries
3. Strings
4. List
5. Dictionary
6. Numpy Library
2
INTRODUCTION TO PYTHON
o Python programming language is a high level language
that is useful for all kinds of scientific and engineering
tasks.
o It may also be used in web-based applications, data
analytics.
o You can also use it to Numerically solve science and
engineering problems that are difficult or even
impossible to solve analytically.
o It is similar to Matlab and IDL: all are used in scientific
and engineering applications.
o They also do not require compilers, as they are
interpreted languages.
o However, unlike Matlab and IDL, Python is free.
INSTALLING Python on your PC
o Visit www.anaconda.com and download the free
Python distribution package.
o Storage Requirement for Software: 457 MB
(Windows); 435 MB (MacOS); 529 MB (Linux).
5
Working with Python
o The default Canopy window consists of: the code editor,
the interactive Python pane (IPython) and the file
browser pane.
o Interactive Python pane (IPython): is the primary
means of interacting with Python. It is used to perform
tasks such as navigating computer file directories and
performing mathematical operations. With IPython,
programmers can run codes directly on the Python shell
without the need to create a new file (also known as a
script).
o The default input prompt of IPython is:
In [1]:
o Code editor: to write and edit Python programs (or
scripts).
o File browser pane: to navigate a computer’s file directory
system in order to view and retrieve files on the computer.
6
Navigation with IPython
The following magic commands are used to perform
various useful tasks in IPYTHON:
o cd ~ sets the computer to its home (default) directory.
o pwd returns the path of the current directory on the
computer
o cd .. moves the IPython shell up one directory in the
directory tree. For example:
o ls lists the names of the files and subdirectories in the
current directory.
o %run filename
o %hist lists the recent commands issued to the IPython
terminal.
o %edit opens a new empty file in the code editor
window.
7
CALCULATIONS WITH IPython
IPython shell can be used to form simple mathematical
operations.
Example 1:
In [1]: (20/4)*3
Out[1]: 15.0
Example 2:
In [2]: 4*3+7
Out[2]: 19
Example 3:
In [3]: 4*(3+7)
Out[3]: 40
Note the effect of parenthesis in Examples 2 and 3. In the
absence of parenthesis, multiplication would be performed
first before addition. The order of arithmetic operations are:
exponential, multiplication and division, addition and
subtraction from left to right.
8
CALCULATIONS WITH IPython
Mathematics Operations in Python
9
CALCULATIONS WITH IPython
Binary Operations in Python
10
Number types
3 basic number types: integers (plain and long), floating
point numbers and complex numbers:
❑Integers: zero, positive or negative whole numbers
without a fractional part, e.g. 0, -1000, 2459871, etc. They
may have binary, octal, and hexadecimal values. To
convert a number into an integer, the int command may
be used:
In [1]: int (60.5)
Out[1]: 60
❑Floating point numbers: are positive and negative real
numbers with a fractional part e.g. 123.4, 3.142, -5.75.
❑Complex numbers: are written in Python as a sum of a
real and imaginary part.
In [2]: (2+3j)*(-4+9j)
Out[2]: (-35+6j)
11
PYTHON LIBRARIES
Themost useful Python libraries for scientific
computing are:
o NumPy: useful for working with arrays. It has functions
for working in domains of linear algebra, Fourier
transform and matrices, amongst others.
SciPy: useful in performing various scientific and
mathematical operations including optimization, linear
algebra, integration, interpolation, special
functions, FFT, signal and image processing.
MatPlotLib: a plotting library in Python useful in
plotting 2-D and 3-D plots.
12
PYTHON LIBRARIES: numpy
o The array object in NumPy is called ndarray.
o The following lines of code describe how Numpy arrays
can be created and modified:
Input:
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1
array
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Change an element of the array
print(a) # Prints "[5, 2, 3]"
Output:
1 2 3
[5 2 3]
13
PYTHON LIBRARIES: numpy
o Some NumPy functions are captured in
the table below.
14
VARIABLES IN PYTHON
o A variable is a name that is used to store different
kinds of data.
For example:
In [1]: x = 27
o Note that the assignment variable works from
right to left. Therefore, the statement “27=x”
makes no sense in Python
o The statement, x = x+1 adds 1 to the current
value of x and assign the result to x. in the example
above, x is now stored as 28.
15
Reserved words
o Reserved words are specifically meant for special
purposes or functions.
o They therefore may not be used as variables
names.
o Reserved words in Python are listed in the table
below.
16
Comments
o # for single line comments
o multiple lines enclose comments with ‘‘‘ or “””
17
script files and programs
o IPython is useful for short lines of code.
o For longer codes that can be stored and
reused later, a script is usually employed.
o Scripts are written using Code Editor in the
Canopy window.
o After writing a script, the code is stored on a
computer with the extension: .py (which tells
the computer that it is a Python program).
Scripting example 1
19
Scripting example 1 continued
o Run the script by typing the following
command in IPython to see the result:
In [10]: run twoPointDistance.py
In [11]: dr
Out[11]: 34.48
20
Data Types:
1. Strings:
Strings are lists of characters
created by enclosing a sequence of characters within a pair of single or double
quotes; “ “ or ‘ ‘
In [1]: a = "My dog’s name is"
In [2]: b = "Bingo"
Strings can be concatenated using the “+” operator:
In [3]: c = a + " " + b
In [4]: c
Out[4]: "My dog’s name is Bingo"
Exercise:
In [5]: d = "927"
In [6]: e = 927
Try:
In [7]: d + e
21
Data Types:
2. Lists:
List contains of one or more elements in a single variable
are defined by a pair of square brackets
Individual elements are separated by commas
indexed by an ordered sequence of integers starting from zero
Examples:
In [1]: a = [0, 1, 1, 2, 3, 5, 8, 13]
In [2]: b = [5., "girl", 2+0j, "horse", 21]
a and b are lists.
access by a[index], where index starts with 0.
In [3]: b[0]
Out[3]: 5.0
The last element of this array is b[4], because b has 5 elements. The last element
can also be accessed as b[-1], no matter how many elements b has, and the next-
to-last element of the list is b[-2], etc. Try it out:
22
Data Types:
2. Lists:
Individual elements of lists can be changed. For example:
In [9]: b
Out[9]: [5.0, ’girl’, (2+0j), ’horse’, 21]
In [10]: b[0] = b[0]+2
In [11]: b[3] = 3.14159
In [12]: b
Out[12]: [7.0, ’girl’, (2+0j), 3.14159, 21]
Adding lists concatenates them, just as the “+” operator concatenates strings
In [16]: a + a
Out[16]: [0, 1, 1, 2, 3, 5, 8, 13, 0, 1, 1, 2, 3, 5, 8, 13]
Slicing lists
In [19]: b[1:4]
Out[19]: [’girls & boys’, (2+0j), 3.14159]
In [20]: b[3:5]
Out[20]: [3.14159, 21]
23
Data Types:
other useful slicing shortcuts:
In [21]: b[2:]
Out[21]: [(2+0j), 3.14159, 21]
In [22]: b[:3]
Out[22]: [10.0, ’girls & boys’, (2+0j)]
In [23]: b[:]
Out[23]: [10.0, ’girls & boys’, (2+0j), 3.14159, 21]
24
Data Types:
Tuples
tuples are lists that are immutable (meaning
elements cannot be changed)
enclosed in round parentheses ()
In [37]: c = (1, 1, 2, 3, 5, 8, 13)
In [37]: c[4]
Out[38]: 5
In [39]: c[4] = 7
Error output
26
Data Types:
Dictionaries
collection of Python objects, just like a list, but one
that is indexed by strings or numbers
enclosed in round parentheses {}
In [1]: room = {"Emma":309, "Jacob":582, "Olivia":764}
In [2]: room["Olivia"]
Out[2]: 764
In [3]: weird = {"tank":52, 846:"horse", "bones":[23,
...: "fox", "grass"], "phrase":"I am here"}
In [4]: weird["tank"]
Out[4]: 52
27
Data Types:
Dictionaries
In [5]: weird[846]
Out[5]: ’horse’
In [6]: weird["bones"]
Out[6]: [23, ’fox’, ’grass’]
In [7]: weird["phrase"]
Out[7]: ’I am here’
28
Data Types:
Dictionaries
Dictionaries can be built up and added to in a straightforward
manner
In [8]: d = {}
In [9]: d["last name"] = "Alberts"
In [10]: d["first name"] = "Marie"
In [11]: d["birthday"] = "January 27"
In [12]: d
Out[12]: {’birthday’: ’January 27’, ’first name’: ’Marie’, ’last name’: ’Alberts’}
29
Data Types:
Dictionaries
You can get a list of all the keys or values of a
dictionary by typing the dictionary name
followed by .keys() or .values().
In [13]: d.keys()
Out[13]: [’last name’, ’first name’, ’birthday’]
In [14]: d.values()
Out[14]: [’Alberts’, ’Marie’, ’January 27’]
30
NUMPY
NumPy, which stands for Numerical Python, is a
library consisting of multidimensional array objects and a
collection of routines for processing arrays
mathematical and logical operations on arrays can be
performed
We will look at numpy array manupilation
Aalready Anaconda installation came with numpy
https://www.tutorialspoint.com/numpy/index.htm
31
NUMPY
Numpy Array
To create converts a list to an array:
In [1]: a = [0, 0, 1, 4, 7, 16, 31, 64, 127]
In [2]: b = np. array(a)
In [3]: b
Out[3]: array([ 0, 0, 1, 4, 7, 16, 31, 64, 127])
In [4]: c = np. array([1, 4., -2, 7])
In [5]: c
Out[5]: array([ 1., 4., -2., 7.])
32
NUMPY
Numpy Array
We can use NumPy linspace or logspace
linspace(start, stop, N)
If the third argument N is omitted, then N=50
In [6]: np. linspace(0, 10, 5)
Out[6]: array([ 0. , 2.5, 5. , 7.5, 10. ])
We can use NumPy arange
arange(start, stop, step)
If the third argument step is omitted, then step=1
In [9]: np.arange(0, 10, 2)
Out[9]: array([0, 2, 4, 6, 8])
In [10]: np. arange(0., 10, 2)
Out[10]: array([ 0., 2., 4., 6., 8.])
In [11]: np. arange(0, 10, 1.5)
Out[11]: array([ 0. , 1.5, 3. , 4.5, 6. , 7.5, 9. ])
33
NUMPY
Numpy Array
We can use ones and zeros to create an array:
In [12]: np.zeros(6)
Out[12]: array([ 0., 0., 0., 0., 0., 0.])
In [13]: np.ones(8)
Out[13]: array([ 1., 1., 1., 1., 1., 1., 1., 1.])
In [14]: np.ones(8, dtype=int)
Out[14]: array([1, 1, 1, 1, 1, 1, 1, 1])
34
NUMPY
Mathematical operations with arrays
In [15]: a = np.linspace(-1., 5, 7)
In [16]: a
Out[16]: array([-1., 0., 1., 2., 3., 4., 5.])
In [17]: a*6
Out[17]: array([ -6., 0., 6., 12., 18., 24., 30.])
In [18]: a/5
Out[18]: array([-0.2, 0. , 0.2, 0.4, 0.6, 0.8, 1. ])
In [19]: a**3
Out[19]: array([ -1., 0., 1., 8., 27., 64., 125.])
In [20]: a+4
Out[20]: array([ 3., 4., 5., 6., 7., 8., 9.])
35
NUMPY
Mathematical operations with arrays
In [23]: np.sin(a)
Out[23]: array([-0.84147098, 0. , 0.84147098, 0.90929743,
0.14112001, -0.7568025 , -0.95892427])
In [24]: np. exp(-a)
Out[24]: array([ 2.71828183, 1. , 0.36787944, 0.13533528,
0.04978707, 0.01831564, 0.00673795])
In [25]: 1. + np. exp(-a)
Out[25]: array([ 3.71828183, 2. , 1.36787944, 1.13533528,
1.04978707, 1.01831564, 1.00673795])
In [26]: b = 5* np. ones(8)
In [27]: b
Out[27]: array([ 5., 5., 5., 5., 5., 5., 5., 5.])
36
NUMPY
Mathematical operations with arrays
create an x-y data set of y = cos x vs. x over the interval from -3.14 to 3.14
In [30]: x = linspace(-3.14, 3.14, 21)
In [31]: y = cos(x)
In [32]: x
Out[32]: array([-3.14 , -2.826, -2.512, -2.198, -1.884, -1.57 ,
-1.256, -0.942, -0.628, -0.314, 0. , 0.314,
0.628, 0.942, 1.256, 1.57 , 1.884, 2.198,
2.512, 2.826, 3.14 ])
In [33]: y
Out[33]: array([ -1.000e+00, -9.506e-01, -8.083e-01,
-5.869e-01, -3.081e-01, 7.963e-04,
3.096e-01, 5.882e-01, 8.092e-01,
9.511e-01, 1.000e+00, 9.511e-01,
8.092e-01, 5.882e-01, 3.096e-01,
7.963e-04, -3.081e-01, -5.869e-01,
-8.083e-01, -9.506e-01, -1.000e+00])
37
NUMPY
Matrix Operations
38
NUMPY
Matrix Operations
In [53]: a = np.ones((3,4), dtype=float)
In [54]: a
Out[54]: array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
In [55]: np.eye(4)
Out[55]: array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
39
NUMPY
Matrix Operations (reshape function)
In [56]: c = np.arange(6)
In [57]: c
Out[57]: array([0, 1, 2, 3, 4, 5])
In [58]: c = np.reshape(c, (2,3))
In [59]: c
Out[59]: array([[0, 1, 2],
[3, 4, 5]])
40
NUMPY
Matrix Operations (dot function)
41
NUMPY
Matrix Operations (transpose, inv)
Matrix Inverse
In [60]: A = np.array([[1, -2, 4],[0, -2.4, 3],[7, 0, -4]])
In [61]: Ainv = np.linalg.inv(A)
In [62]: print(A.dot(Ainv))
x = np.arange(-np.pi,np.pi,0.001)
y = np.sin(x)
plt.plot(x, y,'r')
plt.ylabel("Sin (x)")
plt.xlabel("x")
plt.grid()
plt.show()
43
MATPLOTLIB
Read on basics plotting properties:
plt.figure(1, figsize = (6,4) )
plt.plot(x, y, ’b-’, label=’theory’)
plt.plot(xdata, ydata, ’ro’, label="data")
plt.xlabel(’x’)
plt.ylabel(’transverse displacement’)
plt.legend(loc=’upper right’)
plt.axhline(color = ’gray’, zorder=-1)
plt.axvline(color = ’gray’, zorder=-1)
plt.savefig(’WavyPulse.pdf’)
44
Input and Output
input keyword is input from keyboard
In [1]: distance = input("Input distance in miles: ")
Input distance of trip in miles:
Distance is string.
To convert to integer:
In [3]: distance = eval(distance)
In [4]: distance
Out[4]: 450
To float
In [7]: distance = float(distance)
In [8]: distance
Out[8]: 450.0
45
Input and Output
print keyword is to output to monitor
Read section “4.2 Screen output” from
Introduction to Python for Science
46
Reading data from a CSV file
simplest and robust is to save the spreadsheet as a
CSV (“comma separated value”) file, a format which
all common spreadsheet programs can create and
read.
Excel spreadsheet called MyData.xlsx, the CSV file
saved using Excel’s Save As command would by
default be MyData.csv
47
Reading data from a CSV file
48
Reading data from a CSV file
49
Conclusions
It is a long week (in terms of the notes
and what we covered)
Before answering the HW1 be sure to go
over Chapter 3, 4, and 5 of Introduction
to Python for Science
Try all the examples and exercises given in the
end of each chapter.
50