原因:2017年2月4日 星期六 随笔记录。 说明:本文主要记录学习python的过程,需求不大,轻度使用,所以进行简单的认识性学习。 状态:Updating to 2.14
brew install python3alias py='python3py即可。#!/usr/bin/env python3
print('hello, world')# print absolute value of an integer:
a = 100
if a >= 0:
print(a)
else:
print(-a)#开头的是注释,以:结尾 python中可以处理的数据类型有以下几种:
\辨别,\n换行\t制表符。r''表示''内的字符串不转义。注意在输入多行内容时,提示符由>>>变为…,提示你可以接着上一行输入。如果写成程序,就是:print('''line1
line2
line3''')英文、数字和_的组合,且不能用数字开头。这种变量本身类型不固定的语言称之为动态语言,与之对应的是静态语言。静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。例如Java是静态语言。π。python中常用大写变量PI表示,但事实也是一个变量,python没有机制保障PI不会被改变。/,计算机结果为浮点数。还有一个地板除//,地板除只保留整数部分。取余为%。编码UTF-8。UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间:字符 | ASCII | Unicode | UTF-8 |
|---|---|---|---|
A | 01000001 | 00000000 01000001 | 01000001 |
中 | x | 01001110 00101101 | 11100100 10111000 10101101 |
字符串ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符。b前缀的单引号或双引号。decode()方法(编码encode):>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'>>> len('ABC')
3
>>> len('中文')
2#!/usr/bin/env python3
# -*- coding: utf-8 -*-格式化%实现,举例如下:>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'listtuple条件判断elif,else实现,从上向下以此判断,当有合适的条件,就会跳出,不继续向下判断。a = int(b) 将字符串b转为数值。#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = float(input('身高 : '))
b = float(input('体重 : '))
bmi = b/a/a
if bmi < 18.5 :
print('过轻')
elif bmi <= 25 :
print('正常')
elif bmi <= 28 :
print('过重')
elif bmi <= 32 :
print('肥胖')
elif bmi > 32 :
print('严重肥胖')forfor x in lsit:,可以用range()函数生成从0开始的整数序列。whilewhile x : 当不满足条件x时跳出循环。breakcontinuedict>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95d['Bob'] = 99的方法进行赋值替换,但是key-value是一对一的关系,故会将之前的值冲掉。in进行判断>>> 'miniyao' in d
False>>> d.get('miniyao')
>>> d.get('miniyao',-1)
-1>>> d.pop('Michael')
95
>>> d
{'Bob': 75, 'Tracy': 85}set>>> s = set([1,2,3])
>>> s
{1,2,3}再议不可变对象#从小到大排序 myList.sort() print(myList)
#从大到小排序 myList.sort(reverse = True) print(myList)
- 而不可变对象操作内容不变。
---
## 函数
- 处理有规律的重复等问题,使用函数。
---
### 调用函数
- 对于内置函数,调用时需要知道函数`名称`和`参数`。比如求绝对值函数abs,可以直接查看文档or在交互式命令中输入`help(abs)`
---
#### `数据类型转换`
- python内置的常用函数还包括数据类型转换,譬如int()函数将其他数据类型转为整数
---
### 定义函数
- 在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
- 我们以自定义一个求绝对值的my_abs函数为例:
```python
def my_abs(x):
if x >= 0:
return x
else:
return -xfrom test import my_abs可用于从test.py文件导入my_abs函数。空函数def nop()
pass参数检查TypeError:返回多个值import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny>>>x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)#!/usr/bin/env python3
import math
def quadratic(a,b,c):
n = b*b - 4*a*c
if a==0:
x = -c/b
return x
elif a!=0:
if n > 0:
x1 = (-b + math.sqrt(n))/(2*a)
x2 = (-b - math.sqrt(n))/(2*a)
return x1,x2
elif n == 0:
x = -b/(2*a)
return x
else:
return '无解'默认参数的作用是降低函数的调用难度。def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return sn=2即为默认参数。def add_end(L=[]):
L.append('END')
return L默认参数(小心掉坑里)必须指向不变对象。譬如:def add_end(L=None):
if L is None:
L = []
L.append('END')
return LL=None ,就会在每个list后加上END,当已有END时就会报错!可变参数可变参数就是传入的参数个数是可变的。使用list or tuple传入若干个参数。def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum>>> cale([1,2,3]) #输入需要为list or tupledef calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum>>> calc(1,2) #输入简化了*nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用,而且很常见。关键字参数def person(name,age,**kw):
print('name:',name,'age:',age,'other:',kw)>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=extra['city'], job=extra['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra。命名关键字参数kw检查。def person(name,age,*,city,job):
print(name,age,city,job)>>> person('Jack',24,city='Beijing',job='Engineer')
Jack 24 Beijing Engineer*了:def person(name,age,*age,city,job):
print(name,age,args,city,job)def person(name,age,*,city='Beijing',job):
print(name,age,city,job)参数组合def fact(n):
if n==1:
return 1
return n * fact(n - 1)===> fact(5) #阶乘
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120尾递归优化,事实上尾递归和循环的效果是一样的。def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)return fact_iter(num - 1, num * product)仅返回递归函数本身,num - 1和num * product在函数调用前就会被计算,不影响函数调用。Slice)操作符,能大大简化这种操作。>>> L[:10:2]
[0, 2, 4, 6, 8]>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]>>> L[:]
[0, 1, 2, 3, ..., 99]for ... in ... :实现的,循环的抽象程度较高,只要作用于一个可迭代的对象,for就可以正常运行,通过collection模块的Iterable类型判断对象是否可以迭代:>>> from collection import Iterable
>>> isinstance('abc',Iterable)
Truefor value in d.values(),如果要同时迭代key和value,可以用for k, v in d.items()。enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9List Comprehensions,是python内置的非常将蛋却强大的可以用来创建list的生成式。>>>[x*x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]x*x放到最前面,后面跟for循环,后面还可以跟if判断进行筛选>>> [m+n for m in 'ABC' for n in 'XYZ']:
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']>>> import os # 导入os模块
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']>>>> L1 = ['Hello', 'World', 18, 'Apple', None]
>>>> L2 = [ x.lower() for x in L1 if isinstance(x,str)]
>>>> print(L2)
['hello', 'world', 'apple']isinstance判断是否为字符串,lower()调用数字报错。generator。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> G = (x * x for x in range(10))
>>> G
<generator object <genexpr> at 0x10af5c0a0>Fibonacci的函数实现:def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'a,b = b,a+b 相当于:t = (b,a+b) #t是一个tuple
a = t[0]
b = t[1]print(b)改为yield b就可以了。def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数而是一个generatordef odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#杨辉三角
def triangles(max):
L = [1]
while len(L)<=max:
yield L
L.append(0)
L = [L[i - 1] + L[i] for i in range(len(L))]
n = input('please input the max num : ')
for x in triangles(int(n)):
print(x)