Python-基础语法

一、注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# this is Single-Line Comments

"""
this is block comments,By Double quotation marks

Author: lol_toulan
Date: 2024-12-16 23:59:59
"""

'''
this is block comments,By Single quotation marks

Author: lol_toulan
Date: 2024-12-16 23:59:59
'''

二、语法格式

在Java和C等语言中,我们常以 {}对来表示代码块,以;来标志一行或多行代码的结束

但是在Python中,我们常以缩进来区分不同的代码块,通常也不需要;来标志一行或多行代码的结束

1
2
3
4
5
6
7
8
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
1
2
3
4
5
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
}
}

三、数据类型

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
a = 123
b = 1.23
c = "123"
d = '123'
e = 4+5j
f = True
g = None
h = b'123'
# 不可变
i = (a, b,c,d,e,f,g,h)
# 可变
j = [a,b,c,d,e,f,g,h]
k = {'name':'lol','age':18}
l = {'name','lol','age',18}
# 不可变
o = frozenset({'name','lol','age',18})

m = """
this is multiline comment
"""

n = '''
this is multiline comment
'''

def method_name(name):
for element in name:
print(f"{element} \t ==> type is {type(element)}")

array = [a,b,c,d,e,f,g,h,i,j,k,l,o,m,n]
method_name(array)

image-20241217212420173

四、IF判断

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
a = 123
b = 1.23
c = "123"
d = '123'
e = 4 + 5j
f = True
g = None
h = b'123'
# 不可变
i = (a, b, c, d, e, f, g, h)
# 可变
j = [a, b, c, d, e, f, g, h]
k = {'name': 'lol', 'age': 18}
l = {'name', 'lol', 'age', 18}
# 不可变
o = frozenset({'name', 'lol', 'age', 18})


def if_method(names):
for name in names:
if type(name) == int:
print(f"{name} \t ==> is int")
elif type(name) == float:
print(f"{name} \t ==> is float")
elif type(name) == str:
print(f"{name} \t ==> is str")
elif type(name) == complex:
print(f"{name} \t ==> is complex")
elif type(name) == bool:
print(f"{name} \t ==> is bool")
elif type(name) == type(None):
print(f"{name} \t ==> is None")
elif type(name) == bytes:
print(f"{name} \t ==> is bytes")
elif type(name) == tuple:
print(f"{name} \t ==> is tuple")
elif type(name) == list:
print(f"{name} \t ==> is list")
elif type(name) == dict:
print(f"{name} \t ==> is dict")
elif type(name) == set:
print(f"{name} \t ==> is set")
else:
print(f"{name} \t ==> is {type(name).__name__}")


array = [a, b, c, d, e, f, g, h, i, j, k, l, o]
if_method(array)

a = 10
b = 20

if (a and b):
print("1 - 变量 a 和 b 都为 true")
else:
print("1 - 变量 a 和 b 有一个不为 true")

if (a or b):
print("2 - 变量 a 和 b 都为 true,或其中一个变量为 true")
else:
print("2 - 变量 a 和 b 都不为 true")

# 修改变量 a 的值
a = 0
if (a and b):
print("3 - 变量 a 和 b 都为 true")
else:
print("3 - 变量 a 和 b 有一个不为 true")

if (a or b):
print("4 - 变量 a 和 b 都为 true,或其中一个变量为 true")
else:
print("4 - 变量 a 和 b 都不为 true")

if not (a and b):
print("5 - 变量 a 和 b 都为 false,或其中一个变量为 false")
else:
print("5 - 变量 a 和 b 都为 true")

a = 10
b = 20
list = [1, 2, 3, 4, 5]

if (a in list):
print("1 - 变量 a 在给定的列表中 list 中")
else:
print("1 - 变量 a 不在给定的列表中 list 中")

if (b not in list):
print("2 - 变量 b 不在给定的列表中 list 中")
else:
print("2 - 变量 b 在给定的列表中 list 中")

# 修改变量 a 的值
a = 2
if (a in list):
print("3 - 变量 a 在给定的列表中 list 中")
else:
print("3 - 变量 a 不在给定的列表中 list 中")

a = 20
b = 20

if (a is b):
print("1 - a 和 b 有相同的标识")
else:
print("1 - a 和 b 没有相同的标识")

if (id(a) == id(b)):
print("2 - a 和 b 有相同的标识")
else:
print("2 - a 和 b 没有相同的标识")

# 修改变量 b 的值
b = 30
if (a is b):
print("3 - a 和 b 有相同的标识")
else:
print("3 - a 和 b 没有相同的标识")

if (a is not b):
print("4 - a 和 b 没有相同的标识")
else:
print("4 - a 和 b 有相同的标识")

a = [1, 2, 3, 4]
b = a
print(id(a))
print(id(b))
if (a is b) and (a == b) and (id(a) == id(b)):
print("1 - a 和 b 有相同的标识,并且 a 等于 b")
else:
print("1 - a 和 b 没有相同的标识,或者 a 等于 b")

a = [1, 2, 3, 4]
b = a[:]
print(id(a))
print(id(b))
if (a is b) and (a == b):
print("1 - a 和 b 有相同的标识,并且 a 等于 b")
else:
print("1 - a 和 b 没有相同的标识,或者 a 等于 b")

