Python

一些设计理念

  • Python里的函数,可以定义在类里,也可以不在类里。但不管定义在哪里,最终都会在module里。一个module就是一个py文件。至于一些“global function”,其实是定义在builtin module里,只不过该module是自动加载的,所以让人感觉是builtin function。
  • Python里一切皆为对象,不管是class还是function还是module,甚至基本数据类型,都是对象。

基本数据类型

字符串

"Hello"[3]   # letter second l

整数int 浮点数float

布尔类型bool

True
False

空置类型 NoneType

None  # 代表没有值,如果需要声明变量但不知道赋什么值,可以先定义为None

用type确定数据类型

print(type("hello!"))
print(type(6))
print(type(3.0))
print(type(True))
print(type(None))

# we get the following output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'NoneType'>

条件语句

if的用法

if value < 25:
    print("hello 1")
elif 25 <= value < 50:     # python里竟然还能这样用...
    print("hello 2")
else:
    print("hello 3")

数据结构

list

list.append(element): 将元素加到最后
listinsert(position, element): 将元素加到特定位置
del list[0]:将在特定位置上的元素删除
list.pop(): 将最后一个元素删除并返回
list.pop(position): 将特定位置上的元素删除
list.remove(element): 将列表里出现的第一个该元素删除
list.sort()/list.sort(reverse=True): 将原始列表排序
sorted(list): 排序但是不影响原来列表内部元素顺序
list.reverse(): 列表反转,会影响元素顺序
len(list): 返回列表长度
list comprehension: my_list = [val * 3 for val in range(1, 10)]
list slice: copy_list = original_list[:] my_list = original_list[2:5] my_list = original_list[:3] my_list = original_list[2:] my_list = original_list[-3:]

Scroll to Top