python basic

所有尖括号包含的内容 如<your_user_name>等均需根据实际情况进行适当替换

安装

windows

下载,打开页面后选择Latest Python 3 Release,新出现的页面拉到最下面点击Windows x86-64 executable installer(64位平台的可执行安装包),下载。

mac

下载,打开页面后选择Latest Python 3 Release,新出现的页面拉到最下面点击macOS 64-bit installer(64位平台的可执行安装包),下载。

安装时

注意:
推荐勾选install launcher for all users,这样python路径的位置在C:\Program Files下,易于查找。
推荐勾选add python to path,软件会自动帮你解决环境变量的问题。
选择install now进行安装。

区分cmd与repl

使用python最常见的形式为打开cmd(按win+r输入cmd),

在这时,出现的形似C:\Users\<your_user_name>为cmd接受命令的地方

输入Python

形似

  1. Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>>

为交互式解释器,英文名REPL(Read-Eval-Print Loop),在这里,每输入一行代码,按enter即可运行,然后再输入代码,再运行,为循环。

运行

打开一个文件,写入print('hello word!'),保存为temp.py,在cmd输入python <path_to_temp.py>即可运行该文件

安装包

使用pip进行包的安装,pip命令需要在cmd输入,安装时代码为

  1. pip install requests

安装结果

安装结束出现success,即为安装成功,在repl中import ,无错误即为成功

可能的错误类型
timeouterror 网络不好
No matching distribution found for 包名输入错误

区分中英文字符

英文为半角字符,较窄,例如 !@#$%^&*()_+{}|:"<>?

中文为全角字符,较宽,例如 !@#¥%……&*()——+{}|:“《》?

编程中请一律使用半角字符,一般输入法按shift切换,字符错误执行后一般出现syntaxerror,意为语法错误

