python语法速成方法_学习笔记之X分钟速成Python3

1 #用井字符开头的是单行注释

2

3 """多行字符串用三个引号4 包裹,也常被用来做多5 行注释6 """

7

8 ####################################################

9 ## 1. 原始数据类型和运算符

10 ####################################################

11

12 #整数

13 3 #=> 3

14

15 #算术没有什么出乎意料的

16 1 + 1 #=> 2

17 8 - 1 #=> 7

18 10 * 2 #=> 20

19

20 #但是除法例外,会自动转换成浮点数

21 35 / 5 #=> 7.0

22 5 / 3 #=> 1.6666666666666667

23

24 #整数除法的结果都是向下取整

25 5 // 3 #=> 1

26 5.0 // 3.0 #=> 1.0 # 浮点数也可以

27 -5 // 3 #=> -2

28 -5.0 // 3.0 #=> -2.0

29

30 #浮点数的运算结果也是浮点数

31 3 * 2.0 #=> 6.0

32

33 #模除

34 7 % 3 #=> 1

35

36 #x的y次方

37 2**4 #=> 16

38

39 #用括号决定优先级

40 (1 + 3) * 2 #=> 8

41

42 #布尔值

43 True44 False45

46 #用not取非

47 not True #=> False

48 not False #=> True

49

50 #逻辑运算符,注意and和or都是小写

51 True and False #=> False

52 False or True #=> True

53

54 #整数也可以当作布尔值

55 0 and 2 #=> 0

56 -5 or 0 #=> -5

57 0 == False #=> True

58 2 == True #=> False

59 1 == True #=> True

60

61 #用==判断相等

62 1 == 1 #=> True

63 2 == 1 #=> False

64

65 #用!=判断不等

66 1 != 1 #=> False

67 2 != 1 #=> True

68

69 #比较大小

70 1 < 10 #=> True

71 1 > 10 #=> False

72 2 <= 2 #=> True

73 2 >= 2 #=> True

74

75 #大小比较可以连起来!

76 1 < 2 < 3 #=> True

77 2 < 3 < 2 #=> False

78

79 #字符串用单引双引都可以

80 "这是个字符串"

81 '这也是个字符串'

82

83 #用加号连接字符串

84 "Hello" + "world!" #=> "Hello world!"

85

86 #字符串可以被当作字符列表

87 "This is a string"[0] #=> 'T'

88

89 #用.format来格式化字符串

90 "{} can be {}".format("strings", "interpolated")91

92 #可以重复参数以节省时间

93 "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")94 #=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"

95

96 #如果不想数参数,可以用关键字

97 "{name} wants to eat {food}".format(name="Bob", food="lasagna")98 #=> "Bob wants to eat lasagna"

99

100 #如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法

101 "%s can be %s the %s way" % ("strings", "interpolated", "old")102

103 #None是一个对象

104 None #=> None

105

106 #当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。

107 "etc" is None #=> False

108 None is None #=> True

109

110 #None,0,空字符串,空列表,空字典都算是False

111 #所有其他值都是True

112 bool(0) #=> False

113 bool("") #=> False

114 bool([]) #=> False

115 bool({}) #=> False

116

117

118 ####################################################

119 ## 2. 变量和集合

120 ####################################################

121

122 #print是内置的打印函数

123 print("I'm Python. Nice to meet you!")124

125 #在给变量赋值前不用提前声明

126 #传统的变量命名是小写,用下划线分隔单词

127 some_var = 5

128 some_var #=> 5

129

130 #访问未赋值的变量会抛出异常

131 #参考流程控制一段来学习异常处理

132 some_unknown_var #抛出NameError

133

134 #用列表(list)储存序列

135 li =[]136 #创建列表时也可以同时赋给元素

137 other_li = [4, 5, 6]138

139 #用append在列表最后追加元素

140 li.append(1) #li现在是[1]

141 li.append(2) #li现在是[1, 2]

142 li.append(4) #li现在是[1, 2, 4]

143 li.append(3) #li现在是[1, 2, 4, 3]

144 #用pop从列表尾部删除

145 li.pop() #=> 3 且li现在是[1, 2, 4]

146 #把3再放回去

