An Ultra-Quick Primer To Python: Lecture 1c, February 24, 2021 Simon Scheidegger
An Ultra-Quick Primer To Python: Lecture 1c, February 24, 2021 Simon Scheidegger
th
Lecture 1c, February 24 , 2021
Simon Scheidegger
Outline of this mini-course in Python
Control unit:
→ fetches instructions/data from memory, decodes the instructions and
then sequentially coordinates operations to
accomplish the programmed task.
Arithmetic Unit:
→ performs basic arithmetic operations.
Input/Output
→ interface to the human operator.
I. Motivation
- System Software
Operating System:
- I/O operation.
- Storage & memory.
- Protection among concurrent applications.
Compilers:
- Translate from high level language
such as C++ to hardware instructions.
I. Motivation
What is Python?
- Python is a general purpose programming
language conceived in 1989 by Dutch
programmer Guido van Rossum.
Common uses
Python is a general purpose language used in almost all application
domains:
- communications
- web development
- graphical user interfaces
- games, multimedia, data processing, security, etc.
- Machine Learning, Artificial Intelligence
https://spectrum.ieee.org/computing/software/the-2020-top-programming-languages
I. Motivation
Relative popularity
- The following chart, produced using Stack Overflow Trends, shows one measure of the
relative popularity of Python.
- The figure indicates not only that Python is widely used but also that adoption of Python
has accelerated significantly since 2012.
- We suspect this is driven at least in part by uptake in the scientific domain, particularly in
rapidly growing fields like data science.
I. Motivation
Some features
- Python is a high level language suitable for rapid
development.
- Other features:
A multi-paradigm language, in that multiple programming
styles are supported (procedural, object-oriented, functional,...)
Elegant code might sound superfluous but in fact it’s highly beneficial
because it makes the syntax easy to read and easy to remember.
Remembering how to read from files, sort dictionaries and other such routine
tasks means that you don’t need to break your flow in order to hunt down
correct syntax.
Get Python
You can download and install
Python directly from
https://www.python.org
Since we’re going to use several
libraries for numerical
computation (numpy), data analysis (pandas),
machine learning (scikit-learn), and
visualization (matplotlib),
it is easier to install Anaconda,
which bundles all things required
https://www.continuum.io/downloads
I. Motivation
https://docs.python.org/
I. Motivation
Install Python
https://www.python.org/downloads/
List of examples
https://www.python.org/downloads/
https://www.pythonanywhere.com/try-ipython/
https://repl.it/languages/python
Python setup
II. First steps
Feel free to use it for the course exercises and your own code:
http://pythontutor.com/visualize.html
II. First steps
Basic types
No type declaration needed – Python does that for you on the fly
II. First steps
Type conversions
String literals
II. First steps
String literals II
II. First steps
Operators
II. First steps
Operators II
>>>‘U’ + ‘NIL
‘UNIL?
II. First steps
Operators III
II. First steps
Assignments
II. First steps
Assignments II
II. First steps
Functions
print('Hello, world!')
→ Execute it with
$ python hello.py
II. First steps
Example:
The task is to generate the rows of the table of C and F values. The C value starts at
−20 and is incremented by 5 as long as C ≤ 40. For each C value we compute the
corresponding F value and write out the two temperatures. In addition, we also add a
line of hyphens above and below the table. We postpone to nicely format the C and F
columns of numbers and perform for simplicity a plain print C, F statement
inside the loop.
$python example3_while.py
------------------
-20 -4.0
-15 5.0
( )
-10 14.0
-5 23.0
0 32.0
5 41.0
( ) 10 50.0
15 59.0
( )
20 68.0
25 77.0
30 86.0
35 95.0
40 104.0
------------------
II. First steps
( )
II. First steps
Lists
Up to now a variable has typically contained a single number.
With a variable that refers to the list, we can work with the whole group at once, but we
can also access individual elements of the group.
The figure illustrates the difference between an int object and a list object.
In general, a list may contain a sequence of arbitrary objects in a given order. Python
has great functionality for examining and manipulating such sequences
of objects.
With del C[i] we can remove an element with index i from the list C.
II. First steps
- This construct in Python and many other languages called a “for loop”.
example6_forloop.py
example5_forloop.py
( )
( )
( )
II. First steps
Try this:
>>>help(greet)
II. First steps
Modules
II. First steps
Modules II
II. First steps
Conditionals
II. First steps
Branching in general
II. First steps
Exercises
II. First steps
The results produced by the program, here F, constitute the output data.
Input data can be hard-coded in the program as we do above.
→ There is then no need to modify the program itself when a new set of
input data is to be explored.
II. First steps
example10_read.py
( )
The sys module has a list argv containing all the command-line arguments to the program,
i.e., all the “words” appearing after the program name when we run the program.
Here there is only one argument and it is stored with index 1. The first element in the
sys.argv list, sys.argv[0], is always the name of the program.
import sys
print "This is the name of the script: ", sys.argv[0]
F= 9*float(C)/5 + 32
Run as: print "it is ", F , " degrees F"
$python example11_readsys.py 2
→ Note: there are plenty of option on how to read from files → RTFM
a1 = []
a2 = []
a3 = []
a4 = []
1234
5678 with open('data.txt') as f:
for line in f:
9 10 11 12 data = line.split()
13 14 15 16 a1.append(int(data[0]))
a2.append(int(data[1]))
a3.append(int(data[2]))
a4.append(int(data[3]))
Pandas
II. First steps
import numpy as np
mat=np.matrix([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(mat)
np.savetxt('matrix.txt',mat,fmt='%.2f')
II. First steps
Curve Plotting
- Visualizing a function f (x) is done by drawing the curve y = f (x) in
an x-y coordinate system.
- When we use a computer to do this task, we say that we plot the curve.
Let us plot the curve s for values between 0 and 2. First we generate equally spaced
coordinates for t. Then we compute the corresponding s values at these points, before
we call the plot(t,s) command to make the curve plot.
import matplotlib.pyplot as plt
import numpy as np
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.savefig("test.png")
plt.show()
Want more?
217,612
III. Nonlinear equations & optimization.
- Our course heavily relies on solving large
systems of nonlinear equations or (un-) constraint
optimization problems.
- SciPy.org
- PyOpt.org
- IPOPT
(https://www.coin-or.org/Ipopt; https://github.com/xuy/pyipopt)
III. Opt. & Nonlinear Eqs.
Several methods are available, amongst which hybr (the default) and lm
which respectively use the hybrid method of Powell and the Levenberg-
Marquardt method from MINPACK.
http://docs.python.org/tutorial/
http://pixelmonkey.org/pub/python-training/
http://python4java.necaiseweb.org/Main/TableOfContents
Books:
Youtube:
1. Advice – RTFM
https://en.wikipedia.org/wiki/RTFM
2. Advice – http://lmgtfy.com/
http://lmgtfy.com/?q=introduction+to+python