字符串中可以包裹中文字符

  1. # line一般显示错误行或其上一行的行号,小箭头提示了错误的位置
  2. print('hello world'
  1. File "<ipython-input-1-84a98577e6bb>", line 2
  2. print('hello world'
  3. ^
  4. SyntaxError: invalid character in identifier
  1. # IndentationError意为缩进错误,python以缩进区分代码块,def内部定义函数,函数内部的代码为一个代码块,因此应当有相同的缩进。
  2. def some_function():
  3. print('some')

使用python

让我们开始基础学习吧,学习部分在repl中进行.

使用命令quit()可退出repl

repl特点

使用_可以获得上行代码输出值,使用方向键盘上下键获取之前运行过的代码,在repl中,直接输入变量即可输出,输出默认调用repr函数

  1. >>> a = 1
  2. >>> a
  3. 1
  4. >>> _
  5. 1

了解你的python

  1. import sys # import导入库
  2. print(sys.executable) # 获得python位置
  1. D:\ProgramData\Miniconda3\python.exe
  1. import keyword
  2. print(keyword.kwlist) # 不能使用keywords中的名字作为变量名,会覆盖原有变量含义
  1. ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

变量

变量命名以字母或_开头,可包含字母、数字、_

  1. 1a = 10
  1. File "<ipython-input-5-1be9f8edb7cd>", line 1
  2. 1a = 10
  3. ^
  4. SyntaxError: invalid syntax
  1. a = 1 # 整数int
  2. a = 1.1 # 浮点数float
  3. a = 1+1j # 复数complex
  4. a = True # 逻辑bool
  5. a = False
  6. a = None # 空值
  7. a = "sssimon yang" # 字符串
  8. a = b = c = 1 # 连环赋值
  9. PI = 3.14159265359 # 全大写变量认为是常量
  1. a = 1
  2. a += True # True为1,a+=True等同a=a+True,没有a++
  3. print(a)
  1. 2
  1. a = 1+1j
  2. print(type(a)) # 使用type可以获知其类型
  1. <class 'complex'>
a = 1
b = 2  # 两行代码使用;可以写在一行
a, b, c = 1, 2, "sssimon yang"  # 对应赋值,此处前后均为元组
a, b, c  # 以()包裹的多值为元组,其值不可变
(1, 2, 'sssimon yang')
a = 'ABC'
b = a
a = 'XYZ'
print(b)  # 基本类型a不影响b,其他复杂类型可能传递引用
del a  # 删除变量
ABC
print('i\'m sssimon yang')  # '用于包裹字符串,因此在正常使用时使用\转义
print("i'm sssimon yang")  # 使用"包裹字符串,'无需转义
print("  \\   \n  \"")  # \使用\\正常输出,换行符为\n
print(r"  \\   \n  \"")  # 字符串前缀r表示内部无需转义,按原样输出
i'm sssimon yang
i'm sssimon yang
  \   
  "
  \\   \n  \"
print("hello \
     guys")  # 代码换行使用\
print(1 +
      2 +
      3)
print("""hello
world""")
print('''hello
world''')  # 长字符串使用'''或"""包裹
hello      guys
6
hello
world
hello
world
"""hello
world"""
'hello\nworld'
print(repr("""hello
world"""))  # 上面的输出实际上调用的是repr函数,repr函数的输出带了引号和\n,是该变量的原始模型,而print去掉了引号,是可读性更好输出
'hello\nworld'
print(100, 200)
print(100, end=',')
print(200)  # 正常print最后会加\n,即end默认值为'\n',指定end使两次print输出到了一行
100 200
100,200

每次都在原位置输出

for i in range(100):
    print(f'\r{i}', end='', flush=True)
99
print(0o100)  # 100为8进制的100,print后以10进制输出
print(0x100)  # 100为16进制的100,print后以10进制输出
64
256

数值运算

print(10/3)  # 正常除
print(10//3)  # 整除
print(10 % 3)  # 余
print(10**3)  # 幂
3.3333333333333335
3
1
1000
round(3.33333, ndigits=3)
3.333

逻辑运算

print(None)
print(True)
print(False)  # 内置逻辑变量
print(1 > 2)
print(1 > 2 or True)  # 或|
print(1 > 2 and True)  # 或&
print(1 > 3 & True)
print([] and 2)  # 逻辑运算,短路运算
print(2 and [])
print(100 & 200)  # 此时为位运算
None
True
False
False
True
False
False
[]
[]
64
print(5 > 3 and -1 > 1)
# 或者这样
print(1 < 3 < 5)
print(not 2 == 1)
a = None
print(a is None)  # 鉴定None推荐使用 is 比较的是
False
True
True
True

数据结构

列表list 元组tuple 字典dict 集合set(用于集合运算)

a = [1, 2, 3, 4]
print(a)
a = (1, 2, 3, 4)
print(a)
a = dict(a=1, b=2, c=3, d=4)  # 键值对
print(a)
a = set([1, 2, 3, 4, 1, 2, 3])  # set里非重复
print(a)
[1, 2, 3, 4]
(1, 2, 3, 4)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{1, 2, 3, 4}

序列

字符串,列表,元组都是序列(集合不能进行类似序列取值),列表和元组可以包含任意值,元组不可变,第一个值的索引为1,最后一个值的索引为-1

序列操作

a = [1, 1, 2, 3, 4, 2, 3, 4, 5]  # 定义列表
print(len(a))  # 仅以列表做示范,序列均可进行这些操作
print(a[3])
print(a[-2])
print(a[1:5])  # 左闭右开
print(a[1:5:2])  # 左闭右开步进2
print(a[5:1:-1])  # 步进-1,倒着产生
print(a[2:])  # 一直到末尾
print(a[:4])  # 从开头到索引4
print(a[:])
print(a[::-1])  # 反转
print(a+[1, 2, 3])  # 同类型+可以直接连接
print('sssimon'+' '+'yang')
print(a*3)  # 同类型用*连接多次
print('sssimon'*3)
print(1 in a)  # in 查询是否在其中
print(10 not in a)
print('sss' in 'sssimon')
9
3
4
[1, 2, 3, 4]
[1, 3]
[2, 4, 3, 2]
[2, 3, 4, 2, 3, 4, 5]
[1, 1, 2, 3]
[1, 1, 2, 3, 4, 2, 3, 4, 5]
[5, 4, 3, 2, 4, 3, 2, 1, 1]
[1, 1, 2, 3, 4, 2, 3, 4, 5, 1, 2, 3]
sssimon yang
[1, 1, 2, 3, 4, 2, 3, 4, 5, 1, 1, 2, 3, 4, 2, 3, 4, 5, 1, 1, 2, 3, 4, 2, 3, 4, 5]
sssimonsssimonsssimon
True
True
True

列表

a = [1, 1, 2, 3, 4, 2, 3, 4, 5]
print(a.append(5))  # 在a本身上加了一个5,无返回值,所以相当于返回None
print(a)
print(a.insert(1, 5))  # 索引1处添加5
print(a)
print(a.pop())  # 去除最后一位值并返回
print(a.pop(3))  # 去除索引1处值并返回
print(a)
a[1] = 4  # 修改
print(a)
a[2:5] = []  # 删除
print(a)
del a[2]
print(a)
print(a.extend([1, 2, 3]))  # 原地延长,优于+
print(a)
None
[1, 1, 2, 3, 4, 2, 3, 4, 5, 5]
None
[1, 5, 1, 2, 3, 4, 2, 3, 4, 5, 5]
5
2
[1, 5, 1, 3, 4, 2, 3, 4, 5]
[1, 4, 1, 3, 4, 2, 3, 4, 5]
[1, 4, 2, 3, 4, 5]
[1, 4, 3, 4, 5]
None
[1, 4, 3, 4, 5, 1, 2, 3]
a = [1, 1, 2, 3, 4, 2, 3, 4, 5]
print(a.sort())  # 无返回值,不能用于元组,字符串
print(a)  # 原地改变
print(sorted(a))  # 返回排序后的,可用于元组
None
[1, 1, 2, 2, 3, 3, 4, 4, 5]
[1, 1, 2, 2, 3, 3, 4, 4, 5]
a = (1, 2, 3)
a.sort()
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-26-fb55e2d9fa08> in <module>
      1 a = (1, 2, 3)
----> 2 a.sort()


AttributeError: 'tuple' object has no attribute 'sort'
print(sorted('sssimon yang'))  # 排序按ascii码
print(sorted((1, 2, 3)))
[' ', 'a', 'g', 'i', 'm', 'n', 'n', 'o', 's', 's', 's', 'y']
[1, 2, 3]
a = [10, 4, 3, 1, 74, 23]
a.reverse()  # 反转
print(a)
a = [10, 4, 3, 1, 74, 23]
print(list(reversed(a)))
[23, 74, 1, 3, 4, 10]
[23, 74, 1, 3, 4, 10]

字符串

a = 'sssimon yang'
print(a.split(" "))  # 使用空格分割
['sssimon', 'yang']

编码

print('包含中文的str')
x = b'ABC'  # 表示这是bytes
x = "ABC"  # 这是string
print('中文'.encode('utf-8'))  # 产生bytues 使用utf-8进行编码,utf-8是从字符到字节的一种对应码方案
print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8'))  # 使用utf-8进行解码
包含中文的str
b'\xe4\xb8\xad\xe6\x96\x87'
中文

字符串格式化

print('Hello, %s' % 'world')
print('Hi, %s, you have $%d.' % ('Michael', 1000000))
print('%.3f'.format(3.1415926))
print('PI为{0:>8.3f}'.format(3.1415926))  # 可以使用0表示位置,8位右对齐
print('PI为{pi:0>+8.3f}'.format(pi=3.1415926))  # 可以使用名字,8位右对齐,不足补0带符号
Hello, world
Hi, Michael, you have $1000000.
%.3f
PI为   3.142
PI为00+3.142
# fstring
pi = 3.1415926
print(f'PI为{pi:0>+8.3f}')
PI为00+3.142

元组

a = (1, 2, 3)
a[1] = 2  # 不可变
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-33-7dcf28d59468> in <module>
      1 a = (1, 2, 3)
----> 2 a[1] = 2  # 不可变


TypeError: 'tuple' object does not support item assignment
a = (1)
b = (1,)  # 单值元组需带,
c = 1, 2, 3  # 多值可省略括号
print(a, b, c)
1 (1,) (1, 2, 3)

字典

# 字典操作
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])
d['Jack'] = 90
print(d)
print('Thomas' in d)  # 查询键
print(d.get('Jack'))
print(d.get('Thomas'))
print(d.get("Thomas", 80))  # 查询不到时返回提供值
print(d.update({'Simon': 22}))
print(list(d.keys()))
print(list(d.values()))
del d['Jack']  # 删除jack
print(list(d.items()))
for i, j in d.items():  # items返回键值对元组,分别赋给i,j
    print(i, j)
d.clear()  # 清空
print(d)
95
{'Michael': 95, 'Bob': 75, 'Tracy': 85, 'Jack': 90}
False
90
None
80
None
['Michael', 'Bob', 'Tracy', 'Jack', 'Simon']
[95, 75, 85, 90, 22]
[('Michael', 95), ('Bob', 75), ('Tracy', 85), ('Simon', 22)]
Michael 95
Bob 75
Tracy 85
Simon 22
{}

集合

a = {}  # 空集合为set() {}表示空字典
print(type(a))
a = set([1, 2, 3])
b = set((2, 3, 4))
print(a & b)  # 并集
print(a | b)  # 交集
print(a - b)  # 差集
print(a ^ b)  # 对称差集
<class 'dict'>
{2, 3}
{1, 2, 3, 4}
{1}
{1, 4}
a = 1
b = 2
a, b = b, a
print(a, b)
a, *b, c = (1, 2, 3, 4, 5, 8)
print(a)
print(b)
print(c)
a, *b = (1, 2, 3, 4)
print(b)
*a, b = (1, 2, 3, 4)
print(a)
print(b)
2 1
1
[2, 3, 4, 5]
8
[2, 3, 4]
[1, 2, 3]
4

类型转换

a = '1.123'
print(bool(a))
print(float(a))
print(int(a))  # 不能直接转换
True
1.123



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-143-c023bf093226> in <module>
      2 print(bool(a))
      3 print(float(a))
----> 4 print(int(a))  # 不呢直接转换


ValueError: invalid literal for int() with base 10: '1.123'
print(int(float(a)))
1
1
bool('')  # bool将'' [] () {} 0 0.0 False None均转化为False 其余为True
False
a = 'sssimon yang'
print(list(a))
print(tuple(a))
a = list(a)
print(" ".join(a))  # 使用空格连接各字符串,比+有效率
['s', 's', 's', 'i', 'm', 'o', 'n', ' ', 'y', 'a', 'n', 'g']
('s', 's', 's', 'i', 'm', 'o', 'n', ' ', 'y', 'a', 'n', 'g')
s s s i m o n   y a n g
print(dict(Baidu=1, Google=2, Taobao=3))  # 函数
print(dict([['Baidu', 1], ('Google', 2), ('Taobao', 3)]))  # 使用内含二值的序列嵌套
print(list(dict(Baidu=1, Google=2, Taobao=3)))  # 只有键
{'Baidu': 1, 'Google': 2, 'Taobao': 3}
{'Baidu': 1, 'Google': 2, 'Taobao': 3}
['Baidu', 'Google', 'Taobao']
site = {"name": "sssimon yang", "age": "22"}
print("名字:{name}, 年龄 {age}".format(**site))
名字:sssimon yang, 年龄 22

内置函数

print(sum([1, 2, 3]))
print(abs(-20))
a = [1, 1, 2, 3, 4, 2, 3, 4, 5]
print(max(a))
print(min(a))
a = abs  # 函数可以传递
print(a(-1))
print(all([True,False,True]))
print(any([True,False,True]))
for i, j in enumerate(['tic', 'tac', 'toe']):
    print(i, j)
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))
6
20
5
1
1
0 tic
1 tac
2 toe
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

