python 基础教程

还在更新中,未完待续...

0x01 运算

  • 平方
>>> 2 ** 2
4
  • 立方
>>>pow(2,3)
8
  • 四次方
>>>pow(2,4)
16
  • 整除取整数
>>>5 // 3
1
  • 取余
>>>5%3
2

0x02 字符串

  • 单引号 双引号等的特殊字符需要使用转义字符
>>>'this is book '
'this is book'    
>>> 'He\'s book'
"He's book"

0x03 print函数 与 input函数

>>>print(1+1)
2
>>> print('hello\nworld')
hello
world
>>> input('enter something please:')
enter something please:good is good
'good is good'
  • input用法示例(注意input里面的提示语一定要加引号'')
>>> word = input(please input something:)
  File "<stdin>", line 1
    word = input(please input something:)
                            ^
SyntaxError: invalid syntax
>>> word = input('please input something:')
please input something:god
>>> x = 'ttt'
>>> print(x + word)
tttgod

0x04 字符串操作

  • 字符串可以直接用+连接
>>> 'good'+"good"
'goodgood'
  • 数字在加引号以后也是按照字符串来处理
>>> '2'+'2'
'22'
>>> 1+'2'+3+'4'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • 字符串在print 函数里面*就是打印几倍的关系
>>> print('abc\n'*3)
abc
abc
abc
>>> print('abc'*3)
abcabcabc
  • 单个字母不可以*也不可以+