147 li.append(3) #li变回[1, 2, 4, 3]

148

149 #列表存取跟数组一样

150 li[0] #=> 1

151 #取出最后一个元素

152 li[-1] #=> 3

153

154 #越界存取会造成IndexError

155 li[4] #抛出IndexError

156

157 #列表有切割语法

158 li[1:3] #=> [2, 4]

159 #取尾

160 li[2:] #=> [4, 3]

161 #取头

162 li[:3] #=> [1, 2, 4]

163 #隔一个取一个

164 li[::2] #=>[1, 4]

165 #倒排列表

166 li[::-1] #=> [3, 4, 2, 1]

167 #可以用三个参数的任何组合来构建切割

168 #li[始:终:步伐]

169

170 #用del删除任何一个元素

171 del li[2] #li is now [1, 2, 3]

172

173 #列表可以相加

174 #注意:li和other_li的值都不变

175 li + other_li #=> [1, 2, 3, 4, 5, 6]

176

177 #用extend拼接列表

178 li.extend(other_li) #li现在是[1, 2, 3, 4, 5, 6]

179

180 #用in测试列表是否包含值

181 1 in li #=> True

182

183 #用len取列表长度

184 len(li) #=> 6

185

186

187 #元组是不可改变的序列

188 tup = (1, 2, 3)189 tup[0] #=> 1

190 tup[0] = 3 #抛出TypeError

191

192 #列表允许的操作元组大都可以

193 len(tup) #=> 3

194 tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)

195 tup[:2] #=> (1, 2)

196 2 in tup #=> True

197

198 #可以把元组合列表解包,赋值给变量

199 a, b, c = (1, 2, 3) #现在a是1,b是2,c是3

200 #元组周围的括号是可以省略的

201 d, e, f = 4, 5, 6

202 #交换两个变量的值就这么简单

203 e, d = d, e #现在d是5,e是4

204

205

206 #用字典表达映射关系

207 empty_dict ={}208 #初始化的字典

209 filled_dict = {"one": 1, "two": 2, "three": 3}210

211 #用[]取值

212 filled_dict["one"] #=> 1

213

214

215 #用 keys 获得所有的键。

216 #因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。

217 #注意:字典键的顺序是不定的,你得到的结果可能和以下不同。

218 list(filled_dict.keys()) #=> ["three", "two", "one"]

219

220

221 #用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。

222 list(filled_dict.values()) #=> [3, 2, 1]

223

224

225 #用in测试一个字典是否包含一个键

226 "one" in filled_dict #=> True

227 1 in filled_dict #=> False

228

229 #访问不存在的键会导致KeyError

230 filled_dict["four"] #KeyError

231

232 #用get来避免KeyError

233 filled_dict.get("one") #=> 1

234 filled_dict.get("four") #=> None

235 #当键不存在的时候get方法可以返回默认值

236 filled_dict.get("one", 4) #=> 1

237 filled_dict.get("four", 4) #=> 4

238

239 #setdefault方法只有当键不存在的时候插入新值

240 filled_dict.setdefault("five", 5) #filled_dict["five"]设为5

241 filled_dict.setdefault("five", 6) #filled_dict["five"]还是5

242

243 #字典赋值

244 filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}

245 filled_dict["four"] = 4 #另一种赋值方法

246

247 #用del删除

248 del filled_dict["one"] #从filled_dict中把one删除

249

250

251 #用set表达集合

252 empty_set =set()253 #初始化一个集合,语法跟字典相似。

254 some_set = {1, 1, 2, 2, 3, 4} #some_set现在是{1, 2, 3, 4}

255

256 #可以把集合赋值于变量

257 filled_set =some_set258

259 #为集合添加元素

260 filled_set.add(5) #filled_set现在是{1, 2, 3, 4, 5}

261

262 #& 取交集

263 other_set = {3, 4, 5, 6}264 filled_set & other_set #=> {3, 4, 5}

265

266 #| 取并集

267 filled_set | other_set #=> {1, 2, 3, 4, 5, 6}

268

269 #- 取补集

270 {1, 2, 3, 4} - {2, 3, 5} #=> {1, 4}

271

272 #in 测试集合是否包含元素

273 2 in filled_set #=> True