控制与循环结构

# if语句
age = 20
if age >= 18:
    print('adult')
age = 3
if age >= 18:
    print('adult')
else:
    print('teenager')
age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')
adult
teenager
kid
# 自动类型转换
x = []
if x:
    print('yes')
if not x:
    print('no')
no
names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

sites = ["Baidu", "Google", "Bing"]
for site in sites:
    if site == "Google":
        print('yes')
        break             # 跳出循环 ,continue进入下一个
    print("this is" + site)

sites = ["Google", "Baidu", "Bing"]
for site in sites:
    if site == "Google":
        print('yes')
        continue             # 进入下一个
    print("this is" + site)
else:
    print('final')    # 当非break退出时执行else语句

# 注意在循环中不要向循环对象添加元素,新手常犯
Michael
Bob
Tracy
this isBaidu
yes
yes
this isBaidu
this isBing
final
n = 9
while n > 0:
    print(n)
    n = n-1
# while中同样也有break continue else
9
8
7
6
5
4
3
2
1

lambda表达式与列表、元组、字典生成式

vec = [2, 4, 6]
print([3*x for x in vec])
print(list((2*x for x in range(3))))
freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
print([weapon.strip() for weapon in freshfruit])
print({x: x**2 for x in (2, 4, 6)})
def sum(arg1, arg2): return arg1 + arg2


