Professional Documents
Culture Documents
Python Lecture 01
Python Lecture 01
PROGRAMMING &
NUMERICAL ANALYSIS2014
Lecture 01: Introduction
OVERVIEW
Actually this is a quasi-laboratory course, since no one can learn
how to do programing by only listening to the lectures and take
notes (and only do the homework once a while!).
If you do not have a laptop, you are encouraged to work with your
classmate who has laptop during the lecture.
A QUASI-LABORATORY
LECTURE
A QUASI-LABORATORY
LECTURE
I will not just blah-blah throughout the whole 3 hours.
Instead, 1/2~2/3 of the total time will be devoted to an
introductory lecture with slides.
There will be also some short trial periods during the main
lecture, which allows you to try something easy.
Please also stop me when you run into any difficulties or troubles
throughout the whole lecture.
THE GOAL OF
THIS COURSE
Learn how to solve a problem with computers rather than
a pen and papers.
(well, python is probably the easiest computer language to learn within half of
semester and powerful enough to do many things!)
languages (e.g. C++, fortran, php, etc.) in the future for your own
work. Hopefully you will get some taste of computing in this
semester.
SCIENTIFIC COMPUTING
WITH PYTHON
We will use (some of the) SciPy (pronounced like sign pie)
packages in this lecture:
! !
! !
SciPy library:
fundamental library for scientific computing.
! !
! !
NumPy:
base N-dimensional array package.
! !
! !
Matplotlib:
Comprehensive plot making
OUTLINE
Python, the programming language
The basis
Control flow
Types and data structure
Functions and modules
Input & Output
Classes and others
Numerical analysis with Python
Numerical differential and integration
Random numbers
Show it graphically
Linear algebra
Root finding and minimum finding
Differential equations
Curve fitting and data modeling
8
The first part of the course can be too easy for you in this case, and
you can probably learn the later part by yourself without any
difficulties.
EVALUATION
Homework:
Exercises will be assigned every subject (every 12 weeks).
Please hand back (upload) the code within 1 week.
Quizzes:
Will be assigned during the midterm week (no lecture).
Time limit: 1 week.
Googling the answer is allowed. Discussions are also allowed.
Surely this sounds too relaxed...
10
EVALUATION (II)
From the basic grading toward the final goal:
EVALUATION (III)
How to collect the golden coins:
Be the first 3 people uploading one of the homework .
Be the first 3 people uploading the answer to any one of the
12
TEXTBOOK &
REFERENCES
For python, most of the information are online. Getting a printed
textbook is not really required. A couple of nice
online books/documents are available:
Python.org tutorial:
http://docs.python.org/2/tutorial/index.html
http://www.greenteapress.com/thinkpython/html/index.html
A byte of python:
http://swaroopch.com/notes/python/
TEXTBOOK &
REFERENCES (II)
For SciPy (and NumPy), there are already some document
available on the official website and some online e-books:
http://docs.scipy.org/doc/
http://it-ebooks.info/book/2847/
http://it-ebooks.info/book/1280/
In principle you can always find the help online, so it is
not really required to have a printed book.
14
TEXTBOOK &
REFERENCES (III)
References for computational physics & algorithms (non-python):
Numerical Recipes:
The Art of Scientific Computing
by William H. Press
3rd Edition (2007)
http://www.nr.com/
An Introduction to
Computational Physics
by Tao Pang
2nd Edition (2006)
Computational Physics:
Problem solving with computers
by Rubin H. Landau et al.
There are still many other
2nd Edition (2007)
computational physics or algorithm
text book can be found on the market.
15
16
GETTING START
If you are using any unix-like operation system, such as Linux or
Mac OSX, usually a python is pre-installed in your system:
For Windows, in principle you can download the python from the
official download area (please avoid python 3 for now):
http://www.python.org/download/
https://www.enthought.com/store/
Just download it and install. It comes with all the needed
packages already, together with a nice IDE ready to go.
http://continuum.io/downloads.html
Also simply download it and install. It requires a little bit more
command line working experience but the support is good.
Basically these two options support Windows, Linux, and Max OSX.
18
19
COMMENTS
In principle you can install all of the required packages (Python
21
COMMENTS (CONT.)
Python 2 versus Python 3:
If you check the documents (and the official site) carefully, you
may find there are some issues between python 2 and 3. Basically
python 3 does not have the backward capability with version 2,
and the integration of python 3 has not yet been fully established.
The syntax is slightly different. In this lecture we will use python
2.7 as the default version.
Dont worry about the exact version for now.
The key idea is to learn how to solve a problem
with programming, not the language itself.
22
INTERMISSION
Now its the time to get your working environment ready!
(switch on your laptop now!)
If you only have a pad/phone, you can even try some of the online
python interpreter, e.g.:
http://www.compileonline.com/execute_python_online.php
http://repl.it
23
PYTHON:
AN INTRODUCTION
Quote from Wikipedia: Python is a widely used general-purpose,
Readability counts.
24
PYTHON:
AN INTRODUCTION (II)
Python development was started in December 1989.
Python's principal author: Guido van Rossum.
The origin of the name comes from Monty Python (Monty
PYTHON,
26
HELLO WORLD IN
C/C++
Well, the common starting point for any programming language.
#include <stdio.h>
int main()
{
! printf("hello world!\n");
}
helloworld.cc
27
HELLO WORLD IN
PYTHON
print 'hello world!'
helloworld.py
THE INTERPRETER
An interpreter reads a high-level program (the source code) and
executes it.
PYTHON,
THE INTERPRETER
Python is considered an interpreted language because Python
programs are executed by an interpreter.
31
PYTHON,
THE INTERPRETER (II)
There are actually two ways to use the interpreter:
interactive mode and script mode.
helloworld.py
width = 20
height = 5*9
area = width * height
area
>>> a = 2j
>>> a*a
(-4+0j)
>>> b = complex(3,4) Using the function complex(real, imag)
>>> a+b
(3+6j)
>>> 8j/3j
(2.6666666666666665+0j) Complex numbers are always float.
>>> b.real + b.imag
Exact the real/imaginary part
7.0
with .real and .imag
>>> abs(b) absolute value
5.0
36
The interpreter can also tell you what type a value has:
>>> type('hello!')
<type 'str'>
>>> type(1234)
<type 'int'>
>>> type(3.14159)
<type 'float'>
40
41
>>> type(3<4)
<type 'bool'>
>>> type(open(tmpfile,w))
<type 'file'>
>>> type([1,2,3,4,[five,6.0]])
<type 'list'>
>>> type((1,2,three,4))
<type 'tuple'>
>>> type({'name':'Chen','phone':33665153})
<type 'dict'>
>>> type({'a','b',c})
<type 'set'>
42
VARIABLES
A variable is a name that refers to a value.
An assignment statement creates new variables and gives them
values (you have seen this already):
>>> pi = 3.1415926536
>>> last_message = what a beautiful day
Variable names can be arbitrarily long, can be with both letters and
numbers.
VARIABLES (CONT.)
The variable names have to start with a letter or _
It is a good idea to begin variable names with a lowercase letter.
Pythons keywords: keywords are used to recognize the structure
of the program, and cannot be used as variable names.
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
44
not
or
pass
print
raise
return
try
while
with
yield
INTERMISSION
Now its the time to play with your python interpreter:
As a simple calculator.
Play with the strings.
Examine the python built-in types.
Define your variables and check any possible break-down cases.
45
A STEP TOWARD
PROGRAMMING
A program is a sequence of instructions that specifies how to
perform a mathematical/symbolic computation.
A couple of examples:
STRUCTURE OF
A PROGRAM
Input:
GIVE ME A FLYSWATTER
Programming is error-prone. Programming errors are called bugs
and the process of tracking them down is called debugging.
49
SYNTAX ERRORS
Syntax refers to the structure of a program and the rules about that
structure.
An example:
>>> y = 1 + 4x
File "<stdin>", line 1
y = 1 + 4x
^
SyntaxError: invalid syntax
>>>
50
RUNTIME ERRORS
A runtime error does not appear until after the program has
started running.
>>> a = b = 2
>>> r = ((a + b)/(a - b))**0.5 * (a - b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>>
51
SEMANTIC ERRORS
If there is a semantic error in your program, it will run successfully,
but it will not do the right thing.
52
SEMANTIC ERRORS
An example:
s = t = 1.
s = t = 1
for n in range(1,21):
t /= n
s += t
print "1/0!+1/1!+1/2!+1/3!+...+1/20! =",s
1/0!+1/1!+1/2!+1/3!+...+1/20! = 2
2.71828182846
53
DEBUGGING
It is very difficult to write a bug free program at the first shot.
Programming and debugging can be the same thing.
54
HANDS-ON SESSION
Up to now we have gone through:
The basic python interface
Variables, types, and operators
Now you should be able to do some useful calculations!
Lets start our first round of
hands-on session now!
55
HANDS-ON SESSION
Practice 1:
Get your working environment ready now, and type in your first
hello world!.
56
HANDS-ON SESSION
Practice 2:
4 kg
G = 6.67384 1011 m3kg1s2
5m
3m
A: 5 kg
4m
57
3 kg
HOMEWORK #1
Exercise 1:
print 'Hello!'
print 'My name is XXX.'
print 'My student ID is YYY.'
58