Python基础

本文为Python的一些基础知识总结,基于Python 3。

Types 类型

Basic Types 基础变量类型

Type conversion 类型转换

使用 type(*) 用来获得变量类型,help(*) 可以获得帮助说明。

float(7)  # => 7.0
int(7.24) # => 7
int('A')  # error, 不能强转非数字的字符
str(2)    # => "2"
bool(1)   # => True

Grammar 基本语法

Expression 表达式

Mathematical Operations 数学运算

Python 3中,/// 代表的除法含义不同:

String operations 字符串操作

Define a string 定义字符串

s1 = "Kevin"
s2 = 'Kevin' # s2 同 s1

S3 = """Kevin and "K.K".""" # => Kevin and "K.K".
name[0]  # => 'K'
name

String slicing 字符串切片

Python string的语法定义为 string[start:end:step],其中start默认为0end默认为len(string)step默认为1

使用 str[i:j] 的方式来获取子字符串,其表示从索引i开始截止到(不含)索引j的字符

s2 = “012345678” s2[:5] # => “01234” s2[2:] # => “2345678” s2[2:5] # => “234” s2[2:7:2] # => “246”


List的slicing:
``` python
a = [1, 2, 3]
a[1:]       # => [2, 3]
a[1:2]      # => [2] 注意这是取一个sub-list
a[1]        # => 2   而这是取一个元素

String Concatenation 字符串连接

可以用str0 + str1的方式连接字符

s0 = "I am "
s1 = "Kevin"
s2 = s0 + s1 # => "I am Kevin"

String replication 字符串复制

num * string的方式复制字符串为多次

s1 = "Kevin "
s2 = 3 * s1 # => "Kevin Kevin Kevin "

String is immutable 字符串的值是不可变的

不能改变一个字符串里的值,但可以对变量重新赋值。

s1 = "Kevin "
s1[0] = 'K' # ERROR!!!
s1 = "Wen"  # OK

String functions 字符串常用函数

Lists and Tuple 列表和元组

Tuple 元组

Tuple properties 元组属性

Tuple Nesting 元组嵌套

Tuple的一个item可以是Tuple

tuple0 = (1, 2, ("pop", "rock"), (3, 4))
tuple0[2]     # => ("pop", "rock")
tuple0[2][1]  # => "rock"`

List 列表

List properties 列表属性

Covert String to List 转换字符串到列表

string.split():按照空格拆分字符串

"Kaikai is a dog".split()     # => ['Kaikai', 'is', 'a', 'dog']
"Kaikai,is,a,dog".split(",")  # => ['Kaikai', 'is', 'a', 'dog']

List Aliasing 列表别名

如果一个变量B指向另一个变量A (B = A),那么BA的别名。对A的任何改动,B都可以访问到。

l1 = [1, 2, 3]
l2 = l1
l1[0] = 0
print(l1) # [0, 2, 3]
print(l2) # [0, 2, 3]

List Clone 列表复制

复制一个列表通过 B = A[:]的方式,AB相互不影响

l1 = [1, 2, 3]
l2 = l1[:]
l1[0] = 0
print(l1) # [0, 2, 3]
print(l2) # [1, 2, 3]

Dictionary 字典

Dictionary中的每个元素由(key, value)的键值对组成。

dic = {"k1":1, "k2":"2", "k3":[3,3], "k4":(4,4), ('k5'):5}

Sets 集合

Sets 是类似listtuple的集合,可以包含任意元素。

Conditions and Branching 条件和分支

Conditions 条件

Branching 分支

Loops 循环

range([start], end, [step])

for i in range(N):

for i in range(1, 10, 2):

while (condition):

Functions 函数

函数是有输入和输出的代码集合,主要目的是为了复用,同时让代码结构更清晰。 Python 中函数的定义使用关键词def function_name():

Build in functions 内置函数

Collecting arguments 多参数

参数前可以有1个或2个星号,这两种用法其实都是用来将任意个数的参数导入到python函数中。

Scope 作用域

Python 中变量区分局部和全局作用域,同 C++ / Java 之类的语言。 如果在函数中希望定义全局变量,可以在变量前加关键字global,以便在全局可被访问。

Objects and Classes 对象和类

可以用dir(object)的方式列出类的属性。

File IO 文件操作

File open and close 文件打开关闭

  1. 读写格式
    • FileObject = open(file_path, mode)
      • 创建:"x",如果文件存在则返回失败
      • 只读:"r"
      • 覆写:"w"
      • 追加:"a"
      • 文本:"t" ,为默认值
      • 二进制:"b" ,例如读写图片
  2. 关闭文件
    • file.close()
    • 推荐用with open(path, mode) as file:,在执行完with的作用域时自动调用file.close()

Reading Files 读文件

with open("example.txt", "r") as file:
  content = file.read()
  print(content)

Writting Files 写文件

with open("example.txt", "w") as file:
  file.write("a line")

Delete a File or Folder 删除文件或目录

函数变量

局部变量和全局变量

有其他语言经验的朋友对这两点一定很容易理解这两点。只是想提醒一下,避免global的全部变量,毕竟让code很难维护。下面说说模块导入变量。

模块导入变量

核心思想是把同一个全局模块的内容组织到一个py文件中,通过模块导入的方式共享到相同模块的代码中:

看例子,在main.py中:

import global_abc
import another

def print_variables():
    print(global_abc.GLOBAL_A + ", " + global_abc.GLOBAL_B)

if __name__ == '__main__':
    print_variables()       # Hello, Python

    global_abc.print_name() # Kevin
    global_abc.modify_name()# change Kevin --> GoGo
    global_abc.print_name() # GoGo
    another.print_name_in_3rd_module()  # GoGo

global_abc.py中:

GLOBAL_A = 'Hello'
GLOBAL_B = 'Python'

name = 'Kevin'

def modify_name():
    global name
    name = 'GoGo'

def print_name():
    print(name)

another.py中:

import global_abc

def print_name_in_3rd_module():
    global_abc.print_name()

通过这种方式,可以在多个不同的文件间组织和共享变量。

这部分的内容的组织方式自参考了文章[2]。

其他

Python 参数传递

Python函数参数前面单星号(*)和双星号(**)的区别

'''单星号(*):*agrs:将所以参数以元组(tuple)的形式导入'''
def foo(param1, *param2):
    print(param1, param2)

'''双星号(**):**kwargs:将参数以字典的形式导入'''
def bar(param1, **param2):
    print(param1, param2)
    
foo(1,2,3,4,5)
# output: 1 (2, 3, 4, 5)

bar(1,a=2,b=3)
# output: 1 {'a': 2, 'b': 3}

Reference

  1. Python 3 官方文档
  2. https://blog.csdn.net/Eastmount/article/details/48766861

回到目录