print("相加后的值为 : ", sum(10, 20))
print("相加后的值为 : ", sum(20, 20))
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
print([x*y for x in vec1 for y in vec2])
[6, 12, 18]
[0, 2, 4]
['banana', 'loganberry', 'passion fruit']
{2: 4, 4: 16, 6: 36}
相加后的值为 :  30
相加后的值为 :  40
[8, 6, -18, 16, 12, -36, 24, 18, -54]
filter(lambda x: x % 3, range(10))
list(filter(lambda x: x % 3, range(10)))
<filter at 0x270cb36cdc8>






[1, 2, 4, 5, 7, 8]
map(lambda x:f'x={x}',range(10))
list(map(lambda x:f'x={x}',range(10)))
<map at 0x270cb3bb708>






['x=0', 'x=1', 'x=2', 'x=3', 'x=4', 'x=5', 'x=6', 'x=7', 'x=8', 'x=9']
## 文件操作
a = open('some.txt', 'w')
a.close()
with open('some.txt','w') as f:
    print(f.write('hello word'))

with open('some.txt') as f:
    print(f.read())
10
hello word

其他常用

a = [1, 2, 3]
b = [1, 2, 3]
print(id(a))  # 查看内存地址
print(id(b))
print(a == b)
print(a is b)
print(id(True))
print(id(a == b))  # True False None地址唯一
2683467477640
2683468901128
True
False
140734358989136
140734358989136