274 10 in filled_set #=> False

275

276

277 ####################################################

278 ## 3. 流程控制和迭代器

279 ####################################################

280

281 #先随便定义一个变量

282 some_var = 5

283

284 #这是个if语句。注意缩进在Python里是有意义的

285 #印出"some_var比10小"

286 if some_var > 10:287 print("some_var比10大")288 elif some_var < 10: #elif句是可选的

289 print("some_var比10小")290 else: #else也是可选的

291 print("some_var就是10")292

293

294 """

295 用for循环语句遍历列表296 打印:297 dog is a mammal298 cat is a mammal299 mouse is a mammal300 """

301 for animal in ["dog", "cat", "mouse"]:302 print("{} is a mammal".format(animal))303

304 """

305 "range(number)"返回数字列表从0到给的数字306 打印:307 0308 1309 2310 3311 """

312 for i in range(4):313 print(i)314

315 """

316 while循环直到条件不满足317 打印:318 0319 1320 2321 3322 """

323 x =0324 while x < 4:325 print(x)326 x += 1 #x = x + 1 的简写

327

328 #用try/except块处理异常状况

329 try:330 #用raise抛出异常

331 raise IndexError("This is an index error")332 exceptIndexError as e:333 pass #pass是无操作,但是应该在这里处理错误

334 except(TypeError, NameError):335 pass #可以同时处理不同类的错误

336 else: #else语句是可选的,必须在所有的except之后

337 print("All good!") #只有当try运行完没有错误的时候这句才会运行

338

339

340 #Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列

341 #的对象。比如说上面range返回的对象就是可迭代的。

342

343 filled_dict = {"one": 1, "two": 2, "three": 3}344 our_iterable =filled_dict.keys()345 print(our_iterable) #=> dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象

346

347 #可迭代对象可以遍历

348 for i inour_iterable:349 print(i) #打印 one, two, three

350

351 #但是不可以随机访问

352 our_iterable[1] #抛出TypeError

353

354 #可迭代对象知道怎么生成迭代器

355 our_iterator =iter(our_iterable)356

357 #迭代器是一个可以记住遍历的位置的对象

358 #用__next__可以取得下一个元素

359 our_iterator.__next__() #=> "one"

360

361 #再一次调取__next__时会记得位置

362 our_iterator.__next__() #=> "two"

363 our_iterator.__next__() #=> "three"

364

365 #当迭代器所有元素都取出后,会抛出StopIteration

366 our_iterator.__next__() #抛出StopIteration

367

368 #可以用list一次取出迭代器所有的元素

369 list(filled_dict.keys()) #=> Returns ["one", "two", "three"]

370

371

372

373 ####################################################

374 ## 4. 函数

375 ####################################################

376

377 #用def定义新函数

378 defadd(x, y):379 print("x is {} and y is {}".format(x, y))380 return x + y #用return语句返回

381

382 #调用函数

383 add(5, 6) #=> 印出"x is 5 and y is 6"并且返回11

384

385 #也可以用关键字参数来调用函数

386 add(y=6, x=5) #关键字参数可以用任何顺序

387

388

389 #我们可以定义一个可变参数函数

390 def varargs(*args):391 returnargs392

393 varargs(1, 2, 3) #=> (1, 2, 3)

394

395

396 #我们也可以定义一个关键字可变参数函数

397 def keyword_args(**kwargs):398 returnkwargs399

400 #我们来看看结果是什么:

401 keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}

402

403

404 #这两种可变参数可以混着用

405 def all_the_args(*args, **kwargs):406 print(args)407 print(kwargs)408 """

409 all_the_args(1, 2, a=3, b=4) prints:410 (1, 2)411 {"a": 3, "b": 4}412 """

413

414 #调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。

415 args = (1, 2, 3, 4)416 kwargs = {"a": 3, "b": 4}417 all_the_args(*args) #相当于 foo(1, 2, 3, 4)

418 all_the_args(**kwargs) #相当于 foo(a=3, b=4)

419 all_the_args(*args, **kwargs) #相当于 foo(1, 2, 3, 4, a=3, b=4)

420

421

422 #函数作用域

423 x = 5

424

425 defsetX(num):426 #局部作用域的x和全局域的x是不同的

