1 #################################################### 2 ## 1. 基本操作 3 #################################################### 4 5 python ***.py # 即可执行py文件. 6 # cmd 输入 python,即可进入python命令界面,quit() 退出. 7 print() # 控制台打印 8 input() # 从控制台获取输入数据 9 len() # 获取长度 10 11 #################################################### 12 ## 2. 基本数据类型和操作符 13 #################################################### 14 15 # 控制台可直接进行 加减乘除取余运算. 16 2**3 # => 8 (2的3次方) 17 18 not True # => False 19 not False # => True 20 21 # True and False 代表1和0 22 True + True # => 2 23 True * 8 # => 8 24 False - 5 # => -5 25 26 bool(0) # => False 27 bool(4) # => True 28 bool(-6) # => True 29 0 and 2 # => 0 30 -5 or 0 # => -5 31 32 #################################################### 33 ## 3. 变量和集合 34 #################################################### 35 36 # string 37 "Hello " + "world!" # => "Hello world!" 38 "Hello " "world!" # => "Hello world!" 39 "This is a string"[0] # => 'T' 40 41 "{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" 42 "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") 43 "{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" 44 "%s can be %s the %s way" % ("Strings", "interpolated", "old") 45 46 name = "Reiko" 47 f"{name} is {len(name)} characters long." 48 49 ----------------------------------------------------- 50 51 # 三目运算 52 "yahoo!" if 3 > 2 else 2 # => "yahoo!" 53 54 ----------------------------------------------------- 55 56 # Lists store sequences 57 li = [] 58 other_li = [3, 4, 5] 59 li.append(1) # li is now [1] 60 li.append(2) # li is now [1, 2] 61 li.append(4) # li is now [1, 2, 4] 62 li.append(3) # li is now [1, 2, 4, 3] 63 # Remove from the end with pop 64 li.pop() # => 3 and li is now [1, 2, 4] 65 li.append(3) # li is now [1, 2, 4, 3] 66 li[0] # => 1 67 # Look at the last element 68 li[-1] # => 3 69 li[1:3] # => [2, 4] 70 li[2:] # => [4, 3] 71 li[:3] # => [1, 2, 4] 72 # li[start:end:step] 73 li[::2] # =>[1, 4] 74 li[::-1] # => [3, 4, 2, 1] 75 li2 = li[:] # => li2 = [1, 2, 4, 3], but li2 is li[:] will result in false 76 del li[2] # li is now [1, 2, 3] 77 li.remove(2) # 移除 "2" 78 li.insert(1, 2) # Index 1 插入 "2" 79 li.index(2) # => 1 "2"的 Index 80 li + other_li # => [1, 2, 3, 3, 4, 5] 81 li.extend(other_li) # li Now is [1, 2, 3, 3, 4, 5] 82 1 in li # => True 83 84 # array矩阵a 85 import numpy 86 a = numpy.array([1, 2, 3], 87 [4, 5, 6], 88 [7, 8, 9]) 89 a[:, 0: 2] # ","前代表行,后代表列, 冒号占位表示所有行, 0和 1 列 90 a[1, :] # 下标为 1 的行, 所有列的内容 91 92 ----------------------------------------------------- 93 94 # Tuples are like lists but are immutable. 95 tup = (1, 2, 3) 96 tup[0] # => 1 97 tup[:2] # => (1, 2) 98 # 长度为 1的 Tuples,元素后面必须有逗号.其他长度的则不用 99 type((1)) # => <class 'int'> 100 type((1,)) # => <class 'tuple'> 101 type(()) # => <class 'tuple'> 102 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) 103 # You can unpack tuples (or lists) into variables 104 a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 105 a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 106 d, e, f = 4, 5, 6 107 e, d = d, e # d is now 5 and e is now 4 108 109 ----------------------------------------------------- 110 111 # Dictionaries store, mappings from keys to values, Similar to the java Map 112 empty_dict = {} 113 filled_dict = {"one": 1, "two": 2, "three": 3} 114 # keys are immutable types, include ints, floats, strings, tuples 115 invalid_dict = {[1,2,3]: "123"} # TypeError: key is 'list' 116 valid_dict = {(1,2,3): [1,2,3]} 117 # 根据键取值 118 filled_dict["one"] # => 1 119 filled_dict["four"] # KeyError 120 # 遍历键和值 121 list(filled_dict.keys()) # => ["three", "two", "one"] 122 list(filled_dict.values()) # => [3, 2, 1] 123 # 只可对键 验证是否存在 124 "one" in filled_dict # => True 125 1 in filled_dict # => False 126 # Use "get()" method to avoid the KeyError 127 filled_dict.get("one") # => 1 128 filled_dict.get("four") # => None 129 # The get method supports a default value when the value is missing 130 filled_dict.get("one", 4) # => 1 131 filled_dict.get("four", 4) # => 4 132 # setdefault() 只在键不存在时才能赋值 133 filled_dict.setdefault("five", 5) 134 filled_dict.setdefault("five", 6) # "five" is still '5' 135 # Adding or update 136 filled_dict.update({"four":4}) 137 filled_dict[4] = 4 # ibidem 138 # Remove 139 del filled_dict["one"] 140 # After Python 3.5 you can also use the additional unpacking options ??? 141 {'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} 142 {'a': 1, **{'a': 2}} # => {'a': 2} 143 144 ----------------------------------------------------- 145 146 # Sets 147 empty_set = set() 148 invalid_set = {[1], 1} # TypeError: unhashable type: 'list' 149 valid_set = {(1,), 1} 150 some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} 151 some_set.add(5) # some_set is now {1, 2, 3, 4, 5} 152 other_set = {3, 4, 5, 6} 153 some_set & other_set # => {3, 4, 5} 154 some_set | other_set # => {1, 2, 3, 4, 5, 6} 155 # Do set symmetric difference with ^ 156 {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} 157 {1, 2} >= {1, 2, 3} # => False 158 {1, 2} <= {1, 2, 3} # => True 159 2 in filled_set # => True 160 161 #################################################### 162 ## 4. 条件语句和迭代 163 #################################################### 164 165 # if判断 166 if some_var > 10: 167 print("some_var is totally bigger than 10.") 168 elif some_var < 10: 169 print("some_var is smaller than 10.") 170 else: 171 print("some_var is indeed 10.") 172 173 ----------------------------------------------------- 174 175 # For loops 176 for animal in ["dog", "cat", "mouse"]: 177 print("{} is a animal".format(animal)) 178 for i in range(4): # 0~4 179 for i in range(4, 8): # 4~7 180 for i in range(4, 12, 3): # 4,7,10 181 182 ----------------------------------------------------- 183 184 # While 185 x = 0 186 while x < 4: 187 print(x) 188 x += 1 189 190 ----------------------------------------------------- 191 192 # Handle exceptions with a try/except block 193 try: 194 # Use "raise" to raise an error 195 raise IndexError("This is an index error") 196 except IndexError as e: 197 pass # Pass is just a no-op. Usually you would do recovery here. 198 except (TypeError, NameError): 199 pass # Multiple exceptions can be handled together, if required. 200 else: # Optional clause to the try/except block. Must follow all except blocks 201 print("All good!") # Runs only if the code in try raises no exceptions 202 finally: # Execute under all circumstances 203 print("We can clean up resources here") 204 205 ----------------------------------------------------- 206 207 # Iterable 208 filled_dict = {"one": 1, "two": 2, "three": 3} 209 our_iterable = filled_dict.keys() # type: dict_keys 210 for i in our_iterable: 211 print(i) # Prints one, two, three 212 our_iterator = iter(our_iterable) 213 next(our_iterator) # => "one" 214 next(our_iterator) # => "two" 215 next(our_iterator) # => "three" 216 next(our_iterator) # Raises StopIteration 217 list(filled_dict.keys()) # type: list 218 219 #################################################### 220 ## 5. 方法 221 #################################################### 222 223 def add(x, y): 224 print("x is {} and y is {}".format(x, y)) 225 return x, y # 返回tuples类型值,可省略括号 226 add(y=6, x=5) # 任意顺序传入参数 227 228 ----------------------------------------------------- 229 230 # 方法传入多个参数写法: 231 def all_the_args(*tuples, **map): 232 print(tuples) 233 print(map) 234 all_the_args(1, 2, a=3, b=4) # prints:(1, 2){"a": 3, "b": 4} 235 # 或调换顺序,先申明变量: 236 args = (1, 2, 3, 4) 237 kwargs = {"a": 3, "b": 4} 238 all_the_args(*args) 239 all_the_args(*args, **kwargs) 240 241 ----------------------------------------------------- 242 243 # Function Scope 244 x = 5 245 def set_x(num): 246 x = num # => 43, Local var x 247 print(x) # => 43 248 def set_global_x(num): 249 global x # global var x 250 print(x) # => 5 251 x = num # global var x is now set to 6 252 print(x) # => 6 253 set_x(43) 254 set_global_x(6) 255 256 ----------------------------------------------------- 257 258 # Python has first class functions 259 def create_adder(x): 260 def adder(y): 261 return x + y 262 return adder 263 add_10 = create_adder(10) 264 add_10(3) # x is 10, y is 3 265 266 ----------------------------------------------------- 267 268 # lambda 匿名方法 269 (lambda x: x > 2)(3) # => True 270 (lambda x, y: x ** 2 + y ** 2)(2, 1)# => 5 271 272 ----------------------------------------------------- 273 274 # 内置高阶函数??? 275 list(map((lambda x: x**2), [1, 2, 3, 4, 5])) # map() 逐个把list里面的每个值, 放进前面方法运行 => [1, 4, 9, 16, 25] 276 list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] 277 list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] 278 279 ----------------------------------------------------- 280 281 # 嵌套 282 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] 283 [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] 284 | 285 return 286 | 287 {x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} 288 {x: x**2 for x in range(5)} # => {0:0, 1:1, 2:4, 3:9, 4:16} 289 {x: x**2 for x in range(5)} 290 291 #################################################### 292 ## 6. Modules 293 #################################################### 294 295 # import modules 296 import math as m 297 print(math.sqrt(16)) # => 4.0 298 # get specific functions from a module 299 from math import ceil, floor 300 print(ceil(3.7)) # => 4.0 301 print(floor(3.7)) # => 3.0 302 dir(math) 303 304 #################################################### 305 ## 7. read and write 306 #################################################### 307 308 f = open("***.txt", "r") 309 g = f.read() 310 print(g) 311 f.close() 312 313 f = open("***.txt", "w") 314 f.write("111111") 315 f.write(" ") 316 f.close()