>>> print(a*3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
  • 在print函数里面数字的*就是*的关系来处理
>>> print(4*3)
12
>>> 4*'222'
'222222222222'
>>> 4*'abc'
'abcabcabcabc'
  • 不可以用浮点型来进行*操作
>>> 4.0*'abc'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
  • 字符串与字符串*操作无效
>>> '17'*'21'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
  • 在print函数里面+操作是无效的,不属于标准输入
>>> print('abc'+3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> print(a+3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
  • 在print函数里面字符串可以相加
>>> print('abc'+'3')
abc3

0x05 变量

  • 变量可以写在print里面
>>> x=7
>>> print(x)
7
>>> print(x+3)
10
>>> print(x)
7
  • 字符串加双引号赋值变量
>>> x = cde
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cde' is not defined
>>> x = "cde"
>>> print(x * 3)
cdecdecde
>>>
  • 同名变量被覆盖写入
>>> x = 123
>>> print(x)
123
>>> x = 'abc'
>>> print(x)
abc
  • 变量名称
  • python中的名字只能以包含 字母,数字,下划线,且不能以数字开头
  • python的变通是通过名称来占位的不用的可以用del删掉
>>> foo = 'avc'
>>> foo
'avc'
>>> del foo
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
  • pyhon支持 in-place操作如下
>>> x = 1
>>> x +=1
>>> x
2
>>> x = 'abc'
>>> x +='fgd'
>>> x
'abcfgd'

0x06 格式化数据

  • 常用的 int() str() float()
>>> x = 5
>>> y = x + 3
>>> y = int(str(y) + '2')
>>> print(y)
82
>>> float(y)
82.0

0x07 布尔值

  • python里面的布尔值有两种 True和False
>>> my_abc = True
>>> my_abc
True
>>> 2 == 3
False
>>> 1 != 1
False
>>> 'abc' != "cc"
True
>>> 5 > 3
True
>>> 5 > 5
False
>>> 5 >= 5
True
>>> 5 <= 5
True
>>> 5 <= 5.0
True

0x08 if控制流

  • if语句的格式
if 判断条件:
[tab]执行的内容
cat test2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if 10 > 5:
  print('good')
print('end it')
./test2.py
good
end it
>>> num = 12
>>> if num > 5:
...     print("Bigger than 5")
...     if num < 47:
...             print("Between 5 and 47")
...
Bigger than 5
Between 5 and 47
>>> num = 7
>>> if num == 5:
...   print("Number is 5")
... else:
...   if num == 11:
...     print("Number is 11")
...   else:
...     if num == 7:
...       print("Number is 7")
...     else:
...       print("Number isn't 5, 11 or 7")
...
Number is 7
>>> num = 7
>>> if num == 5:
...    print("Number is 5")
... elif num == 11:
...    print("Number is 11")
... elif num == 7:
...    print("Number is 7")
... else:
...    print("Number isn't 5, 11 or 7")
...
Number is 7

0x0A 布尔逻辑

  • 与and 或or 非not
>>> 1 == 1 and 2 == 2
True
>>> 1 == 1 and 2 == 3
False
>>> 1 != 1 and 2 == 2
False
>>> 2 < 1 and 3 >  6
False
>>> 1 == 1 or 2 == 2
True
>>> 1 == 1 or 2 == 3
True
>>> 1 != 1 or 2 == 2
True
>>> 2 < 1 or 3 >  6
False
>>> not 1 == 1
False
>>> not 1 > 7
True

0x0B while循环

  • 正常的循环
>>> i = 1
>>> while i <= 5:
...     print(i)
...     i +=1
...
1
2
3
4
5
  • 死循环
>>> while 1 == 1:
...     print("good")
...
good
good
good
good
good
good
good
good
>>> while True:
...     print("good")
...
good
good
good
good
good
good
good
good
  • break跳出循环
➜  python cat test2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
i = 1
while 1 == 1:
    print(i)
    i = i+1
    if i >= 5:
        print('Breaking')
        break
print('Finished')
➜  python ./test2.py
1
2
3
4
Breaking
Finished
  • continue 跳回本次循环而不退出
➜  test cat test2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
i = 0
while True:
    i = i+1
    if i == 2:
        print('Skiping 2')
        continue
    if i >= 5:
        print('Breaking')
        break
    print(i)
print('Finished')
➜  test ./test2.py
1
Skiping 2
3
4
Breaking
Finished

0x0C 列表 []

  • 列表中的元素从0开始计数,下例中的words是列表的名字,[]中的内容标识的是元素的位置
>>> words = ['abc','bcd','!']
>>> print(worlds[0])
abc
>>> print(worlds[1])
bcd
>>> print(worlds[2])
!
  • 空的列表用[]来创建
>>> words = []
>>> print(words)
[]
  • 列表里面可以还有列表
>>> nums = 3
>>> things = ['string',0,[1,2,nums],4.56]
>>> print(things[1])
0
>>> print(things[2])
[1, 2, 3]
>>> print(things[2][2])
3
***
  • str可以当作列表来使用,如果用int会引发TypeError
>>> str = "Hello world!"
>>> print(str[8])
r
>>> str = 123
>>> print(str[0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
  • 元素替换
>>> nums = [7,7,7,7,7]
>>> nums[2] = 5
>>> print(nums)
[7, 7, 5, 7, 7]
  • 元素 *操作
>>> nums = [1,2,3]
>>> print(nums + [4,5,6])
[1, 2, 3, 4, 5, 6]
>>> print(nums * 3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
  • 元素布尔
>>> words = ['eggs','spam','sausage','good']
>>> print('egg' in words)
False
>>> print('eggs' in words)
True
>>> print('good' in words)
True
  • 支持not操作
>>> nums = [1,2,3]
>>> print(not 4 in nums)
True
>>> print(4 not in nums)
True
>>> print(not 3 in nums)
False
>>> print(3 not in nums)
False

0x0D range

  • range 默认从0开始,范围-1
>>> numbers = list(range(10))
>>> print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 从这个例子可以看出,实际上是从前一个参数开始,最大数-1
>>> numbers = list(range(3,8))
>>> print(numbers)
[3, 4, 5, 6, 7]
  • 第三个参数代表间隔
>>> numbers = list(range(3,20,2))
>>> print(numbers)
[3, 5, 7, 9, 11, 13, 15, 17, 19]

0x0E loops

  • 循环与列表
>>> words = ['Hello','world','!','good']
>>> counter = 0
>>> maxindex = len(words) -1
>>> while counter <= maxindex:
...     word = words[counter]
...     print(word + '?')
...     counter = counter + 1
...
Hello?
world?
!?
good?
  • for loop
>>> words = ['Hello','world','!','good']
>>> for word in words:
...     print(word)
...
Hello
world
!
good

注意格式 要加:

>>> for i in range(5)
  File "<stdin>", line 1
    for i in range(5)
                    ^
SyntaxError: invalid syntax
  • 可以把range与for 结合当做次数来使用
>>> for i in range(5):
...     print("hello")
...
hello
hello
hello
hello
hello

简单计算器

➜  test cat test11.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Fuction calculator
while True:
    print("Options:")
    print("Enter 'add' to add two numbers")
    print("Enter 'subtract' to subtract two numbers")
    print("Enter 'multiply' to multiply two numbers")
    print("Enter 'divide' to divide two numbers")
    print("Enter 'quit' to end the program")
    user_input = input(:)
    if user_input == 'add'
        num1 = float(input("Enter a number:"))
        num2 = float(input("Enter another number:"))
        result = str(num1 +num2)
        print("The answer is " + result)
    elif user_input == 'subtract'
        pass
    elif user_input == 'multiply'
        pass
    elif user_input == 'devide'
        pass
    elif user_input == 'quit'
        break

0x0F 函数

  • 定义一个函数
>>> def print_with_input(word):
...     print(word + '!')
...
>>> print_with_input(good)
  File "<stdin>", line 1
    print_with_input(good)
                         ^
SyntaxError: invalid character in identifier
传递进去的参数要匹配类型,字符串就是字符串
>>> print_with_input("good")
good!
>>>
  • 多个参数传递
>>> def print_sum_twice(x,y):
...     print(x+y)
...
>>> print_sum_twice(6,9)
15
  • 局部变量,全局无效
>>> def fuction(variable):
...     variable +=1
...     print(variable)
...
>>> fuction(10)
11
>>> print(variable)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'variable' is not defined
  • 返回值
>>> def max(x,y):
...     if x>=y:
...             return x
...     else:
...             return y
...
>>> print(max(5,7))
7
>>> z = max(6,8)
>>> print(z)
8
  • return不能在定义的函数之外使用
  • 字符串长短比较
>>> def short_test(x,y):
...     if len(x) >= len(y):
...             return x
...     else:
...             return y
...
>>> short_test('sada','asdasd')
'asdasd'
  • return
    遇到return后立即中止
>>> def add_numbers(x,y):
...     total = x + y
...     return total
...     print("The result is " + str(total))
...
>>> add_numbers(5,9)
14
  • 问题 关于print函数
    无效的句法,问题出在数据类型上
 def add_numbers(x,y):
...     total = x + y
...     return total
...     print("The result is " total)
  File "<stdin>", line 4
    print("The result is " total)
                               ^
SyntaxError: invalid syntax

只有它自己时候是正常的,因为只有一种数据类型

def add_numbers(x,y):
...     total = x + y
...     print(total)
...
>>> add_numbers(5,9)
14

前面字符串+还是字符串

 def add_numbers(x,y):
...     
...     total = x + y
...     print("The result is " + total)
...
>>> add_numbers(5,9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in add_numbers
TypeError: Can't convert 'int' object to str implicitly

0x10 注释

  • 常规方式的 #注释 #以后的内容都是注释
>>> x = 365
>>> y = 7
>>> # This is comment
...
>>> print(x % y) #find the remainder
1
>>> # print (x // y )
...
>>> # another comment
...
>>>
  • 脚本方式
➜  test ./1.py       
1
➜  test cat 1.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
x = 365
y = 7
# This is comment
print(x % y) #find the remainder
# print (x // y )
# another comment
  • 多行注释中间可以用成对儿的3个'''或3个"""
>>> def shout(word):
...     '''
...     Print a word with an
...     exclamation mark following it.
...     '''
...     print(word + "!")
...
>>> shout("good")
good!

0x11 函数作为对象使用

  • 下面的示例中要注意 a b作为参数的数据类型
>>> def multiply(x,y):
...     return x * y
...
>>> a = 4
>>> b = 7
>>> operation = multiply
>>> print(operation(a,b))
28
  • 函数也可以作为其他函数的参数使用
>>> def add(x,y):
...     return x + y
...
>>> def do_twice(func,x,y):
...     return func(func(x,y),func(x,y))
...     """
    本例中中的第二个函数功能作用是调用第一个参数(函数)得出小括号里面的x,y  func(x,y)结果,再发结果继续传递给func作为参数
...     """
>>> a = 5
>>> b = 7
>>> print(do_twice(add,a,b))
24

0x12 模块

  • 模块是别人写好的功能块,最基本的使用方法是在代码的最顶部写入import modules_name,访问模块内部的函数,变量使用.,比如var是modules_name内部的一个函数。那么调用的时候表示为modules.var
>>> import random
>>> for i in range(5):
...     value = random.randint(1,6)
...     print(value)
...
2
4
5
5
6
  • 上例中充分体现了使用模块 中的函数的方法用. 虽然下例中也一样,但是需要注意的是 print函数的位置不一样,python是用tab来标识从属关系的
>>> import random
>>> for i in range(5):
...     value = random.randint(1,6)
...
>>> print(value)
5
  • 引用模块中的单一函数。可以使用from moudule_name import var这样的方法
>>> from math import pi
>>> print(pi)
3.141592653589793
  • 引用多个模块用 from moudule_name import var1,var2
>>> from math import pi
>>> print(pi)
3.141592653589793
>>> from math import pi,sqrt
>>> print(pi)
3.141592653589793
>>> sqrt(4)
2.0
  • from math import * 加入math里面的所有模块这样是不好的,容易内外变量冲突
  • import以后就可以直接用import时候的名字使用,如果没有import就会报未定义的错误
>>> pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
>>> sqrt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
  • import 不存在的modules或拼写错误会报错
>>> import some_modules
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'some_modules'
  • 重命名improt 的module from moudles
>>> from math import sqrt as square_root
>>> print(square_root(100))
10.0
  • pyhton里面主要有3种模块,一种是自己写的,另一种是其他人写好的,直接安装的,最后一种是安装pyhton时候预安装的。最后一种,我们叫做标准库,常用的标准库有 string,re,datetime,math,random,os,multprocessing,subprocess,socket,email,json,doctest,unittest,pdb,argparse,sys
    标准库能够完成,数据解析、数据排序、debug、大数据处理、电子邮件、命令行参数等。一些标准库使用C语言编写,一些使用python。
  • 大部分通用与全平台,有一些是windows、unix特定的。
  • 大部分的第三方模块在PyPI上面,最好的获取方式是使用pip在线安装。pip install library_name pip安装是最标准的方式比较通用于所有系统,也有一写是在windwos下编译好的,优先生成的图形化安装界面。

0x13 异常

  • 出现异常的时候常会有对应的报错通过报错信息即可判断除当前的异常状态。常见的异常状态如下:
    • ImportError an import fails
    • IndexError a list id indexed with an out-of-range number
    • NameError an unknows variable is used
    • SyntaxError the code can't be prased properly
    • TypeError a fuction is called on a value of an inappropriate type
    • ValueError a fuction is called on a value of the correct type,but with an inappropriate value
>>> num1 = 7
>>> num2 = 0
>>> print(num1/num2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> print("4" + 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
  • 异常处理,使用try与except来处理异常。当try里面的代码发生异常时候,except里面买代码被执行。异常不发生,只执行try里面的。
  • 异常处理在用户输入时候特别有用
  • 下例中except 里面定义了错误类型与处理的方法
>>> try:
...     num1 = 7
...     num2 = 0
...     print(num1 / num2)
...     print("Done calculation")
... except ZeroDivisionError:
...     print("An error occurred")
...     print("due to zero division")
...
An error occurred
due to zero division
  • 多个异常处理可以使用()来连接
>>> try:
...     variable = 10
...     print(variable + "hello")
...     print(variable / 2)
... except ZeroDivisionError:
...     print('Divided by zero')
... except(ValueError,TypeError):
...     print('Error occurred')
...
Error occurred
  • except 不标识错误类型会识别所有错误类型,这要小心,识别的范围太广,代码将无法运行。
>>> try:
...     word = "spam"
...     print(word / 0)
... except:
...     print("An error occurred" )
...
An error occurred
  • finally 无乱如何都会运行的一个语句,写在 try/except 底部。
>>> try:
...     print("Hello")
...     print(1 / 0)
... except ZeroDivisionError:
...     print('Divided by zero')
... finally:
...     print("This code will run no mattwe what")
...
Hello
Divided by zero
This code will run no mattwe what
  • 前一个未捕获的异常也会触发finally(问题出在except那句的print没有‘’)
>>> try:
...     print("Hello")
...     print(1 / 0)
... except ZeroDivisionError:
...     print(Divided)
... finally:
...     print("This code will run no mattwe what")
...
Hello
This code will run no mattwe what
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
NameError: name 'Divided' is not defined
  • raise可以引发异常
>>> raise ValueError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError
>>> try:
...     print(1 / 0)
... except ZeroDivisionError:
...     raise ValueError
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError
>>> name = 123
>>> raise NameError("invalid name!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: invalid name!
  • raise可以用来重新引发异常
>>> try:
...     num = 5 / 0
... except:
...     print("An error occurred")
...     raise
...
An error occurred
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
  • assert 断言;assert是一个严格判断条件,条件判断错误,引发异常。断言通过assert引发。
>>> print(1)
1
>>> assert 2 + 2 == 4
>>> print(2)
2
>>> assert 2 + 2 == 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
  • assert 断言可以接受第二个参数,但是需要注意断言引发的异常如果不处理将中止整个程序。
>>> temp = -10
>>> assert(temp >= 0),"Cloder than absolute zero!"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Cloder than absolute zero!
>>> temp = -10
>>> assert(temp <= 0),"Cloder than absolute zero!"
  • 程序员常用的技巧是在函数开始的部分加入断言检查输入是否有效,然后在函数调用后检查是否有效输出

0x14 文件读操作

  • python可以非常简单的处理文件,文件在被编辑或读取之前需要先open
  • open参数里面写的是文件的path 如果文件和程序是同级目录,直接写文件名即可
myfile = open("filename.txt")
  • 打开文件时候添加第二个参数可以改变文件打开的方式
    • r 只读
    • w 写入
    • a 追加
    • b 以二进制方式打开
# write mode
myfile = open("filename.txt","w")
# read mode
myfile = open("filename.txt","r")
myfile = open("filename.txt")
# binary write mode
myfile = open("filename.txt","wb")
  • 文件打开后必须要close
file = open("filename.txt","w")
# do something
file.close()
  • 文档类型的文件能够用read模式打开
file = open("filename.txt","w")
count = file.read()
print(count)
file.close()
  • 给read加参数,读取指定长度
>>> file = open("/home/ivo/test/python_phone/book","r")
>>> for i in range(5):
...     print(file.read(8))
...
“Neurons
 are the
 informa
tion-pro
cessing
>>> for i in range(5):
...     print(file.read(3))
...
uni
ts
in
the
 br
>>> for i in range(5):
...     print(file.read(20))
...
ain, and the cerebra
l cortex is the part
 of the brain that c
an combine informati
on from different so
  • 文件前部分被加参数的读取过没close时候,不加参数读取剩余部分
>>> print(file.read())
urces and create new associations, recognize patterns, make decisions to act differently based on past experience and start making predictions for the future," Suzana Herculano-Houzel, the Vanderbilt professor who developed the method for measuring neurons, told ABC News.
  • 什么都不加只读取一次那么是读取文件整体的。
>>> file = open("/home/ivo/test/python_phone/book","r")
>>> print(file.read())
“Neurons are the information-processing units in the brain, and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations, recognize patterns, make decisions to act differently based on past experience and start making predictions for the future," Suzana Herculano-Houzel, the Vanderbilt professor who developed the method for measuring neurons, told ABC News.
  • 读完一次再读,那么会返回一个空的string
>>> file = open("/home/ivo/test/python_phone/book","r")
>>> print(file.read())
“Neurons are the information-processing units in the brain, and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations, recognize patterns, make decisions to act differently based on past experience and start making predictions for the future," Suzana Herculano-Houzel, the Vanderbilt professor who developed the method for measuring neurons, told ABC News.
>>> print(file.read())
  • 获取文件中的字符长度
>>> file = open("/home/ivo/test/python_phone/book","r")
>>> str = file.read()
>>> print(len(str))
429
  • 以行为单位处理文件,readlines()方法
>>> file = open("/home/ivo/test/python_phone/book","r")
>>> print(file.readlines())
['"Neurons are the information-processing units in the brain, \n', 'and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations, \n', 'recognize patterns,\n', ' make decisions to act differently based on past experience and start making predictions for the future,\n', '" Suzana Herculano-Houzel, \n', 'the Vanderbilt professor who developed the method for measuring neurons, \n', 'told ABC News.\n']
  • 用for 循环来实现文件的单行处理
>>> file = open("/home/ivo/test/python_phone/book","r")
>>> for line in file:
...     print(line)
...
"Neurons are the information-processing units in the brain,
and the cerebral cortex is the part of the brain that can combine information from different sources and create new associations,
recognize patterns,
 make decisions to act differently based on past experience and start making predictions for the future,
" Suzana Herculano-Houzel,
the Vanderbilt professor who developed the method for measuring neurons,
told ABC News.
>>>
  • 输出行的时候是用空格来进行分割的,最后自动添加的换行符

0x15 文件写操作

  • 文件写入,写入时候是新文件,所以文件不存在没关系,不会报错
>>> file = open("/home/ivo/test/python_phone/word","w")
>>> file.write("This has been written to a file")
31
>>> file.close()
>>> file = open("/home/ivo/test/python_phone/word","r")
>>> print(file.read())
This has been written to a file
>>> file.close()
  • 文件写入的时候之前的内容会被覆盖
>>> file = open("/home/ivo/test/python_phone/word","r")
>>> print(file.read())
This has been written to a file
>>> file.close()
>>> file = open("/home/ivo/test/python_phone/word","w")
>>> file.write("Some new text")
13
>>> file.close()
>>> file = open("/home/ivo/test/python_phone/word","r")
>>> print(file.read())
Some new text
>>> file.close()
  • 文件一旦被w模式打开里面的内容就会被删除
>>> file = open("/home/ivo/test/python_phone/word","r")
>>> print(file.read())
Some new text
>>> file.close()
>>> file = open("/home/ivo/test/python_phone/word","w")
>>> file.close()
>>> file = open("/home/ivo/test/python_phone/word","r")
>>> print(file.read())
  • write模式下返回的字符是写操作成功的标志指的是写入了多少字符或者可以表示为file.write(msg) == len(msg)
>>> msg = "Hello world"
>>> file = open("/home/ivo/test/python_phone/word","w")
>>> amount_written = file.write(msg)
>>> print(amount_written)
11
>>> file.close()
  • 为避免资源浪费在操作文件后确认它关闭是一个好的习惯。可以用try finally来实现
>>> file = open("/home/ivo/test/python_phone/word","w")
>>> file.write("good is good")
12
>>> file.close()
>>> try:
...     file = open("/home/ivo/test/python_phone/word","r")
...     print(file.read())
... finally:
...     file.close()
...
good is good
  • 即使中间出错了 try也会close
  • with as方式打开文件
>>> with open("/home/ivo/test/python_phone/word") as f:
...     print(f.read())
...
good is good
  • 使用with是自动close的,with结束,close结束。即使中间发生错误

0x16 None

  • None是用来表示缺少的值,类似于其他与引种的null。像其他的空值,比如 0, [],空字符串转换成布尔值都是False。在python里面输入,它显示为空字符串
>>> None == None
True
>>> None
>>> print(None)
None
  • None对象在函数中用于返回任何不明确的意义
>>> def some_fun():
...     print("Hi!")
...
>>> var = some_fun()
Hi!
>>> print(var)
None
>>> foo = print()
>>> if foo == None:
...     print(1)
... else:
...     print(2)
...
1

0x17 Dictionaries 字典

  • 字典是一种数据结构,map keys to values.list 可以理解为一种特殊的字典,字典与list有相同的索引方式,[ ]
>>> ages = {"Dave":24,"Mary":42,"John":58}
>>> print(ages["Dave"])
24
>>> print(ages["John"])
58
  • 键入一个没有的index keys,会报KeyError
>>> primary = {
...     "red":[255,0,0],
...     "green":[0,255,0],
...     "blue":[0,0,255]
... }
>>> print(primary[red])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'red' is not defined
#key有""
>>> print(primary["red"])
[255, 0, 0]
>>> print(primary["yellow"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'yellow'
>>> test = {}
>>> print(test[0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0
  • 只有不可变的对象才能当作key使用。
>>> bad_dict = {
...     [1,2,3]:"one two three"
... }
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: unhashable type: 'list'
  • 字典中的操作,替换值添加值
>>> squares = {1:1,2:4,3:"error",4:16}
>>> squares[8] = 125
>>> squares[3] = 68
>>> print(squares)
{8: 125, 1: 1, 2: 4, 3: 68, 4: 16}
>>> print(squares)
{8: 125, 1: 1, 2: 4, 3: 68, 4: 16}
>>> print(squares[squares[1]])
1
  • 使用in或not in 来确定key是否在字典中
>>> nums = {
...     1:"one",
...     2:'two',
...     3:'three'
... }
>>> print(1 in nums)
True
>>> print(5 in nums)
False
>>> print(5 not in nums)
True
  • 字典中一个常用的方法是get,它像index一样,但出现不存在的key的时候会返回特殊的值,默认为None
>>> pairs = {1:'apples',
...     'orange':[1,2,4],
...     True:False,
...     None:'True'
... }
>>> print(pairs.get('orange'))
[1, 2, 4]
>>> print(pairs.get(7))
None
>>> print(pairs.get('apples'))
None
>>> print(pairs.get(12345,"not in dictionary"))
not in dictionary
>>> fib = {1:1,2:1,3:2,4:3}
>>> print(fib.get(4,0) + fib.get(7,5))
8
#get(4,0) return 3       get(7,5) because 7 not exist so return 5
  • 字典中的每一个元素都是由 key:value来表示
  • 创建空字典用{}

0x18 tuples 元祖

  • tuples与list极其相似,tuples是不可变的。它用()创建
>>> words = ('spam','eggs','sausages')
>>> print(words[0])
spam
>>> words[0] = 'good'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
  • tuples可以不用()创建,只要将values用,隔开即可
>>> words = 'spam','eggs','sausages'
>>> print(words[0])
spam
  • 创建一个空的tuple用()
tpl = ()
>>> tpl = (1,(1,2,3))
>>> print(tpl[1])
(1, 2, 3)
>>> print(tpl[1][0])
1
>>> print(tpl[1][1])
2
>>> print(tpl[1][2])
3
>>> print(tpl[1][2][0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
  • tuples are faster than list,but they cannot be change
  • tuples与list dictionary 一样都能够被互相嵌套

0x19 list slices 切片

  • list slices是一种高级的list操作。写法是中括号中用:隔开的两个整数
>>> squares = [0,1,4,9,16,25,36,47,64,81]
>>> print(squares[2:6])
[4, 9, 16, 25]
>>> print(squares[3:8])
[9, 16, 25, 36, 47]
>>> print(squares[0:1])
[0]
# 第一个index的数包含在里面,第二个没有。和range一样
  • 第一个数被省略的话从头开始算,第二个省略的话从数到尾
>>> squares = [0,1,4,9,16,25,36,47,64,81]
>>> print(squares[:4])
[0, 1, 4, 9]
>>> print(squares[4:])
[16, 25, 36, 47, 64, 81]
  • slicing 在tuple上面也能使用
  • slices 可添加3个参数,第3个参数代表step
>>> squares = [0,1,4,9,16,25,36,47,64,81]
>>> print(squares[::2])
[0, 4, 16, 36, 64]
>>> print(squares[2:8:2])
[4, 16, 36]
>>> print(squares[2:8:3])
[4, 25]
>>> print(squares[2:8:4])
[4, 36]
>>> print(squares[2:8:5])
[4, 47]
>>> print(squares[2:8:6])
[4]
  • slices中的负数代表从list的尾部算
>>> squares = [0,1,4,9,16,25,36,47,64,81]
>>> print(squares[1:-1])
[1, 4, 9, 16, 25, 36, 47, 64]
>>> print(squares[1:-2])
[1, 4, 9, 16, 25, 36, 47]
>>> print(squares[-5:-2])
[25, 36, 47]
  • slice中step的负数,代表向后完成,通常用[::-1]反转list
>>> squares = [0,1,4,9,16,25,36,47,64,81]
>>> print(squares[::-1])
[81, 64, 47, 36, 25, 16, 9, 4, 1, 0]
>>> print(squares[::-2])
[81, 47, 25, 9, 1]
>>> print(squares[::-5])
[81, 16]
>>> print(squares[7:2:-2])
[47, 25, 9]
>>> print(squares[7:2:-3])
[47, 16]

0x1A List comprehension 列表推导式

  • 列表推导式,是一种快速的根据规则来创建列表的方式
>>> cubes = [i**3 for i in range(5)]
>>> print(cubes)
[0, 1, 8, 27, 64]
  • 列表推导式,里面可以包含if语句
>>> evens=[i**2 for i in range(10) if i**2 % 2 == 0]
>>> print(evens)
[0, 4, 16, 36, 64]
Create a list of multiples of 3 from 0 to 20.
a = [i for i in range(20) if i%3 ==0]
  • 列表推导式如果用于创造一个巨大的range会导致MemoryError,这也并非无解后面会提到
even = [2*i for i in range(10**100)]
创建一个range 5-9 x10的list
a = [x*10 for x in range(5,9)]

0x1B String Formatting 格式化

前面已经将非格式化的字符串,格式化成了字符串。在python里面还提供了一种更强大的方法把非string0的对象嵌入到str中。
- 每个参数的格式函数放在字符串在相应的位置,这是决定使用花括号{ }。

>>> nums = [4, 5, 6]
>>> msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
>>> print(msg)
Numbers: 4 5 6
  • 格式化字符串可以用名称作为参数
>>> a = "{x}, {y}".format(x=5, y=12)
>>> print(a)
5, 12
>>> str="{c}, {b}, {a}".format(a=5, b=9, c=7)
>>> print(str)
7, 9, 5

0x1C Useful Functions 常用的str函数

  • 在日常的任务中,python有很多内置的函数与方法
join(sub) - 以字符串为分隔符,插入到sub中私有的字符之间
replace(old,new) - 旧的字符串替换成新的
startswith and endswith - 确定字符串的开始,结束是否正确
lower and upper 大小写
分割方法相反的加入,将某个分隔符字符串转化为一个列表。 
print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"
print("Hello ME".replace("ME", "world"))
print("This is a sentence.".startswith("This"))
# prints "True"
print("This is a sentence.".endswith("sentence."))
# prints "True"
print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."
print("AN ALL CAPS SENTENCE".lower())
#prints "an all caps sentence"
print("spam, eggs, ham".split(", "))
#prints "['spam', 'eggs', 'ham']"
  • 数值函数
max min - 最大值,最小值
abs - 绝对值
round - 取整数 3.5 的3, 4.1的4
sum - 求和
>>> print(round(5.14159265))
5
>>> print(min(1, 2, 3, 4, 0, 2, 1))
0
>>> print(max([1, 4, 9, 2, 5, 6, 8]))
9
>>> print(abs(-99))
99
>>> print(abs(42))
42
>>> print(sum([1, 2, 3, 4, 5]))
15
  • list可以作为参数来使用。返回是True。enumerate函数是枚举,遍历值的同时加标签
>>> nums = [55, 44, 33, 22, 11]
>>> 
>>> if all([i > 5 for i in nums]):
...    print("All larger than 5")
... 
All larger than 5
>>> if any([i % 2 == 0 for i in nums]):
...    print("At least one is even")
... 
At least one is even
>>> for v in enumerate(nums):
...    print(v)
... 
(0, 55)
(1, 44)
(2, 33)
(3, 22)
(4, 11)
>>> nums = [-1, 2, -3, 4, -5]
>>> if all([abs(i) < 3 for i in nums]):
...   print(1)
... else:
...   print(2)
... 
2
  • Text Analyzer 文本分析
这是一个例子项目,显示程序,分析样本文件来查找文本每个字符占用的百分比。
test
Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcenfr fv orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabthu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orgnf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba bg thrff.
Gurer fubhyq or bar-- naq cersrenoylbayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arrire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!
>>> def count_char(text,char):
...     count = 0
...     for c in text:
...             if c == char:
...                     count += 1
...     return count
... 
>>> filename = input("Enter a filename:")
Enter a filename:/home/ivo/test
>>> with open(filename) as f:
...     text = f.read()
... 
>>> print(count_char(text,"r"))
83
def count_char(text, char):
    count = 0
    for c in text:
        if c == char:
            count += 1
    return count
file = open("newfile.txt", "w")
file.write("""Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcenfr fv orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabthu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orgnf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba bg thrff.
Gurer fubhyq or bar-- naq cersrenoylbayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arrire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""")
file.close()
filename = "newfile.txt"
with open(filename) as f:
    text = f.read()
for char in "abcdefghijklmnopqrstuvwxyz":
    perc = 100 * count_char(text, char) / len(text)
    print("{0} - {1}%".format(char, round(perc, 2)))
#perc 是得到小数点
#round 取小数点2位
#format char round 对应0 - 1
>>> nums = (55, 44, 33, 22)
>>> print(max(min(nums[:2]), abs(-42)))
44
>>> print(nums[:2])
(55, 44)

0x1D Functional Programming 函数式编程

  • 函数式编程是一种编程风格,函数式编程的关键部分是高阶函数。之前讲的都是函数作为对象来使用。
  • 高阶函数将其他函数作为参数,或将其作为结果返回。
def apply_twice(func, arg):
   return func(func(arg))
def add_five(x):
   return x + 5
print(apply_twice(add_five, 10))
>>>
20
add_five(add_five(10))
add_five(15)
>>>
20
  • lambdas 快速的创建一个函数,不用def的方式
def my_func(f, arg):
  return f(arg)
my_func(lambda x: 2*x*x, 5)
  • lambdas 没有def的函数功能强大,它只能坐一些简单的处理,用一行代码来处理
#named function
def polynomial(x):
    return x**2 + 5*x + 4
print(polynomial(-4))
#lambda
print((lambda x: x**2 + 5*x + 4) (-4))
double = lambda x: x * 2
print(double(7))
  • 可以将lambda函数分配给变量,并像普通函数一样使用。(但是通常不会这样用)
double = lambda x: x * 2
print(double(7))
  • map映射
映射和过滤器是非常有用的内建高阶函数。函数映射接受一个函数和一个迭代器作为参数,并返回一个新的迭代器,该函数应用于每个参数。
>>> def add_five(x):
...   return x + 5
... 
>>> nums = [11, 22, 33, 44, 55]
>>> result = list(map(add_five, nums))
>>> print(result)
[16, 27, 38, 49, 60]
#同样可以用lambda来实现
>>> nums = [11,12,15,15,18]
>>> result = list(map(lambda x: x+7,nums))
>>> print(result)
[18, 19, 22, 22, 25]
#list是将结果转化为列表
  • filter,过滤器通过布尔值的返回去过滤掉那些不匹配的项
>>> nums = [11, 22, 33, 44, 55]
>>> res = list(filter(lambda x: x%2 == 0,nums))
>>> print(res)
[22, 44]
  • generators 生成器是一种可迭代的类型,如列表或元组。
与列表不同,它们不允许使用任意索引进行索引,但它们仍然可以通过for循环迭代。它们可以使用函数和yield语句来创建。
yield语句用于定义一个生成器,替换函数的返回值以向调用者提供结果而不破坏局部变量。
>>> def countdown():
...     i = 5
...     while i > 0:
...             yield i
...             i = i - 1
... 
>>> for i in countdown():
...     print(i)
... 
5
4
3
2
1
由于它们一次产生一个项目,因此生成器不具有列表的内存限制。实际上生成器是无限的,简而言之,生成器允许你声明一个像迭代器一样的函数,即它可以在for循环中使用。
def infinite_sevens():
  while True:
    yield 7        
for i in infinite_sevens():
  print(i)
>>>
7
7
7
7
7
7
7
...
有限生成器可以通过将它们作为参数传递给列表函数来转换为列表。使用生成器可以提高性能,这是惰性(按需)生成值的结果,这意味着更低的内存使用率。此外,我们不需要等到所有元素都已经生成,然后再开始使用它们。
def numbers(x):
  for i in range(x):
    if i % 2 == 0:
      yield i
print(list(numbers(11)))
What is the result of this code?
def make_word():
  word = ""
  for ch in "spam":
    word +=ch
    yield word
print(list(make_word()))
['s', 'sp', 'spa', 'spam']
  • Decorators 装饰器
装饰器提供了一种使用其他函数修改函数的方法。当您需要扩展您不想修改的功能的功能时,这非常理想。
>>> def decor(func):
...   def wrap():
...     print("============")
...     func()
...     print("============")
...   return wrap
... 
>>> def print_text():
...   print("Hello world!")
... 
>>> decorated = decor(print_text)
>>> decorated()
============
Hello world!
============
我们定义了一个名为decor的函数,它具有单个参数func。在内部装饰中,我们定义了一个名为wrap的嵌套函数。wrap函数将打印一个字符串,然后调用func()并打印另一个字符串。decor函数返回包装函数作为其结果。我们可以说变量装饰是print_text的装饰版本 - 它是print_text加上一些东西。实际上,如果我们写了一个有用的装饰器,我们可能想要将print_text完全替换为装饰版本,所以我们总是得到print_text的“plus something”版本。这是通过重新分配包含我们的函数的变量来完成的
print_text = decor(print_text)
print_text()
在我们之前的例子中,我们通过用包装版本替换包含函数的变量来修饰我们的函数。
>>> def print_text():
...   print("Hello world!")
... 
>>> print_text = decor(print_text)
这个模式可以随时用于包装任何功能。python通过预先用装饰器名称和@符号预先定义函数定义来支持在装饰器中包装函数。如果我们正在定义一个函数,我们可以使用@符号来“装饰”它:
@decor
def print_text():
  print("Hello world!")
一个函数可以有多个装饰器。
my_func = my_dec(my_func)
上一篇
下一篇