0%

python基本语法

文章字数:987,阅读全文大约需要3分钟

指定字符编码 # -*- coding: utf-8 -*-

输入输出

  1. 输入 name = input()
  2. 输出 print('1+1=',1+1)

循环

  1. if

    1
    2
    3
    4
    5
    6
    7
    8
    # :后面的缩进(4个空格)都是代码块
    a = 100
    if a >= 0:
    print(a)
    elif a = 0:
    print(0)
    else:
    print(-a)
  2. for

1
2
3
4
5
6
names = [1,2,3,5]
for name in names
print(name)

for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
  1. while
1
2
3
4
n = 0
while n > 0:
sum = sum + n
n = n - 2
  1. 退出
  • break退出所有循环
  • continue退出本次循环

数据类型

变量不用声明,直接用 a=123

  1. 整数 1
  2. 浮点数 1.23
  3. 字符串
  • ' '
  • " "
  • r' ' 内部不转义
  • ''' sss ''' 多行文本
  1. 布尔值 True False使用and or not运算
  2. 空值 None

集合

  1. list
  • 声明 classmates = ['Michael', 'Bob', 'Tracy']
  • 长度 len(classmates)
  • 正向下标取值classmates[0] 第一个
  • 负向下标取值classmates[-1] 最后一个
  • 追加到末尾classmates.append('Adam')
  • 插入指定位置classmates.insert(1, 'Jack')
  • 删除末尾classmates.pop()
  • 删除指定位置classmates.pop(1)
  • 切片获取 r[0:3]从0取到3,0可省略
  1. tuple不可变集合
  • 声明classmates = ('Michael', 'Bob', 'Tracy')
  • 声明空的tuplet = ()
  • 声明一个:t = (1,)为了和数值型区分,后面加,
  1. dict:键值对
  • 声明 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
  • 取出d['Michael']或者d.get('Michael')
  • 判断是否key在字典中'Thomas' in d返回布尔
  • 删除d.pop('Bob')
  1. set无序集合
  • 声明s = set([1, 2, 3])
  • 添加s.add(4)
  • 删除remove(key)
  • 交集并集s1 & s2 s1 | s2

函数

  1. 函数赋值a = abs指向abs(),然后a()

  2. 声明

    1
    2
    3
    4
    5
    def my_fun(x):
    if x >= 0:
    return x
    # 返回None
    return
  3. 空函数

1
2
3
def nop():
# 占位,也可用于循环的占位
pass
  1. 返回多值
1
2
3
4
5
def xx():
return 1,2

# 其实是个cuple
x, y = xx()

对象

  • 对象迭代
1
2
3
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
  • 声明
1
2
3
4
5
# object代表父类
class Cl(object):
# self代表本身,永远是第一个
def __init__(self, name)
self.name = nema

c = Cl('123')

  • 指定对象可以使用的属性
    __slots__ = ('name', 'age')仅当前类有用,子类无作用

  • toString 写__str__方法

  • 类作用于len():写__len__方法

  • 对象可以被遍历

1
2
3
4
5
def __iter__(self):
return self
def __next__(self):
# 迭代器每次都会调用这个方法,接收返回
# raise StopIteration()退出(抛出异常)
  • get set
1
2
3
4
5
6
@property
def score(self):
return self._score

@score.setter
def score(self, value):

s.score:等于s.get_sore()
s.score = 60:s.set_sore(60)

函数式编程

  1. map/reduce
    r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])f是函数,接收一个值,map会把list的参数一个个传进去

reduce(f, [x1, x2, x3, x4])f是函数,接收两个值第一个是上一个的返回值,第二个是list的元素

  1. filter filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])返回满足条件的集合

  2. sorted([36, 5, -12, 9, -21])排序

  3. 函数可以返回函数

  4. 获取函数变量的方法名fun.__name__

模块

  • 定义abc.py就是abc模块
  • 引入import abc

常用方法

  1. range(5)生成 0-5 的有序集合
  2. list(range(5))展示list
  3. b = a.replace('a', 'A')字符替换
  4. help(abs)查看函数说明
  5. abs(100)取整
  6. int()转换类型
  7. max(1,2,3,)取最大值
  8. hex()十进制转16
  9. now()现在的时间
  10. type('abc')获取类型,也可以传对象

io

  1. 打开文件
  • f = open('/Users/michael/test.txt', 'r')r只读
  • f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')指定字符编码
  • f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')字符编码错误忽略
  1. 读取f.read()

  2. 关闭f.close()

  3. 安全打开(有异常也关闭)

1
2
3
4
5
try:
f = open('/Users/michael/test.txt', 'r')
finally:
if f:
f.close()
  1. 自动关闭

    1
    2
    with open('/path/to/file', 'r') as f:
    print(f.read())
  2. 其它读

  • read(size)读取固定大小
  • readline()读取一行
  • readlines()读一行,返回所有内容的list
  • 覆盖w追加a
  • f.write('Hello, world!')
  1. StringIO,BytesIO
  • f = StringIO('Hello!\nHi!\nGoodbye!')string转成io
  • f = BytesIO()然后写f.write('中文'.encode('utf-8'))
    f.getvalue() : b'\xe4\xb8\xad\xe6\x96\x87'二进制数据
  1. 文件目录
    import os
  • os.rename('test.txt', 'test.py')重命名
  • os.remove('test.py')删除
  • os.mkdir('/Users/michael/testdir')创建目录
  • os.rmdir('/Users/michael/testdir')删除目录
  1. 对象写入
  • 转换成bytes:
    1
    2
    3
    4
    5
    import pickle
    f = open('dump.txt', 'wb')
    d = dict(name='Bob', age=20, score=88)
    pickle.dumps(d)
    f.close()
  • 转json
    1
    2
    3
    4
    5
    import json
    d = dict(name='Bob', age=20, score=88)
    json.dumps(d)
    # 解析json
    json.loads(json_str)

多线程

  1. 支持多进程
  2. 多线程
    1
    2
    3
    4
    5
    6
    def loop():
    ...

    t = threading.Thread(target=loop, name='LoopThread')
    t.start()
    t.join()