427 x = num #=> 43

428 print (x) #=> 43

429

430 defsetGlobalX(num):431 globalx432 print (x) #=> 5

433 x = num #现在全局域的x被赋值

434 print (x) #=> 6

435

436 setX(43)437 setGlobalX(6)438

439

440 #函数在Python是一等公民

441 defcreate_adder(x):442 defadder(y):443 return x +y444 returnadder445

446 add_10 = create_adder(10)447 add_10(3) #=> 13

448

449 #也有匿名函数

450 (lambda x: x > 2)(3) #=> True

451

452 #内置的高阶函数

453 map(add_10, [1, 2, 3]) #=> [11, 12, 13]

454 filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]

455

456 #用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。

457 [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]

458 [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]

459

460 ####################################################

461 ## 5. 类

462 ####################################################

463

464

465 #定义一个继承object的类

466 classHuman(object):467

468 #类属性,被所有此类的实例共用。

469 species = "H. sapiens"

470

471 #构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属

472 #性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这

473 #种格式。

474 def __init__(self, name):475 #Assign the argument to the instance's name attribute

476 self.name =name477

478 #实例方法,第一个参数总是self,就是这个实例对象

479 defsay(self, msg):480 return "{name}: {message}".format(name=self.name, message=msg)481

482 #类方法,被所有此类的实例共用。第一个参数是这个类对象。

483 @classmethod484 defget_species(cls):485 returncls.species486

487 #静态方法。调用时没有实例或类的绑定。

488 @staticmethod489 defgrunt():490 return "*grunt*"

491

492

493 #构造一个实例

494 i = Human(name="Ian")495 print(i.say("hi")) #印出 "Ian: hi"

496

497 j = Human("Joel")498 print(j.say("hello")) #印出 "Joel: hello"

499

500 #调用一个类方法

501 i.get_species() #=> "H. sapiens"

502

503 #改一个共用的类属性

504 Human.species = "H. neanderthalensis"

505 i.get_species() #=> "H. neanderthalensis"

506 j.get_species() #=> "H. neanderthalensis"

507

508 #调用静态方法

509 Human.grunt() #=> "*grunt*"

510

511

512 ####################################################

513 ## 6. 模块

514 ####################################################

515

516 #用import导入模块

517 importmath518 print(math.sqrt(16)) #=> 4.0

519

520 #也可以从模块中导入个别值

521 from math importceil, floor522 print(ceil(3.7)) #=> 4.0

523 print(floor(3.7)) #=> 3.0

524

525 #可以导入一个模块中所有值

526 #警告:不建议这么做

527 from math import *

528

529 #如此缩写模块名字

530 importmath as m531 math.sqrt(16) == m.sqrt(16) #=> True

532

533 #Python模块其实就是普通的Python文件。你可以自己写,然后导入,

534 #模块的名字就是文件的名字。

535

536 #你可以这样列出一个模块里所有的值

537 importmath538 dir(math)539

540

541 ####################################################

542 ## 7. 高级用法

543 ####################################################

544

545 #用生成器(generators)方便地写惰性运算

546 defdouble_numbers(iterable):547 for i initerable:548 yield i +i549

550 #生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的

551 #值全部算好。

552 #553 #range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。

554 #555 #如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。

556 range_ = range(1, 900000000)557 #当找到一个 >=30 的结果就会停

558 #这意味着 `double_numbers` 不会生成大于30的数。

559 for i indouble_numbers(range_):560 print(i)561 if i >= 30:562 break

563

564

565 #装饰器(decorators)

566 #这个例子中,beg装饰say

567 #beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。

568 from functools importwraps569

570

571 defbeg(target_function):572 @wraps(target_function)573 def wrapper(*args, **kwargs):574 msg, say_please = target_function(*args, **kwargs)575 ifsay_please:576 return "{} {}".format(msg, "Please! I am poor :(")577 returnmsg578

579 returnwrapper580

581

582 @beg583 def say(say_please=False):584 msg = "Can you buy me a beer?"

585 returnmsg, say_please586

587

588 print(say()) #Can you buy me a beer?

589 print(say(say_please=True)) #Can you buy me a beer? Please! I am poor :(

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值