1. Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
  2. #Chapter 5 条件, 循环和其它语句
  3. #5.1 print和import的很多其它信息
  4. #对于非常多应用程序来说, 使用logging模块记日志比print语句更合适
  5. #5.1.1 使用逗号输出
  6. #能够看到, 每隔參数之间都自己主动插入了一个空格符
  7. >>> print 'Age:',42
  8. Age: 42
  9. >>> 1,2,3
  10. (1, 2, 3)
  11. #print的參数并不像我们预期那样构成一个元组
  12. >>> print 1,2,3
  13. 1 2 3
  14. >>> print (1,2,3)
  15. (1, 2, 3)
  16. >>> name='Gumby'
  17. >>> salution='Mr.'
  18. >>> greeting='Hello,'
  19. >>> print greeting, salution, name
  20. Hello, Mr. Gumby
  21. >>> greeting='Hello'
  22. >>> print greeting, ',', salution, name
  23. Hello , Mr. Gumby
  24. >>> print greeting + ',', salution, name
  25. Hello, Mr. Gumby
  26. #假设在结尾处加上逗号,那么接下来的语句会与前一语句在同一行打印(仅仅在脚本中起作用,在交互式Python会话中无效)
  27. print 'Hello,',
  28. print 'world!'
  29. #输出Hello, world!
  30. #5.1.2 import语句
  31. #import somemodule
  32. #from somemodule import somefunction
  33. #from somemodule import somefunction, anotherfunction, yetanotherfunction
  34. #from somemodule import *
  35. #为模块提供别名
  36. >>> import math as foobar
  37. >>> foobar.sqrt(4)
  38. 2.0
  39. #为函数提供别名
  40. >>> from math import sqrt as foobar
  41. >>> foobar(4)
  42. 2.0
  43. #给不同模块中的同名函数提供别名
  44. #from module1 import open as open1
  45. #from module2 import open as open2
  46. #5.2 赋值魔法
  47. #5.2.1 序列解包(sequence unpacking)
  48. >>> x, y, z = 1, 2, 3
  49. >>> print x, y, z
  50. 1 2 3
  51. >>> x, y = y, x
  52. >>> print x, y, z
  53. 2 1 3
  54. >>> values = 1,2,3
  55. >>> values
  56. (1, 2, 3)
  57. >>> x,y,z=values
  58. >>> x
  59. 1
  60. >>> y
  61. 2
  62. >>> z
  63. 3
  64. >>> scoundrel={'name':'Robin', 'girlfriend':'Marion'}
  65. >>> key, value = scoundrel.popitem()
  66. >>> key
  67. 'girlfriend'
  68. >>> value
  69. 'Marion'
  70. >>> x,y,z = 1,2
  71.  
  72. Traceback (most recent call last):
  73. File "<pyshell#31>", line 1, in <module>
  74. x,y,z = 1,2
  75. ValueError: need more than 2 values to unpack
  76. >>> x,y,z=1,2,3,4
  77.  
  78. Traceback (most recent call last):
  79. File "<pyshell#32>", line 1, in <module>
  80. x,y,z=1,2,3,4
  81. ValueError: too many values to unpack
  82. #Python 3.0 中有另外一个解包的特性
  83. #a,b,rest*=[1,2,3,4]
  84. #rest的结果将会是[3,4]
  85. #5.2.2 链式赋值
  86. #x=y=somefunction
  87. #等效于
  88. #y=somefunction
  89. #x=y
  90.  
  91. #5.2.3 增量赋值(augmented assignment)
  92. >>> x=2
  93. >>> x += 1
  94. >>> x *= 2
  95. >>> x
  96. 6
  97. >>> fnord = 'foo'
  98. >>> fnord += 'bar'
  99. >>> fnord *= 2
  100. >>> fnord
  101. 'foobarfoobar'
  102. #语句块: 缩排的乐趣
  103. #5.4 条件和条件语句
  104. # False None 0 "" '' () [] {} 会被解释器看做假
  105. >>> True
  106. True
  107. >>> False
  108. False
  109. >>> True == 1
  110. True
  111. #标准的布尔值为False(0)和True(1)
  112. >>> False == 0
  113. True
  114. >>> True + False + 42
  115. 43
  116. #bool函数能够用来(和list, str以及tuple相似)转换其它值
  117. >>> bool('I think, therefore I am')
  118. True
  119. >>> bool(42)
  120. True
  121. >>> bool('')
  122. False
  123. >>> bool(0)
  124. False
  125. >>> bool([])
  126. False
  127. >>> bool(())
  128. False
  129. >>> bool({})
  130. False
  131. #5.4.2 条件运行和if语句
  132. >>> name = raw_input('What is your name?
  133.  
  134. ')
  135. What is your name? Gumby
  136. >>> if name.endswith('Gumby'):
  137. ... print 'Hello, Mr. Gumby'
  138. ...
  139. Hello, Mr. Gumby
  140. #5.4.3 else子句
  141. >>> name = raw_input('What is your name? ')
  142. What is your name?
  143.  
  144. Jon
  145. >>> if name.endswith('Gumby'):
  146. ... print 'Hello, Mr. Gumby'
  147. ... else:
  148. ... print 'Hello, stranger'
  149. ...
  150. Hello, stranger
  151. #5.4.4 elif子句
  152. >>> num = input('Enter a number: ')
  153. Enter a number: 0
  154. >>> if num > 0:
  155. ... print 'The number is positive'
  156. ... elif num < 0:
  157. ... print 'The number is negative'
  158. ... else:
  159. ... print 'The number is zero'
  160. ...
  161. The number is zero
  162. #5.4.5 嵌套代码块
  163. >>> name = raw_input('What is your name? ')
  164. What is your name? Mrs. Gumby
  165. >>> if name.endswith('Gumby'):
  166. ... if name.startswith('Mr.'):
  167. ... print 'Hello, Mr. Gumby'
  168. ... elif name.startswith('Mrs.'):
  169. ... print 'Hello, Mrs. Gumby'
  170. ... else:
  171. ... print 'Hello, Gumby'
  172. ... else:
  173. ... print 'Hello, stranger'
  174. ...
  175. Hello, Mrs. Gumby
  176. #链式比較运算
  177. #比較对象的时候能够使用内建的cmp函数
  178. >>> age=10
  179. >>> 0<age<100
  180. True
  181. >>> age=-1
  182. >>> 0<age<100
  183. False
  184. #相等运算符
  185. >>> "foo" == "foo"
  186. True
  187. >>> "foo" == "bar"
  188. False
  189. >>> "foo" = "foo"
  190. File "<stdin>", line 1
  191. SyntaxError: can't assign to literal
  192. #同一性运算符
  193. #避免将is运算符用于比較相似数值和字符串这类不可变值.
  194. >>> x=y=[1,2,3]
  195. >>> z=[1,2,3]
  196. >>> x == y
  197. True
  198. >>> x == z
  199. True
  200. >>> x is y
  201. True
  202. >>> x is z
  203. False
  204. >>>
  205. >>> x is z
  206. False
  207. >>> x = [1,2,3]
  208. >>> y = [2,4]
  209. >>> x is not y
  210. True
  211. >>> del x[2]
  212. >>> y[1]=1
  213. >>> y.reverse()
  214. >>> x == y
  215. True
  216. >>> x is y
  217. False
  218. #in: 成员资格运算符
  219. >>> name = raw_input('What is your name? ')
  220. What is your name?
  221.  
  222. Jonathan
  223. >>> if 's' in name:
  224. ... print 'Your name contains the letter "s".'
  225. ... else:
  226. ... print 'Your name does not contain the letter "s".'
  227. ...
  228. Your name does not contain the letter "s".
  229. >>> "alpha" < "beta"
  230. True
  231. >>> 'FnOrd'.lower() == 'Fnord'.lower()
  232. True
  233. >>> [1,2] < [2,1]
  234. True
  235. >>> [2,[1,4]]<[2,[1,5]]
  236. True
  237. #布尔运算符
  238.  
  239. >>> number = input('Enter a number between 1 and 10: ')
  240. Enter a number between 1 and 10: 8
  241. >>> if number <= 10:
  242. ... if number >=1:
  243. ... print 'Great!'
  244. ... else:
  245. ... print 'Wrong!'
  246. ... else:
  247. ... print 'Wrong!'
  248. ...
  249. Great!
  250. >>> number = input('Enter a number between 1 and 10: ')
  251. Enter a number between 1 and 10: 6
  252. >>> if number <= 10 and number >= 1:
  253. ... print 'Great!'
  254. ... else:
  255. ... print 'Wrong!'
  256. ...
  257. Great!
  258. >>> number = input('Enter a number between 1 and 10: ')
  259. Enter a number between 1 and 10: 11
  260. >>> if 1 <= number <= 10:
  261. ... print 'Great!'
  262. ... else:
  263. ... print 'Wrong!'
  264. ...
  265. Wrong!
  266. >>> name = raw_input('Please enter your name: ') or '<unknown>'
  267. Please enter your name:
  268. >>> name
  269. '<unknown>'
  270. #短路逻辑和条件表达式
  271. #相似C和Java中的三元运算符
  272. >>> name = 'Jon'if True else 'Jack'
  273. >>> name
  274. 'Jon'
  275. >>> name = 'Jon'if False else 'Jack'
  276. >>> name
  277. 'Jack'
  278. #5.4.7 断言
  279. >>> age = 10
  280. >>> assert 0 < age < 100
  281. >>> age = -1
  282. >>> assert 0 < age < 100
  283. Traceback (most recent call last):
  284. File "<stdin>", line 1, in <module>
  285. AssertionError
  286. #条件后能够加入逗号和字符串,用来解释断言
  287. >>> age = -1
  288. >>> assert 0 < age < 100, 'The age must be realistic'
  289. Traceback (most recent call last):
  290. File "<stdin>", line 1, in <module>
  291. AssertionError: The age must be realistic
  292. #5.5 循环
  293. #5.5.1 while循环
  294. >>> x=1
  295. >>> while x <= 100:
  296. ... print x
  297. ... x +=1
  298. ...
  299. 1
  300. 2
  301. 3
  302. ...
  303. 100
  304. >>> x
  305. 101
  306.  
  307. >>> name = ''
  308. >>> while not name:
  309. ... name = raw_input('Please enter your name: ')
  310. ...
  311. Please enter your name:
  312. Please enter your name:
  313. Please enter your name: Jon
  314. >>> print 'Hello, %s!' % name
  315. Hello, Jon!
  316. >>> name = ''
  317. >>> while not name or name.isspace():
  318. ... name = raw_input('Please enter your name: ')
  319. ...
  320. Please enter your name:
  321. Please enter your name:
  322. Please enter your name: Chan
  323. >>> print 'Hello, %s!' % name
  324. Hello, Chan!
  325. >>> while not name.strip():
  326. ... name = raw_input('Please enter your name: ')
  327. ...
  328. >>> name = ''
  329. >>> while not name.strip():
  330. ... name = raw_input('Please enter your name: ')
  331. ...
  332. Please enter your name:
  333. Please enter your name:
  334. Please enter your name: Kingston
  335. >>> print 'Hello, %s!' % name
  336. Hello, Kingston!
  337.  
  338. #5.5.2 for循环
  339. >>> words=['this', 'is', 'an', 'ex', 'parrot']
  340. >>> for word in words:
  341. ... print word
  342. ...
  343. this
  344. is
  345. an
  346. ex
  347. parrot
  348. >>> numbers = [0,1,2,3,4,5,6,7,8,9]
  349. >>> for number in numbers:
  350. ... print number
  351. ...
  352. 0
  353. 1
  354. 2
  355. 3
  356. 4
  357. 5
  358. 6
  359. 7
  360. 8
  361. 9
  362. >>> range(10)
  363. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  364. #假设能使用for循环,就尽量不用while循环
  365. #当须要迭代一个巨大的序列时,xrange会比range更高效
  366. >>> for number in range(1,5):
  367. ... print number
  368. ...
  369. 1
  370. 2
  371. 3
  372. 4
  373. #5.5.3 循环遍历字典元素
  374. >>> d={'x':1, 'y':2, 'z':3}
  375. >>> for key in d:
  376. ... print key, 'corresponds to', d[key]
  377. ...
  378. y corresponds to 2
  379. x corresponds to 1
  380. z corresponds to 3
  381. >>> for key, value in d.items():
  382. ... print kye, 'corresponds to', value
  383. ...
  384. Traceback (most recent call last):
  385. File "<stdin>", line 2, in <module>
  386. NameError: name 'kye' is not defined
  387. >>> for key, value in d.items():
  388. ... print key, 'corresponds to', value
  389. ...
  390. y corresponds to 2
  391. x corresponds to 1
  392. z corresponds to 3
  393. >>>
  394.  
  395. #5.5.4 一些迭代工具
  396. #并行迭代
  397. >>> names = ['anne', 'beth', 'george', 'damon']
  398. >>> ages = [12, 45, 32, 102]
  399. >>> for in in range(len(names)):
  400.  
  401. SyntaxError: invalid syntax
  402. >>> for i in range(len(names)):
  403. print names[i], 'is', ages[i], 'year old'
  404.  
  405. anne is 12 year old
  406. beth is 45 year old
  407. george is 32 year old
  408. damon is 102 year old
  409. >>> for i in range(len(names)):
  410. print names[i], 'is', ages[i], 'years old'
  411.  
  412. anne is 12 years old
  413. beth is 45 years old
  414. george is 32 years old
  415. damon is 102 years old
  416. >>> zip(names, ages)
  417. [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
  418. >>> for name, age in zip(names, ages):
  419. print name, 'is', age, 'years old'
  420.  
  421. anne is 12 years old
  422. beth is 45 years old
  423. george is 32 years old
  424. damon is 102 years old
  425. >>> zip(range(5), xrange(100000000))
  426. [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
  427. #在索引上迭代
  428. >>> strings = ['I am xxx', 'I like losing my face', 'Say goodbye']
  429. >>> for string in strings:
  430. index = strings.index(string) # Search for the string in the list of strings
  431. strings[index]='[censored]'
  432.  
  433. >>> strings
  434. ['[censored]', '[censored]', '[censored]']
  435. >>> strings = ['I am xxx', 'I like losing my face', 'Say goodbye']
  436. >>> for string in strings:
  437. if 'xxx'in strings:
  438. index = strings.index(string) # Search for the string in the list of strings
  439. strings[index]='[censored]'
  440.  
  441. >>> strings
  442. ['I am xxx', 'I like losing my face', 'Say goodbye']
  443. >>> strings = ['I am xxx', 'I like losing my face', 'Say goodbye']
  444. >>> for string in strings:
  445. if 'xxx' in string:
  446. index = strings.index(string) # Search for the string in the list of strings
  447. strings[index]='[censored]'
  448.  
  449. >>>
  450. >>> string
  451. 'Say goodbye'
  452. >>> strings
  453. ['[censored]', 'I like losing my face', 'Say goodbye']
  454. >>> ['I am xxx', 'I like losing my face', 'Say goodbye']
  455. ['I am xxx', 'I like losing my face', 'Say goodbye']
  456. >>> index = 0
  457. >>> for string in strings:
  458. if 'xxx' in string:
  459. strings[index]='[censored]'
  460. index += 1
  461. SyntaxError: invalid syntax
  462. >>> index = 0
  463. >>> for string in strings:
  464. if 'xxx' in string: strings[index]='[censored]'
  465. index += 1
  466.  
  467. >>> strings
  468. ['[censored]', 'I like losing my face', 'Say goodbye']
  469. >>> ['I am xxx', 'I like losing my face', 'Say goodbye', 'xxx is a sensitive word']
  470. ['I am xxx', 'I like losing my face', 'Say goodbye', 'xxx is a sensitive word']
  471. >>> for index, string in enumerate(strings):
  472. if 'xxx' in string:
  473. strings[index]='[censored]'
  474.  
  475. >>> strings
  476. ['[censored]', 'I like losing my face', 'Say goodbye']
  477. >>> strings = ['I am xxx', 'I like losing my face', 'Say goodbye', 'xxx is a sensitive word']
  478. #enumerate函数能够在提供索引的地方迭代索引-值对.
  479. >>> for index, string in enumerate(strings):
  480. if 'xxx' in string:
  481. strings[index]='[censored]'
  482.  
  483. >>> strings
  484. ['[censored]', 'I like losing my face', 'Say goodbye', '[censored]']
  485.  
  486. #翻转和排序迭代
  487. >>> sorted([4,3,6,8,3])
  488. [3, 3, 4, 6, 8]
  489. >>> sorted('Hello, world!')
  490. [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
  491. >>> list(reversed('Hello, world'))
  492. ['d', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
  493. >>> ''.join(reversed('Hello, world!'))
  494. '!dlrow ,olleH'
  495.  
  496. #5.5.5 跳出循环
  497. #break
  498. >>> from math import sqrt
  499. >>> for n in range(99, 0, -1);
  500. SyntaxError: invalid syntax
  501. >>> for n in range(99, 0, -1):
  502. root = sqrt(n)
  503. if root == int(root):
  504. print n
  505. break
  506.  
  507. 81
  508. # continue
  509. # while True/break习惯使用方法
  510. >>> word = 'dummy'
  511. >>> while word:
  512. word = raw_input('Please enter a word: ')
  513. # 处理word:
  514. print 'The word was ' + word
  515.  
  516. Please enter a word: first
  517. The word was first
  518. Please enter a word: second
  519. The word was second
  520. Please enter a word:
  521. The word was
  522.  
  523. >>> word = raw_input('Please enter a word: ')
  524. Please enter a word: first
  525. >>> while word:
  526. print 'The word was ' + word
  527. word = raw_input('Please enter a word: ')
  528.  
  529. The word was first
  530. Please enter a word: second
  531. The word was second
  532. Please enter a word:
  533.  
  534. >>> while True:
  535. word = raw_input('Please enter a word: ')
  536. if not word: break
  537. print 'The word was ' + word
  538.  
  539. Please enter a word: first
  540. The word was first
  541. Please enter a word: second
  542. The word was second
  543. Please enter a word:
  544. #5.5.6 循环中else子句
  545. #原始方案
  546. from math import sqrt
  547. break_out = False
  548. for n in range(99, 81, -1):
  549. root = sqrt(n)
  550. if root == int(root):
  551. break_out = True
  552. print n
  553. break
  554.  
  555. if not break_out:
  556. print "Didn't find it!"
  557.  
  558. #结果Didn't find it!
  559.  
  560. #改进方案
  561. from math import sqrt
  562. for n in range(99, 81, -1):
  563. root = sqrt(n)
  564. if root == int(root):
  565. print n
  566. break
  567. else:
  568. print "Didn't find it!"
  569. #结果Didn't find it!
  570.  
  571. #列表推导式(list comprehension)--轻量级循环
  572.  
  573. >>> [x*x for x in range(10)]
  574. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  575. #能够和if子句联合使用
  576. >>> [x*x for x in range(10) if x % 3 == 0]
  577. [0, 9, 36, 81]
  578. >>> [(x,y) for x in range(3) for y in range(3)]
  579. [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
  580. >>>
  581. >>> result=[]
  582. >>> for x in range(3):
  583. for y in range(3):
  584. result.append((x,y))
  585.  
  586. >>> result
  587. [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
  588.  
  589. >>> girls=['alice', 'bernice', 'clarice']
  590. >>> boys=['chris', 'arnold', 'bob']
  591. >>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
  592. ['chris+clarice', 'arnold+alice', 'bob+bernice']
  593.  
  594. #更优方案
  595. >>> girls = ['alice', 'bernice', 'clarice']
  596. >>> boys = ['chris', 'arnold', 'bob']
  597. >>> letterGirls={}
  598. >>> for girl in girls:
  599. letterGirls.setdefault(girl[0], []).append(girl)
  600.  
  601. >>> print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
  602. ['chris+clarice', 'arnold+alice', 'bob+bernice']
  603. >>> letterGirls
  604. {'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
  605.  
  606. #5.7 三人行 pass, del 和 exec
  607.  
  608. #5.7.1 什么都没发生
  609.  
  610. >>> name = 'Bill Gates'
  611. >>> if name == 'Ralph Auldus Melish':
  612. ... print 'Welcome!'
  613. ... elif name == 'Enid':
  614. ... pass
  615. ... elif name == 'Bill Gates':
  616. ... print 'Access Denied'
  617. ...
  618. Access Denied
  619.  
  620. #5.7.2 使用del删除
  621. >>> scoundrel = {'age':42, 'first name':'Robin', 'last name':'of Locksley'
  622. >>> robin = scoundrel
  623. >>> scoundrel
  624. {'last name': 'of Locksley', 'first name': 'Robin', 'age': 42}
  625. >>> robin
  626. {'last name': 'of Locksley', 'first name': 'Robin', 'age': 42}
  627. >>> scoundrel = None
  628. >>> scoundrel
  629. >>> print scoundrel
  630. None
  631. >>> robin
  632. {'last name': 'of Locksley', 'first name': 'Robin', 'age': 42}
  633. >>> x = 1
  634. >>> y = x
  635. >>> x=1
  636. >>> del x
  637. >>> x
  638. Traceback (most recent call last):
  639. File "<stdin>", line 1, in <module>
  640. NameError: name 'x' is not defined
  641. >>> x = ['Hello', 'world']
  642. >>> y = x
  643. >>> y[1]='Python'
  644. >>> x
  645. ['Hello', 'Python']
  646. >>> del x
  647. >>> y
  648. ['Hello', 'Python']
  649.  
  650. #5.7.3 使用exec和eval运行和求值字符串
  651. # exec 在 Python 3.0 中是一个函数而不是语句
  652. >>> exec "print 'Hello, world!'"
  653. Hello, world!
  654. >>> from math import sqrt
  655. >>> exec "sqrt=1"
  656. >>> sqrt(4)
  657. Traceback (most recent call last):
  658. File "<stdin>", line 1, in <module>
  659. TypeError: 'int' object is not callable
  660.  
  661. #命名空间,或称为作用域(scope)
  662. #能够通过in <scope> 来实现, 当中的<scope>就是起到放置代码字符串命名空间作用的字典
  663. >>> from math import sqrt
  664. >>> scope={}
  665. >>> exec 'sqrt = 1' in scope
  666. >>> sqrt(4)
  667. 2.0
  668. >>> scope ['sqrt']
  669. 1
  670. >>> len(scope)
  671. 2
  672. >>> scope.keys()
  673. ['__builtins__', 'sqrt']
  674. # eval--求值字符串
  675. >>> eval(raw_input("Enter an arithmetic express: "))
  676. Enter an arithmetic express: 6 + 18 * 2
  677. 42
  678. >>> scope={}
  679. >>> scope['x']=2
  680. >>> scope['y']=3
  681. >>> eval('x * y', scope)
  682. 6
  683. >>> scope = {}
  684. >>> exec 'x=2' in scope
  685. >>> eval('x*x', scope)
  686. 4
  687. >>>
  688.  
  689. #5.8 小结
  690. #打印--print语句能够用来打印由逗号隔开的多个值. 假设语句以逗号结尾,随后的print语句会在同一行内接续打印
  691. #导入--能够用as对模块或函数提供别名
  692. #赋值--通过 序列解包 和 链式赋值 功能, 多个变量能够一次性赋值, 通过 增量赋值 能够原地改变变量
  693. #块--块是通过缩排使语句成组的一种方法. 块能够在条件以及循环语句中使用,也能够在函数和类中使用
  694. #条件--几个条件能够串联使用if/elif/else. 另一个变体叫做条件表达式,形如a if b else c.
  695. #断言--断言简单来说就是肯定某事(布尔表达式)为真, 也可在它后面跟上这么觉得的原因.
  696. #循环--能够使用continue语句跳过块中的其它语句然后继续下一次迭代, 或使用break语句跳出循环
  697. # 还能够选择在循环结尾加上else子句, 当没有运行循环内部的break语句时便会运行else子句中的内容.
  698. #列表推导式--是看起来像循环的表达式.通过它, 能够从旧列表中产生新的列表, 对元素应用函数, 过滤掉不须要的元素,等等.
  699. #pass, del, exec 和 eval 语句. pass语句什么都不做, 能够作为占位符使用. del语句用来删除变量(名称),或数据结构的一部分, 可是不能用来删除值.
  700. # exec语句用与运行Python程序同样的方式来运行字符串. 内建的eval函数对字符串中的表达式进行求值并返回结果.
  701.  
  702. #5.8.1 本章的新函数
  703. #chr(n) 返回序数n所代表的字符的字符串(0<=n<=256)
  704. #eval(source[, globals[, locals]]) 将字符串作为表达式计算,而且返回值
  705. #enumerate 产生用于迭代的(索引,值)对
  706. #ord(c) 返回单字符字符串的int值
  707. #range([start,] stop[, step]) 创建整数的列表
  708. #reversed(seq) 产生seq中值的反向副本, 用于迭代
  709. #sorted(seq[, cmp][, key][, reverse]) 返回seq中值排序后的列表副本
  710. #xrange([start,] stop[, step]) 创建xrange对象用于迭代
  711. #zip(seq1, seq2,...) 创建用于并行迭代的新序列

Python基础教程之第5章 条件, 循环和其它语句的更多相关文章

  1. Python基础教程之第2章 列表和元组

    D:\>python Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Typ ...

  2. Python基础教程之第3章 使用字符串

    Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyri ...

  3. Python基础教程之第1章 基础知识

    #1.1 安装Python #1.1.1 Windows #1.1.2 Linux和UNIX #1.1.3 Macintosh #1.1.4 其它公布版 #1.1.5 时常关注.保持更新 #1.2 交 ...

  4. Python基础教程之List对象 转

    Python基础教程之List对象 时间:2014-01-19    来源:服务器之家    投稿:root   1.PyListObject对象typedef struct {    PyObjec ...

  5. Python基础教程之udp和tcp协议介绍

    Python基础教程之udp和tcp协议介绍 UDP介绍 UDP --- 用户数据报协议,是一个无连接的简单的面向数据报的运输层协议.UDP不提供可靠性,它只是把应用程序传给IP层的数据报发送出去,但 ...

  6. python基础教程第5章——条件循环和其他语句

    1.语句块是在条件为真(条件语句)时执行或者执行多次(循环语句)的一组语句.在代码前放置空格来缩进语句即可穿件语句块.块中的每行都应该缩进同样的量.在Phyton中冒号(:)用来标识语句块的开始,块中 ...

  7. python基础教程之pymongo库

    1. 引入 在这里我们来看一下Python3下MongoDB的存储操作,在本节开始之前请确保你已经安装好了MongoDB并启动了其服务,另外安装好了Python的PyMongo库. 1.  安装 pi ...

  8. Python基础教程之dict和set

    1. dict Python中的dict等于js中的 map ,使用键-值(key-value)存储,具有极快的查找速度. 如果 我们要根据同学的姓名去查找他的成绩在不用dict的情况下.就需要两个l ...

  9. OpenVAS漏洞扫描基础教程之OpenVAS概述及安装及配置OpenVAS服务

    OpenVAS漏洞扫描基础教程之OpenVAS概述及安装及配置OpenVAS服务   1.  OpenVAS基础知识 OpenVAS(Open Vulnerability Assessment Sys ...

随机推荐

  1. Learning Face Age Progression: A Pyramid Architecture of GANs

    前言 作为IP模式识别的CNN初始模型是作为单纯判别式-模式识别存在的,并以此为基本模型扩展到各个方向.基本功能为图像判别模型,此后基于Loc+CNN的检测模型-分离式.end2end.以及MaskC ...

  2. webstom2017最新破解 ------------ http://blog.csdn.net/voke_/article/details/76418116

    webstorm 作为最近最火的前端开发工具,也确实对得起那个价格,但是秉着勤俭节约的传统美德,我们肯定是能省则省啊. 方法一:(更新时间:2018/1/23)v3.3 注册时,在打开的License ...

  3. Java实现打包文件

    把文件打包到压缩包里 public void zip (String... files) throws IOException { //创建文件打包流对象 ZipOutputStream zos = ...

  4. vue组件---动态组件之多标签页面

    首先看下效果图 代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> & ...

  5. 网络编程 - socket实现多个连接处理

    #服务端import socket,osso_server=socket.socket()so_server.bind(("localhost",6969))so_server.l ...

  6. java基础学习日志--异常案例

    package test7; public class InvalidScroreException extends Exception { public InvalidScroreException ...

  7. 洛谷——P3946 ことりのおやつ(小鸟的点心)

    P3946 ことりのおやつ(小鸟的点心) 题目太长,请去链接里看吧 注意细节:特判终点(即使困住又能怎样,到达就好了),特判高度 #include<bits/stdc++.h> #defi ...

  8. msdn的原版windows下载地址链接

    http://msdn.itellyou.cn/ 所有版本的下载地址 进去点左边操作系统

  9. BZOJ 1468 Tree 【模板】树上点分治

    #include<cstdio> #include<algorithm> #define N 50010 #define M 500010 #define rg registe ...

  10. POJ 3468 线段树区间修改查询(Java,c++实现)

    POJ 3468 (Java,c++实现) Java import java.io.*; import java.util.*; public class Main { static int n, m ...