跳转至

Python

1 脚本环境

1.1 文件编码

Python 源码文件的编码是 UTF-8,如果需要改变,可以在文件头按以下格式设置编码方式,其中encoding可以是utf-8等。

# -*- coding: encoding -*-
  • 示例
# -*- coding: utf-8 -*-

1.2 脚本默认启动程序

  • 指定python3执行脚本, 这是UNIX "shebang"用法,这样当不指定python来执行可执行文件时,默认会以python3来执行
#!/usr/bin/env python3
# -*- coding: cp1252 -*-

2 输入输出

1 input

从命令行读取用户输入

In [3]: a=input("请输入数字:")
请输入数字:3

In [4]: a
Out[4]: '3'

2 print

打印内容到标准输出上

In [18]: print("hello\nworld")
hello
world

In [19]: print(r"hello\nworld")
hello\nworld

In [20]: str="boo"

In [21]: print(f"hello\n{str}")
hello
boo

3 open

用open打开一个文件,返回句柄后进行读写

#!/usr/bin/python3  

# 打开一个文件  
f = open("foo1.txt", "w")  

value = ('hello world', 9)  
s = str(value)  
f.write(s)  

# 关闭打开的文件  
f.close()

3 数据结构

1 数字

2 字符串

2.1 字符格式化

  • 语法:str.format(*args, **kwargs)
  • 示例
In [16]: "hello {}".format('bob')
Out[16]: 'hello bob'

In [17]: "hello {1} say {0}".format('by','bob')
Out[17]: 'hello bob say by'

4 函数

1 参数

  • 函数定义def func(*args):def func(**args):作用:
    • *args表示把传进来的位置参数都放在元组 args 。调用 func(a, b, c) 时, args= (a, b, c)
    • **args表示把传进来的位置参数都放在字典 args。调用 func(a=0, b=1, c=2 时, args= {‘a’:0, ‘b’:1, ‘c’:2}
  • 函数调用fun(*arg)fun(**arg)作用
    • *args表示把传进来的序列args解包,如args=[0, 1, 2],则相应解包为:a, b, c=[0, 1, 2], 即func(0, 1, 2)
    • **args表示把传进来的字典args解包,如args= {'a':0, 'b':1, 'c':2},则相应解包为:a,b,c = {'a':0, 'b':1, 'c':2}, 即func(a=0, b=1, c=2)
  • 示例
In [28]: def fun1(*arg):
    ...:     print(arg)
    ...:

In [29]: fun1(1,2,3)
(1, 2, 3)

In [31]: def fun2(**arg):
    ...:     print(arg)
    ...:

In [32]: fun2(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}

In [35]: args=[1,2,3]

In [36]: def fun3(a,b,c):
    ...:     print("a={} b={} c={}".format(a,b,c))
    ...:

In [37]: fun3(*args)
a=1 b=2 c=3

In [38]: args={'a':1,'b':2,'c':3}

In [39]: fun3(**args)
a=1 b=2 c=3

5 循环

6 条件

1 pass

pass 语句不执行任何操作。语法上需要一个语句,但程序不实际执行任何动作时,可以使用该语句。例如:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

下面这段代码创建了一个最小的类:

>>> class MyEmptyClass:
...     pass
...

pass 还可以用作函数或条件子句的占位符,让开发者聚焦更抽象的层次。此时,程序直接忽略 pass

>>> def initlog(*args):
...     pass   # Remember to implement this!
...

2 match

作用同c/c++中的switch/case - 示例

In [40]: def fun(status):
    ...:     match status:
    ...:         case 400:
    ...:             return "Bad Error"
    ...:         case _:
    ...:             return "default"
    ...:

In [41]: fun(400)
Out[41]: 'Bad Error'

In [42]: fun(401)
Out[42]: 'default'