Skip to content

基础

输入输出、基本类型、变量

输入输出

python
name = input("Please enter your name.")
print("name is:", name)
name is: zhangsan

整数和浮点

python
print(1, 100, -90, 0, 0xFF00, 10_000_000_000, 0xA1B2_C3D4, 1.23e9, 12.3e8, 3.14, -9.01)
1 100 -90 0 65280 10000000000 2712847316 1230000000.0 1230000000.0 3.14 -9.01

字符串

python
print('I\'m "OK"!')
print(r"I\'m \"OK\"!")
print(
    """line1
lin2
lin3
"""
)
I'm "OK"!
I\'m \"OK\"!
line1
lin2
lin3

布尔

python
print(True)
print(False)
print(3 > 2)
print(3 > 5)
print(True and True)
print(True and False)
print(False and False)
print(5 > 3 > 1)
print(True or True)
print(True or False)
print(False or False)
print(not True)
print(not False)
print(not 1 > 2)
True
False
True
False
True
False
False
True
True
True
False
False
True
True

空值

python
print(None)
None

常量

python
PI = 3.1415926585793238462643383176502
print(PI)
3.1415926585793237

运算

python
print(8 / 3)  # 除法
print(8 // 3)  # 整除
print(8 % 3)  # 取模
2.6666666666666665
2
2

字符串编码

python
print("包含中文的字符串 str")
print(ord("中"), ord("国"), ord("A"))
print(chr(20013), chr(20014), chr(66))
print("\u4e2d\u6587", "中文")
包含中文的字符串 str
20013 22269 65
中 丮 B
中文 中文

字节 bytes

python
print("ABC".encode("ascii"), b"ABC".decode("ascii"))
print("中文".encode("utf-8"), b"\xe4\xb8\xad\xe6\x96\x87".decode("utf-8"))
print(len("ABC"), len("中文"), len(b"ABC"), len(b"\xe4\xb8\xad\xe6\x96\x87"))
# 报错
# print('中文'.encode('ascii'))
b'ABC' ABC
b'\xe4\xb8\xad\xe6\x96\x87' 中文
3 2 3 6

格式化输出

  • 传统格式化输出
python
print("%2d-%02d" % (3, 1))
print("%.2f" % 3.1415926)
print("Age: %s, Gender: %s" % (25, True))
print("growth rate: %d %%" % 7)
 3-01
3.14
Age: 25, Gender: True
growth rate: 7 %
  • 使用 format() 格式化输出
python
print("Hello, {0}, 成绩提升了 {1:.1f}%. {2}。".format("小明", 17.125, "!"))
Hello, 小明, 成绩提升了 17.1%. !。
  • 使用 f-string 格式化输出
python
r = 2.5
s = 3.14 * r**2
print(f"The area of a circle with radius {r} is {s:.2f}")
The area of a circle with radius 2.5 is 19.62

列表 list 和 元组 tuple

元祖 tuple:占用空间小

list 列表

python
classmates = ["Michael", "Bob", "Tracy"]

print(classmates)

print(len(classmates))  # 列表长度
print(classmates[0])  # 列表第一项
print(classmates[-1])  # 列表最后一项

classmates.append("Adam")
print("添加", classmates)

classmates.insert(1, "Jack")
print("插入", classmates)

classmates.pop()
print("删除", classmates)

classmates.pop(1)
print("删除索引为 1 的项", classmates)

classmates[1] = "Alice"
print("修改", classmates)
['Michael', 'Bob', 'Tracy']
3
Michael
Tracy
添加 ['Michael', 'Bob', 'Tracy', 'Adam']
插入 ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
删除 ['Michael', 'Jack', 'Bob', 'Tracy']
删除索引为 1 的项 ['Michael', 'Bob', 'Tracy']
修改 ['Michael', 'Alice', 'Tracy']

二维数组

python
s = ["Python", "Java", ["asp", "jsp"], "scheme"]
print(len(s))
print(s[2][1])
4
jsp

tuple 元组

元组初始化后不能修改

python
classmates = ("Michael", "Bob", "Tracy")
print(classmates[1])
print(classmates[-1])

t = (1, 2)
print(t)  # (1, 2)

t = ()
print(t)  # ()

t = 1
print(t)  # 1,因为 () 会被识别为运算符

t = (1,)
print(t)  # (1,)
Bob
Tracy
(1, 2)
()
1
(1,)

可"变" tuple

python
t = ("a", "b", ["A", "B"])
t[2][0] = "X"
t[2][1] = "Y"
print(t)  # ('a', 'b', ['X', 'Y'])
('a', 'b', ['X', 'Y'])

条件判断

if else

python
age = 20
if age >= 10:
    print("your age is", age)
    print("adult")

birth = int(input("birth: "))
if birth < 2000:
    print("00前")
else:
    print("00后")
your age is 20
adult
00前

match 匹配

python
score = "B"
match score:
    case "A":
        print("score is A.")
    case "B":
        print("score is B.")
    case "C":
        print("score is C.")
    case _:
        print("score is ???.")
score is B.

match 复杂匹配

python
age = 15
match age:
    case x if x < 10:
        print(f"< 10 years old: {x}")
    case 10:
        print("10 years old")
    case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18:
        print("11 ~ 18 years old")
    case 19:
        print("19 years old")
    case _:
        print("not sure")
11 ~ 18 years old

match 匹配列表

python
args = ["gcc", "hello.c", "world.c"]
match args:
    case ["gcc"]:
        print("gcc: missing source file(s)")
    case ["gcc", file1, *files]:
        print("gcc compile: " + file1 + ", " + ", ".join(files))
    case ["clean"]:
        print("clean")
    case _:
        print("invalid command")
gcc compile: hello.c, world.c

循环

for in 循环

python
names = ["Michael", "Bob", "Tracy"]
for name in names:
    print(name)
print(list(range(100)))
Michael
Bob
Tracy
[0, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

for in range

python
sum = 0
for i in range(101):
    sum += i
print(sum)
5050

while 循环

python
sum = 0
n = 99
while n > 0:
    sum += n
    n -= 2
print(sum)
2500

break 退出循环

python
n = 1
while n <= 100:
    if n > 10:
        break
    n += 1
print(n)
11

continue 退出循环

python
n = 0
while n <= 100:
    n += 1
    if n % 2 == 0:
        continue
    print(n)
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99
101

字典 dict

dict:空间换时间

python
names = ["Michael", "Bob", "Tracy"]
scores = [95, 85, 75]
d = {"Michael": 95, "Bob": 85, "Tracy": 75}
  • dict 中,字符串、整数都是不可变的,因此可以作为 key;
  • list 由于是可变的,因此不可以作为 key;
python
# 会报错
# key = [1, 2, 3]
# d[key] = 'a list'

查看 dict 中的 value

python
print(d["Michael"])
95

判断 dict 中 key 是否存在

python
print("Alice" in d, "Michael" in d)
print(d.get("Alice", None), d.get("MIchael", None))
False True
None None

删除 dict 中某个 key

python
d.pop("Michael")
print("dict is:", d)
dict is: {'Bob': 85, 'Tracy': 75}

集合 set

python
s = {1, 2, 3}  # 等价于 set([1, 2, 3])
print(s)
{1, 2, 3}

去重

python
s = {1, 2, 3, 3, 3, 2, 2}
print(s)
{1, 2, 3}

添加

python
s.add(4)
print(s)
{1, 2, 3, 4}

删除

python
s.remove(3)
print(s)
{1, 2, 4}

交集 & 和并集 |

python
s1 = {1, 2, 3}
s2 = {2, 3, 4}
print(s1 & s2)  # {2, 3}
print(s1 | s2)  # {1, 2, 3, 4}
{2, 3}
{1, 2, 3, 4}

不可变对象 str

list 可变对象

python
a = ["c", "b", "a"]
a.sort()
print(a)
['a', 'b', 'c']

str 不可变对象

python
a = "abc"
b = a.replace("a", "A")  # replace 作用在 'abc' 上,而不是变量 a 上
print(a, b)
abc Abc