本文内容来源于Yupeng Jiang(伦敦大学数学系)课件,本人认为非常经典,原文为纯英文,网上也已经有翻译的版本,但是自认为还是有些凌乱,看起来不是很舒服,故再次整理发布于此。其一,是作为自己巩固复习之用;其二,资源共享
课程大纲:
- 第1天:Python背景 ;基础(环境,数据类型 ,运算符,数据结构 ,条件语句,循环语句,方法 ,I/O)
- 第2天:用Numpy,Scipy,Matplotlib和其他模块进行计算。 用Python解决一些数学问题。
- 第3天:时间序列:用Pandas进行统计和实际数据分析。 随机和蒙特卡罗。
day1:
一、背景:
为什么使用python?
- Python是开源的,这意味着它是免费的。
- Python是一种胶水语言:
- Python使你的编码更加轻松
- Python平均来讲,比一些语言计算更快,比如Matlab
- Python有一个很大的程序员社区。 它带来了与大量的标准库和扩展包。
- Python广泛应用于各种行业(Google,NASA,对冲基金,银行等)。
二、基础知识:
1.python环境
- 安装Python科学堆栈的推荐方法是使用Continuum Analytics Anaconda。
- Anaconda是一个免费的软件包管理器,环境管理器,以及开源软件包的集合。
- Anaconda包括核心Python解释器和标准库。
- https://www.continuum.io/downloads
2. Anaconda中包含的库:
- NumPy(http://numpy.scipy.org ):该库用于处理(大)数组。
- SciPy(http://www.scipy.org ):该库包含许多有用的科学功能。
- Matplotlib(http://matplotlib.sourceforge.net ):该库用于绘图。
- Pandas(http://pandas.sourceforge.net ):该库有效并快速分析大数据集; 尤其针对金融时间序列。
- IPython(http://wprw.ipython.org ):shell、或基于浏览器:开发环境。
- Spyder(http://pythonhosted.org/spyder/ ):IDE交互式开发环境
3.常用的数据类型:
Name | Notation | Declaration e.g. |
---|---|---|
Integers | int | a = 10 |
Floating | float | b = 3.14 |
Complex | complex | c = 1 + 2j |
String | str | d = 'Python' |
- 备注:
- 在Python 2.7中,int与另一个int运算将导致int结果。 但是,一个浮点运算与int会导致浮点数。
- 在Python 3.x中,int与另一个int运算将导致浮点数。
4.算数运算符:
Name | Notation | Examples |
---|---|---|
Addition | + | a + b |
Subtraction | - | c - b |
Multiplication | * | x*y |
Division | / | x/z |
Modulus | % | x%a |
Exponent | ** | a**x |
练习:执行下列代码
- a = 10 # int
- b = 3.14 # fLoat
- c = 3 #int
- d = a ** 2 # square of a
- print (type (d)) # return the type of d
- print (type (d/l0)) # return the type of d/l0
- print (type (a/b)) # return the type of a/b
- print (type (a/c)) # return the type of a/c
- print (type (bd)) # return the type of bd
浮点数的精度:
- 尝试在您的控制台中键入0.1 + 0.2。 你会发现这个值是
- 0.30000000000000004
- 这是二进制浮点的本质。 您可以在支持硬件浮点运算的所有语言中看到同样的东西。
- 可以使用“round()”功能控制显示精度,
- decimal Library将给出精确的存储值,请参见以下示例。
import decimal print (round (3*1415,2)) #3. 14 print (round (9.995,2)) #9. 99 print (decimal.Decimal (9.995)) #9.9949999999999992184029906638897955417633056640625
练习:字符串str的一些方法
t = 'He is a string. Who are you?' print(t.capitalize()) # Cap first letter print(t.split()) # split by words print(t.find('i')) # return index of 'i' print(t[0:4]) # returu from index 0 to 3 print(t.replace(' ','|')) # replace by '|' w = 'http://www.google.com' print(w.strip('http://')) #delete sth
5.python基本数据结构
Name | Nation | Declaration e.g. |
---|---|---|
Tuple | tuple | b = (1,2.5, 'data') |
List | list | c = [1,2.5,'data'] |
Dictionary | dict | d = {'Name': 'Kobe', 'Country':'US'} |
Set | set | e = set(['u','d','ud','d','du']) |
- 元组(tuple)只有几种方法可以更改。
- 列表(list)比元组更灵活。
- 字典(dict)是一个键值对存储对象。
- 集合(set)是对象中唯一的无序集合对象。
列表(list)的一些方法:
l = [1,2,3.14,'data']
print (type(l))
l.append ([4,3])
print(l)
l.extend (['delta',5,6] )
print(l)
l.insert(3,'beta')
print(l)
l.remove ('data')
print(l)
<class 'list'> [1, 2, 3.14,'data',[4,3]] [1, 2, 3.14,'data',[4,3],'delta',5,6] [1, 2, 3.14,'beta','data',[4, 3],'delta', 5,6] [1, 2, 3.14,'beta',[4, 3],'delta',5,6]
python参考对象:
- 在Python中,如果要将值从一个对象传递给另一个对象,则=(等号)将按地址传递值。
- 例如:
x = [1,2,3,4] y = x y[0] = 5 print(x) x = [1,2,3,4] z = x.copy() z[0] = 5 print (x)
输出:
[5,2,3,4] [1,2,3,4]
多维列表:试一试
a = [[1,2,3,4],[1,2,3,4],[1,2,3]] print(a) print(a[0][3])请注意: 多维列表不是矩阵。 数学运算符可能会导致您不想看到的结果。 对于矩阵计算,我们将在明天花费大量的时间
6.条件语句
- 条件控制元素包括if,else和elif。
- 对于条件语句,我们有如下几种:
Name | Notation |
---|---|
larger | > |
smaller | < |
equal | == |
larger or equal | >= |
sma |
- 对于多条件同时使用的情况,我么使用and, or 或者 not作为关键字来相互衔接
a = [24,16,54] b = [] if a[0]< a[1] and a[0]< a[2] : b.append(a[0]) if a[1] < a[2]: b.append(a[1]) b.append(a[2]) else: b.append(a[2]) b.append(a[1]) # This piece of code is not done yet. # Please complete it !!!
7.循环语句:
循环语句有很多不同的样式代码,我们举例说明两种,for循环和while循环
for...in ... :
statement A
是循环中最常用的语句,通常与range(start,end,step)一起使用,start为起始值,end为结束值,step为步长。
while ...:
statement A
将会执行A语句,直到满足while的条件。
例子:
for i in range(2, 10, 3): print(i) l= i**2 print(l) a = 0 sumup = O while a < 100 : a + 1 sumup += a print(sumup)
break和continue
- 你可以在循环语句中使用关键字break,以跳出循环。(you can use the keyword break inside a loop to leave the loop..)
- 你也可以在循环语句中使用关键字continue,以暂停当前循环执行后面的语句。(you can use the keyword continue inside a loop to stop pracessing the current iteration of the loop and immediately go on to the next round.)
- 举例 E.g.
for i in range(300, 351): if i % 17 == O: print(i) break else : continue
循环嵌套:
for i in range(10): print(i) for j in range(5): print(j)
8.方法(函数)的定义
def TheNameOfFunction(paral, para2): ... return Outcome
举例:求两个变量最大值的函数
def MaxOfTwo (x1, x2): if x1 >= x2: return x1 else: return x2 a = l b = 2 c = MaxOfTwo(a, b) print(c)
9.读取/写入文件
内置的open()方法
- 要打开一个文件,使用Python内建的open()函数。 open()方法返回一个文件对象,最常用的一般使用两个参数。
file_object = open(filename, mode)
这个mode参数可以是(The mode can be)
- 'r' 只读模式(when the file will only be read)
- 'w' 只写模式(与一个现存文件文件同名,则被清除)
- 'a' 添加模式,即任意写入文件的数据都被自动添加到末尾
- 'r+' 打开文件,可以读、写
例子:
写入
file = open('newfile.txt', 'w') file.write('I am created for the course. \n') file.write('How about you? ') file.write('How is your exam?') file.close()
读取
file = open('newfile.txt', 'r') #show whole efile print(file.read()) #show first ten characterrs print(file.read(10)) #view by line print(file.readline()) #view all by line print(file.readlines()) file.close()
循环读取
file = open('newfile.txt', 'r') for line in file: print (line) file.close()
文件添加内容
file = open('newfile.txt', 'a') file.write('\nI am back again. \n') file.write('Do you miss me?\n') file.close()
with语句
- 由于很容易忘记close文件,所以最好使用with语句:
with open("humpty.txt") as f:
...
第二天内容请进传送门>>>三天搞定python基础-day2