if (id(a) == id(b)):
print("2 - a 和 b 有相同的标识")
else:
print("2 - a 和 b 没有相同的标识")

image-20241217214313728

五、SWITCH…CASE…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

mystatus=400
print(f" {mystatus} ==> {http_error(mystatus)}")

mystatus=500
print(f" {mystatus} ==> {http_error(mystatus)}")

image-20241217215031208

六、FOR循环

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
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in sites:
print(site)
print()

word = 'runoob'
for letter in word:
print(letter)

print()
# 1 到 5 的所有数字:
for number in range(1, 6):
print(f"range(1, 6) ==> {number}")


print()
for number in range(1, 6, 2):
print(f"range(1, 6, 2) ==> {number}")



print()
for number in range(0, 6, 2):
print(f"range(0, 6, 2) ==> {number}")


print()
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in range(len(sites)):
print(f"循环数据 {site} ==> {sites[site]}")


print()
runoob = "Runoob"
for x in range(len(runoob)):
print(f"range('Runoob') {x} ==> {runoob[x]}")


print()
for x in range(6):
print(f"range(6) ==> {x}")
else:
print("Finally finished!")


print()
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")

image-20241217221017121

七、WHILE循环

1
2
3
4
5
6
7
8
9
10
n = 100

sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
if(counter % 10 == 0):
print(f"{sum} ==> {counter}")
print("1 到 %d 之和为: %d" % (n, sum))

image-20241217221304861

八、类型转换

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
print("-------------------------------------------------------------------------------------")
print("隐式类型转换")
# int + int = int
# int + float = float
# float + float = float

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("num_int 数据类型为:", type(num_int))
print("num_flo 数据类型为:", type(num_flo))

print("num_new 值为:", num_new)
print("num_new 数据类型为:", type(num_new))

# int + str = 报错
# float + str = 报错
# str + str = str
# char + str = str


num_int = 123
num_str = "456"

print("num_int 数据类型为:", type(num_int))
print("num_str 数据类型为:", type(num_str))

# TypeError: unsupported operand type(s) for +: 'int' and 'str'
# print(num_int+num_str)

# TypeError: unsupported operand type(s) for +: 'float' and 'str'
# print(num_flo+num_str)

# TypeError: ord() expected a character, but string of length 3 found
# print(ord(num_str)+num_int)

num_str2 = "456"
print(num_str + num_str2)

num_char = 'A'
print(num_char + num_str)

print(ord(num_char))
# ord(num_char) 转为字符的ASCII码 'A'的值是65
print(ord(num_char) + num_int)

print("-------------------------------------------------------------------------------------")
print("显式类型转换")

num_char = 'A'

num_str = "abc"
num_str_a = "a"

num_str_int = "123"
num_int = 123

num_float = 1.23
num_float_str = "1.23"

num_complex = 1.23j

# ValueError: invalid literal for int() with base 10: 'A'
# print(int(num_char_A))

# ValueError: invalid literal for int() with base 10: 'abc'
# print(int(num_str_abc))

int_num_int = int(num_str_int) + num_int
print(f"{int_num_int} \t\t type is {type(int_num_int)}")

str_num_float = float(num_float_str) + num_float
print(f"{str_num_float} \t\t type is {type(str_num_float)}")

str_num_complex = complex(num_float_str) + num_complex
print(f"{str_num_complex} \t\t type is {type(str_num_complex)}")

s = str(num_int)
print(f"{s} \t\t type is {type(s)}")
print(f"{num_int} \t\t type is {type(num_int)}")

s = "12345678"
str_to_tuples = tuple(s)
str_to_list = list(s)
str_to_set = set(s)
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
# str_to_dict = dict(s)
print(f"{str_to_tuples} \t\t type is {type(str_to_tuples)}")
print(f"{str_to_list} \t\t type is {type(str_to_list)}")
print(f"{str_to_set} \t\t type is {type(str_to_set)}")


dict_str = {"a":1}
print(f"{dict_str} \t\t type is {type(dict_str)}")




s = "12345678"
str_to_tuples = tuple(s)
str_to_list = list(str_to_tuples)
str_to_list.append(9)
str_to_set = set(str_to_list)
str_to_set.add(10)
print(f"{str_to_tuples} \t\t type is {type(str_to_tuples)}")
print(f"{str_to_list} \t\t type is {type(str_to_list)}")
print(f"{str_to_set} \t\t type is {type(str_to_set)}")


print("-------------------------------------------------------------------------------------")
print("其他显式转换")
num = 98
num_to_char = chr(num)
char_to_num = ord(num_to_char)
num_to_hex = hex(char_to_num)
num_to_oct = oct(num)

print(f"{num} \t\t type is {type(num)}")
print(f"{num_to_char} \t\t type is {type(num_to_char)}")
print(f"{char_to_num} \t\t type is {type(char_to_num)}")
print(f"{num_to_hex} \t\t type is {type(num_to_hex)}")
print(f"{num_to_oct} \t\t type is {type(num_to_oct)}")

image-20241217212826781

九、函数

十、标准输入输出

十一、类《Class》