help

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

py文件结构

print(__name__)  # 内置变量_name__, 当本文件为运行文件时,值为__main__, 当本文件被导入时, 值为文件名
__main__
def main():
    return 'hello'
if __name__ == '__main__':
    main()
'hello'

函数

传参

def nothing():
    pass

def plus(n):
    return n+1

def hello():
    print("hello")

print(nothing())
print(plus(1))
print(hello())
print(hello)
None
2
hello
None
<function hello at 0x00000270CB3589D8>

默认参数

def enroll(name, gender, age=6, city='Beijing'):
    print(f'name:{name},gender:{gender},age:{age},city:{city}')


enroll('Sarah', 'F')
enroll('Bob', 'M', age=7)
enroll('Adam', 'M', city='Tianjin')
enroll('Adam', 'M', city='Tianjin', age=18)
enroll(*('Adam', 'M'), **{'age': 18, 'city': 'Tianjin'})
name:Sarah,gender:F,age:6,city:Beijing
name:Bob,gender:M,age:7,city:Beijing
name:Adam,gender:M,age:6,city:Tianjin
name:Adam,gender:M,age:18,city:Tianjin
name:Adam,gender:M,age:18,city:Tianjin

变长参数

def main(*args, **kwargs): 
    print(args)
    print(kwargs)


main('Michael', 30)
main('Adam', 45, gender='M', job='Engineer')
('Michael', 30)
{}
('Adam', 45)
{'gender': 'M', 'job': 'Engineer'}

单行函数

def strip(x): return x.strip()  # lambda函数

strip(' hello world ')
'hello world'

异常处理

a = 1/0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-167-6c16767f6731> in <module>
----> 1 a = 1/0


ZeroDivisionError: division by zero
try:
    a = 1/0
except ZeroDivisionError:
    print('division by zero is forbidden')  # else finally语句可加可不加
else:
    print('success')
finally:
    print('always print this line')
division by zero is forbidden
always print this line
try:
    a = 1/10
except ZeroDivisionError:
    print('division by zero is forbidden')  # else finally语句可加可不加
else:
    print('success')
finally:
    print('always print this line')
success
always print this line
try:
    a = 1/0
except:                                # 捕捉所有可能错误,不建议
    print('error')
error
assert 1==0
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-187-788ee363e0a2> in <module>
----> 1 assert 1==0


AssertionError:
raise Exception
---------------------------------------------------------------------------

Exception                                 Traceback (most recent call last)

<ipython-input-188-2aee0157c87b> in <module>
----> 1 raise Exception


Exception:

import使用包

import os
# from os import * # 不建议
from os import chdir
from os.path import exists as some_other_name
import os
os.remove('some.txt')