数据类型

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#缩进
if 5 > 3 :
print("hello")

#注释
"""
comment more than 1 line
"""

#赋值
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

x = y = z = "Orange"
print(x)
print(y)
print(z)

x = "awesome"
print("Python is " + x)

#变量类型
x = 1
def func1():
x = 2 #局部变量
print(x)
global y #模块内创建局部变量
y = 3
def func2():
global x
x = 4 #修改全局变量

#数据类型
x = int(4) # 可以这样创建实际上也是强制类型转换
y = float(3.0)
z = complex(1j) #complex不可以再变成前两种

import random
print(random.randrange(1,5))

数据类型

plaintext
1
2
3
4
5
6
7
python 以类的方式定义数据类型
数据类型的类产生的对象x,也有自己的方法
例如: x = "hello"
x.function()

y = 3
y = int(2)

字符串

Python 字符串

  • 换行字符串
  • 字符串索引
  • 字符串裁剪
  • 字符串长度
  • 字符串方法
  • 字符串关键字
  • 字符串与其他类型组合 使用字符串对象的format方法

布尔值

bool()

python
1
2
x = int(8)
print(isinstance(x , int))

运算符

python
1
2
3
4
5
6
3 // 2
3 ** 2
and or not
is is not
in not in

集合

  • *列表(List)*是一种有序和可更改的集合。允许重复的成员。
  • *元组(Tuple)*是一种有序且不可更改的集合。允许重复的成员。
  • *集合(Set)*是一个无序和无索引的集合。没有重复的成员。
  • *词典(Dictionary)*是一个无序,可变和有索引的集合。没有重复的成员。

列表 Python 列表 (像数组)

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
my_list = ["a",'b','c']

copy_list = my_list
copy_list [-2] = 'x'
print(my_list[-2:-1])

if 'x' in my_list:
print("reference is valid")
copy_list.append('y')
copy_list.insert(1,'z')
copy_list.remove('a')
del my_list
if len(copy_list) != 0:
print('im ok')
print(copy_list[1])

元组

python
1
2
3
4
5
my_tuple = ("me",)
x = my_tuple.count("me")
y = my_tuple.index("me")
print(x)
del my_tuple

集合(无序)

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
thisset.update(["orange", "mango", "grapes"])
thisset.remove("banana")
thisset.discard("banana")
x = thisset.pop()
thisset.clear()


set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
set1.update(set2)
thisset = set(("apple", "banana", "cherry")) # 请留意这个双括号

字典

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#initial
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}

#[]运算
x = thisdict["model"]
#等价于
x = thisdict.get("model")
thisdict["year"] = 2019

#print
for x in thisdict.values():
print(x)
for x, y in thisdict.items():
print(x, y)

#add
thisdict["color"] = "red"

#delelt
thisdict.pop("model")
thisdict.popitem() #删除最后一个添加的项目
del thisdict
thisdict.clear()

#create
mydict = thisdict.copy()
dic = thisdict #引用
mydict = dict(thisdict) #构造函数

child1 = {
"name" : "Phoebe Adele",
"year" : 2002
}
child2 = {
"name" : "Jennifer Katharine",
"year" : 1996
}
child3 = {
"name" : "Rory John",
"year" : 1999
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}