here2share

# Demos-In-General.txt

Apr 9th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 63.21 KB | None | 0 0
  1. # Demos-In-General.txt --
  2. # Python 2.7.13
  3.  
  4. '''
  5. CONTENT:
  6.    The Zen of Python
  7.    First program
  8.    Comments
  9.    Data types
  10.    Data type conversions
  11.    Variables
  12.    Arithmetic operators
  13.    Comparison operators
  14.    Logical operators
  15.    Bitwise operators
  16.    Import
  17.    Functions
  18.    Math functions
  19.    if
  20.    if-else
  21.    if-elif
  22.    if-elif-else
  23.    for
  24.    for-else
  25.    while
  26.    Recursion
  27.    Strings
  28.    String format
  29.    String items
  30.    String operations
  31.    String methods
  32.    String constants
  33.    Tuples
  34.    Tuple items
  35.    Lists
  36.    List items
  37.    List operations
  38.    List methods
  39.    List conversion
  40.    List comprehensions
  41.    Stacks
  42.    Queues
  43.    Deque
  44.    Dictionaries
  45.    Dictionary items
  46.    Dictionary operations
  47.    Dictionary iteration
  48.    Slices
  49.    Classes
  50.    Properties
  51.    Inheritance
  52.    Polymorphism
  53.    Truth value testing
  54.    Escape sequences
  55.    Named arguments
  56.    Lambda functions
  57.    Random numbers
  58.    Exceptions
  59.    Raise
  60.    Keyboard input
  61.    Get documentation
  62.    Own documentation
  63.    Unit testing
  64.    CSV files
  65.    JSON string reader
  66.    JSON file reader
  67.    JSON file writer
  68.    JSON file helper
  69.    Hash functions
  70.    Argument parser
  71.    Version
  72.    Keywords
  73.    continue
  74.    break
  75.    return
  76.    Built-in functions
  77.    type()
  78.    sorted()
  79.    reversed()
  80.    map()
  81.    enumerate()
  82.    filter()
  83.    reduce()
  84.    zip()
  85.    izip()
  86.    Built-in list
  87.    Run script
  88.    Run script and check output
  89.    Save output
  90.  
  91. Variables, data types, functions, operators and comments in Python
  92. The Zen of Python
  93.  
  94. Import the this module to read The Zen of Python by Tim Peters.
  95. Description:
  96.  
  97. The Zen of Python is a list of good practices for writing code in Python.
  98. Source code:
  99.  
  100. zen.py
  101. '''
  102.  
  103. # shows The Zen of Python by Tim Peters
  104. import this
  105.  
  106. '''
  107. on console
  108.  
  109. The Zen of Python, by Tim Peters
  110.  
  111. Beautiful is better than ugly.
  112. Explicit is better than implicit.
  113. Simple is better than complex.
  114. Complex is better than complicated.
  115. Flat is better than nested.
  116. Sparse is better than dense.
  117. Readability counts.
  118. Special cases aren't special enough to break the rules.
  119. Although practicality beats purity.
  120. Errors should never pass silently.
  121. Unless explicitly silenced.
  122. In the face of ambiguity, refuse the temptation to guess.
  123. There should be one-- and preferably only one --obvious way to do it.
  124. Although that way may not be obvious at first unless you're Dutch.
  125. Now is better than never.
  126. Although never is often better than *right* now.
  127. If the implementation is hard to explain, it's a bad idea.
  128. If the implementation is easy to explain, it may be a good idea.
  129. Namespaces are one honking great idea -- let's do more of those!
  130.  
  131.  
  132. First program:
  133.  
  134. This example shows how to print a string on the console using the print statement.
  135. print is often used when debugging a program, because it allows us to print on the console the values of the variables that may be causing that the program does not work correctly.
  136. Source code:
  137.  
  138. first_program.py
  139. '''
  140.  
  141. print u'Hello World!'
  142.  
  143. '''
  144. on console
  145.  
  146. Hello World!
  147.  
  148. ### prints the string u'Hello World! on the console. u means that it is a unicode string.
  149.  
  150.  
  151. Comments
  152.  
  153. This example shows how to write comments in a Python script.
  154.  
  155. comments.py
  156. '''
  157.  
  158. # This is a single-line comment
  159.  
  160. # This is a
  161. # multi-line comment
  162.  
  163. '''
  164. It is recommended to document the source code, especially sections that it is not possible to understand at a glance. However, it is not recommended to document the source code that is clearly understood at a glance.
  165.  
  166.  
  167. Data types
  168.  
  169. This example shows some data types available in Python.
  170.  
  171. data_types.py
  172. '''
  173.  
  174. # strings
  175. print 'This is a string'
  176. print "This is a string"
  177. print '''This is a string'''
  178. print """This is a string"""
  179.  
  180. # unicode strings
  181. print u'This is a unicode string'
  182. print u"This is a unicode string"
  183. print u'''This is a unicode string'''
  184. print u"""This is a unicode string"""
  185.  
  186. # integer
  187. print 0
  188.  
  189. # long
  190. print 9999999999L
  191.  
  192. # float
  193. print 1.2
  194.  
  195. # complex
  196. print 1.2J
  197.  
  198. # booleans
  199. print True
  200. print False
  201.  
  202. # none
  203. print None
  204.  
  205. # list (mutable list)
  206. print [1, 2]
  207.  
  208. # tuple (immutable list)
  209. print (1, 2)
  210.  
  211. # set (mutable set)
  212. print {1, 2}
  213.  
  214. # frozenset (inmutable set)
  215. print frozenset([1, 2])
  216.  
  217. # dictionary
  218. print {1: 'one', 2: 'two'}
  219.  
  220. '''
  221. on console
  222.  
  223. This is a string
  224. This is a string
  225. This is a string
  226. This is a string
  227. This is a unicode string
  228. This is a unicode string
  229. This is a unicode string
  230. This is a unicode string
  231. 0
  232. 9999999999
  233. 1.2
  234. 1.2j
  235. True
  236. False
  237. None
  238. [1, 2]
  239. (1, 2)
  240. set([1, 2])
  241. frozenset([1, 2])
  242. {1: 'one', 2: 'two'}
  243.  
  244. Data type           Description                 Example
  245. str                 string                      'string'
  246. unicode             unicode string              u'unicode string'
  247. int                 integer number              1
  248. long                long integer number         9999999999L
  249. float               floating-point number       1.0
  250. complex             complex number              1.1J
  251. bool                boolean value               True
  252. None                none                        None
  253. list                mutable list                [0, 1]
  254. tuple               immutable list              (0, 1)
  255. set mutable         list without duplicates     {0, 1} or set([0, 1])
  256. frozenset           immutable list              frozenset([0, 1])
  257.                     without duplicates
  258. dict                dictionary                  {0: 'cero', 1: 'uno'}
  259.  
  260.  
  261. Data type conversions
  262.  
  263. data_type_conversions.py
  264. '''
  265.  
  266. # int()
  267. print 'int() examples'
  268. print int(2.1)
  269. print int(2.6)
  270. print int('2')
  271.  
  272. # long()
  273. print '\nlong() examples'
  274. print long(2)
  275. print long('2')
  276.  
  277. # float()
  278. print '\nfloat() examples'
  279. print float(2)
  280. print float('2')
  281. print float('2.1')
  282.  
  283. # complex()
  284. print '\ncomplex() examples'
  285. print complex(2)
  286. print complex(2.1)
  287. print complex('2.1')
  288.  
  289. # str()
  290. print '\nstr() examples'
  291. print str(2)
  292. print str(2L)
  293. print str(2.1)
  294. print str(2.1J)
  295. print str(True)
  296.  
  297. # bool()
  298. print '\nbool() examples'
  299. print bool(0)
  300. print bool(1)
  301. print bool(-1)
  302. print bool('True')
  303. print bool('False')
  304. print bool('')
  305.  
  306. '''
  307. on console
  308.  
  309. int() examples
  310. 2
  311. 2
  312. 2
  313.  
  314. long() examples
  315. 2
  316. 2
  317.  
  318. float() examples
  319. 2.0
  320. 2.0
  321. 2.1
  322.  
  323. complex() examples
  324. (2+0j)
  325. (2.1+0j)
  326. (2.1+0j)
  327.  
  328. str() examples
  329. 2
  330. 2
  331. 2.1
  332. 2.1j
  333. True
  334.  
  335. bool() examples
  336. False
  337. True
  338. True
  339. True
  340. True
  341. False
  342.  
  343.  
  344. Variables
  345.  
  346. variables.py
  347. '''
  348.  
  349. string = 'This is a string'
  350. integer_number = 0
  351. long_number = 1L
  352. float_number = 1.2
  353. complex_number = 1.2J
  354. boolean_value = True
  355. my_tuple = (1, 2)
  356. my_list = [1, 2]
  357. my_set = {1, 2}
  358. my_frozen_set = frozenset([1, 2])
  359. my_dictionary = {1: 'one', 2: 'two'}
  360.  
  361. print string
  362. print integer_number
  363. print long_number
  364. print float_number
  365. print complex_number
  366. print boolean_value
  367. print my_tuple
  368. print my_list
  369. print my_set
  370. print my_frozen_set
  371. print my_dictionary
  372.  
  373. '''
  374. on console
  375.  
  376. This is a string
  377. 0
  378. 1
  379. 1.2
  380. 1.2j
  381. True
  382. (1, 2)
  383. [1, 2]
  384. set([1, 2])
  385. frozenset([1, 2])
  386. {1: 'one', 2: 'two'}
  387.  
  388.  
  389. Arithmetic operators
  390.  
  391. arithmetic_operators.py
  392. '''
  393.  
  394. # addition
  395. print 2 + 3
  396.  
  397. # subtraction
  398. print 3 - 2
  399.  
  400. # multiplication
  401. print 2 * 3
  402.  
  403. # integer division
  404. print 3 / 2
  405.  
  406. # float division
  407. print 3 / 2.0
  408.  
  409. # exponentiation
  410. print 2 ** 3
  411.  
  412. # modulus operator (returns the remainder of a division)
  413. print 3 % 2
  414.  
  415. # use parentheses for grouping
  416. print 1 + 2 * 3 + 4
  417. print (1 + 2) * (3 + 4)
  418.  
  419. '''
  420. on console
  421.  
  422. 5
  423. 1
  424. 6
  425. 1
  426. 1.5
  427. 8
  428. 1
  429. 11
  430. 21
  431.  
  432.  
  433. Comparison operators
  434.  
  435. comparison_operators.py
  436. '''
  437.  
  438. # is equal to
  439. print 1 == 1
  440.  
  441. # is not equal to
  442. print 1 != 1
  443.  
  444. # is greater than
  445. print 2 > 1
  446.  
  447. # is less than
  448. print 2 < 1
  449.  
  450. # is greater than or equal to
  451. print 2 >= 1
  452.  
  453. # is less than or equal to
  454. print 2 <= 1
  455.  
  456. # object identity
  457. print 2 is int(2)
  458.  
  459. # negated object identity
  460. print 2.0 is not int(2)
  461.  
  462. '''
  463. on console
  464.  
  465. True
  466. False
  467. True
  468. False
  469. True
  470. False
  471. True
  472. True
  473.  
  474. operator    description
  475. <           strictly less than
  476. <=          less than or equal
  477. >           strictly greater than
  478. >=          greater than or equal
  479. ==          equal
  480. !=          not equal
  481. is          object identity
  482. is not      negated object identity
  483.  
  484.  
  485. Logical operators
  486.  
  487. logical_operators.py
  488. '''
  489.  
  490. # AND
  491. print 'AND operator'
  492. print True and True
  493. print True and False
  494. print False and True
  495. print False and False
  496.  
  497. # OR
  498. print '\nOR operator'
  499. print True or True
  500. print True or False
  501. print False or True
  502. print False or False
  503.  
  504. # NOT
  505. print '\nNOT operator'
  506. print not True
  507. print not False
  508.  
  509. '''
  510. on console
  511.  
  512. AND operator
  513. True
  514. False
  515. False
  516. False
  517.  
  518. OR operator
  519. True
  520. True
  521. True
  522. False
  523.  
  524. NOT operator
  525. False
  526. True
  527.  
  528.  
  529. Bitwise operators
  530.  
  531. bitwise_operators.py
  532. '''
  533.  
  534. # 15 == 0000 1111
  535. #  3 == 0000 0011
  536.  
  537. # binary AND
  538. print 15 & 3  # 0000 0011 == 3
  539.  
  540. # binary OR
  541. print 15 | 3  # 0000 1111 == 15
  542.  
  543. # binary XOR
  544. print 15 ^ 3  # 0000 1100 == 12
  545.  
  546. # binary NOT
  547. print ~3  # 1111 1100 == -4
  548.  
  549. # binary LEFT SHIFT
  550. print 3 << 1  # 0000 0110 == 6
  551.  
  552. # binary RIGHT SHIFT
  553. print 3 >> 1  # 0000 0001 == 1
  554.  
  555. '''
  556. on console
  557.  
  558. 3
  559. 15
  560. 12
  561. -4
  562. 6
  563. 1
  564.  
  565.  
  566. Import
  567.  
  568. import.py
  569. '''
  570.  
  571. # imports the 'math' module
  572. import math
  573.  
  574. # imports the 'sqrt' function from the 'math' module
  575. from math import sqrt
  576.  
  577. # PI constant
  578. print math.pi
  579.  
  580. # returns the square root of a number
  581. print sqrt(9)
  582.  
  583. '''
  584. on console
  585.  
  586. 3.14159265359
  587. 3.0
  588.  
  589.  
  590. Functions
  591.  
  592. functions.py
  593. '''
  594.  
  595. # function
  596. def addition(a, b):
  597.     return a + b
  598.  
  599.  
  600. print addition(2, 3)
  601.  
  602. '''
  603. on console
  604.  
  605. 5
  606.  
  607.  
  608. Math functions
  609.  
  610. math_functions.py
  611. '''
  612.  
  613. import math
  614.  
  615. # Euler's constant
  616. print 'math.e'
  617. print math.e
  618.  
  619. # PI constant
  620. print '\nmath.pi'
  621. print math.pi
  622.  
  623. # return the absolute value of a number
  624. print '\nmath.fabs(-5)'
  625. print math.fabs(-5)
  626.  
  627. # exponentiation
  628. print '\nmath.pow(2, 3)'
  629. print math.pow(2, 3)
  630.  
  631. # returns the square root of a number
  632. print '\nmath.sqrt(9)'
  633. print math.sqrt(9)
  634.  
  635. # converts radians to degrees
  636. print '\nmath.degrees(math.pi)'
  637. print math.degrees(math.pi)
  638.  
  639. # converts degrees to radians
  640. print '\nmath.radians(180)'
  641. print math.radians(180)
  642.  
  643. # returns the trigonometric sine of an angle
  644. print '\nmath.sin(math.radians(90))'
  645. print math.sin(math.radians(90))
  646.  
  647. # returns the trigonometric cosine of an angle
  648. print '\nmath.cos(math.radians(0))'
  649. print math.cos(math.radians(0))
  650.  
  651. # returns the trigonometric tangent of an angle
  652. print '\nmath.tan(math.radians(0))'
  653. print math.tan(math.radians(0))
  654.  
  655. # returns the factorial of a number
  656. print '\nmath.factorial(10)'
  657. print math.factorial(10)
  658.  
  659. # modulus operator (returns a remainder of a division)
  660. print '\nmath.fmod(3, 2)'
  661. print math.fmod(3, 2)
  662.  
  663. # returns the total sum of all values and avoids loss of precision
  664. print '\nmath.fsum([93, 86, 38, 23, 46, 32])'
  665. print math.fsum([93, 86, 38, 23, 46, 32])
  666.  
  667. '''
  668. on console
  669.  
  670. math.e
  671. 2.71828182846
  672.  
  673. math.pi
  674. 3.14159265359
  675.  
  676. math.fabs(-5)
  677. 5.0
  678.  
  679. math.pow(2, 3)
  680. 8.0
  681.  
  682. math.sqrt(9)
  683. 3.0
  684.  
  685. math.degrees(math.pi)
  686. 180.0
  687.  
  688. math.radians(180)
  689. 3.14159265359
  690.  
  691. math.sin(math.radians(90))
  692. 1.0
  693.  
  694. math.cos(math.radians(0))
  695. 1.0
  696.  
  697. math.tan(math.radians(0))
  698. 0.0
  699.  
  700. math.factorial(10)
  701. 3628800
  702.  
  703. math.fmod(3, 2)
  704. 1.0
  705.  
  706. math.fsum([93, 86, 38, 23, 46, 32])
  707. 318.0
  708.  
  709.  
  710. if
  711.  
  712. In an if statement, action is executed if condition is True.
  713. Flowchart:
  714. Flowchart if
  715. Source code:
  716.  
  717. if.py
  718. '''
  719.  
  720. # condition
  721. is_running = True
  722.  
  723. if is_running:
  724.     # if condition is True, executes action
  725.     print u'Running...'
  726.  
  727. '''
  728. on console
  729.  
  730. Running...
  731.  
  732.  
  733. if-else
  734.  
  735. In an if-else statement, action 1 is executed if condition is True, otherwise action 2 is executed.
  736. Flowchart:
  737. Flowchart if-else
  738. Source code:
  739.  
  740. if_else.py
  741. '''
  742.  
  743. # condition
  744. is_running = False
  745.  
  746. if is_running:
  747.     # if condition is True, executes action 1
  748.     print u'Running...'
  749. else:
  750.     # if condition is False, executes action 2
  751.     print u'Not running'
  752.  
  753. '''
  754. on console
  755.  
  756. Not running
  757.  
  758.  
  759. if-elif
  760.  
  761. In an if-elif statement, action n is executed if any condition n is True, where n is the number of nested conditions.
  762. Flowchart:
  763. Flowchart if-elif
  764. Source code:
  765.  
  766. if_elif.py
  767. '''
  768.  
  769. number = 2
  770.  
  771. # condition 1
  772. if number == 1:
  773.     # if condition 1 is True, executes action 1
  774.     print u'One'
  775.  
  776. # if condition 1 is False, condition 2 is checked
  777. elif number == 2:
  778.     # if condition 2 is True, executes action 2
  779.     print u'Two'
  780.  
  781. # if condition 2 is False, condition 3 is checked
  782. elif number == 3:
  783.     # if condition 3 is True, executes action 3
  784.     print u'Three'
  785.  
  786. '''
  787. on console
  788.  
  789. Two
  790.  
  791.  
  792. if-elif-else
  793.  
  794. In an if-elif-else statement, action n is executed if any condition n is True, otherwise action n+1 is executed, where n is the number of nested conditions.
  795. Flowchart:
  796. Flowchart if-elif-else
  797. Source code:
  798.  
  799. if_elif_else.py
  800. '''
  801.  
  802. number_1 = 2
  803. number_2 = 3
  804.  
  805. # condition 1
  806. if number_1 == number_2:
  807.     # if condition 1 is True, executes action 1
  808.     print unicode(number_1) + u' is equal to ' + unicode(number_2)
  809.  
  810. # if condition 1 is False, condition 2 is checked
  811. elif number_1 > number_2:
  812.     # if condition 2 is True, executes action 2
  813.     print unicode(number_1) + u' is greater than ' + unicode(number_2)
  814.  
  815. else:
  816.     # if no condition is True, executes action 3
  817.     print unicode(number_1) + u' is less than ' + unicode(number_2)
  818.  
  819. '''
  820. on console
  821.  
  822. 2 is less than 3
  823.  
  824.  
  825. for
  826.  
  827. for.py
  828. '''
  829.  
  830. print 'example #1'
  831. for i in xrange(5):
  832.     print i
  833.  
  834. print '\nexample #2'
  835. for i in xrange(1, 5):
  836.     print i
  837.  
  838. print '\nexample #3'
  839. for i in xrange(1, 5, 2):
  840.     print i
  841.  
  842. print '\nexample #4'
  843. for i in xrange(5, 0, -1):
  844.     print i
  845.  
  846. print '\nexample #5'
  847. for i in [1, 2, 3, 2, 1]:
  848.     print i
  849.  
  850. '''
  851. on console
  852.  
  853. example #1
  854. 0
  855. 1
  856. 2
  857. 3
  858. 4
  859.  
  860. example #2
  861. 1
  862. 2
  863. 3
  864. 4
  865.  
  866. example #3
  867. 1
  868. 3
  869.  
  870. example #4
  871. 5
  872. 4
  873. 3
  874. 2
  875. 1
  876.  
  877. example #5
  878. 1
  879. 2
  880. 3
  881. 2
  882. 1
  883.  
  884.  
  885. for-else
  886.  
  887. for_else.py
  888. '''
  889.  
  890. def find_character(ch, string):
  891.     """
  892.    prints the index within this string of the first occurrence of the specified character, else prints a message
  893.    that the specified character has not been found
  894.    """
  895.     for index, character in enumerate(string):
  896.         if character == ch:
  897.             print '"{}" (index: {})'.format(ch, index)
  898.             break
  899.     else:
  900.         print '"{}" has not been found'.format(ch)
  901.  
  902.  
  903. message = 'Hello World!'
  904. find_character('o', message)
  905. find_character('r', message)
  906. find_character('z', message)
  907.  
  908. '''
  909. on console
  910.  
  911. "o" (index: 4)
  912. "r" (index: 8)
  913. "z" has not been found
  914.  
  915.  
  916. while
  917.  
  918. while repeats the statements inside its block while its condition is True.
  919.  
  920. while.py
  921. '''
  922.  
  923. # initializes the variable 'i'
  924. i = 0
  925.  
  926. # the condition should be 'False' at some point, otherwise it will produce an infinite loop
  927. while i < 5:
  928.     # prints the variable 'i' on the console
  929.     print i
  930.  
  931.     # increases by 1 the value of the variable 'i'
  932.     i += 1
  933.  
  934. '''
  935. on console
  936.  
  937. 0
  938. 1
  939. 2
  940. 3
  941. 4
  942.  
  943.  
  944. Recursion
  945.  
  946. recursion.py
  947. '''
  948.  
  949. def factorial(n):  # without optimization
  950.     if n == 0:
  951.         return 1
  952.     return n * factorial(n - 1)  # recursion
  953.  
  954.  
  955. print factorial(10)
  956.  
  957. '''
  958. on console
  959.  
  960. 3628800
  961.  
  962.  
  963. Strings
  964.  
  965. strings.py
  966. '''
  967.  
  968. message = 'Hello World!'
  969. print message
  970.  
  971. message = "'Hello' World!"
  972. print message
  973.  
  974. message = '"Hello" World!'
  975. print message
  976.  
  977. message = """single quote (') and double quote (")"""
  978. print message
  979.  
  980. message = '''single quote (') and double quote (")'''
  981. print message
  982.  
  983. '''
  984. on console
  985.  
  986. Hello World!
  987. 'Hello' World!
  988. "Hello" World!
  989. single quote (') and double quote (")
  990. single quote (') and double quote (")
  991.  
  992.  
  993. String format
  994.  
  995. string_format.py
  996. '''
  997.  
  998. import datetime
  999.  
  1000. print '{} {}'.format('Hello', 'World!')
  1001.  
  1002. # arguments by position
  1003. print '{1} {0}'.format('Hello', 'World!')
  1004. print '{0} {1} {0} {1}'.format('Hello', 'World!')
  1005.  
  1006. # arguments by name
  1007. print '{x}, {y}'.format(x='2', y='4')
  1008.  
  1009. # decimal hexadecimal octal binary
  1010. print '{0:d} {0:x} {0:o} {0:b}'.format(10)
  1011. print '{0:d} {0:#x} {0:#o} {0:#b}'.format(10)
  1012.  
  1013. # leading zeros
  1014. print '{:04d}'.format(1)
  1015.  
  1016. # thousand separator
  1017. print '{:,}'.format(10000)
  1018.  
  1019. # percentage
  1020. print '{:.1%}'.format(.5)
  1021.  
  1022. # datetime
  1023. print '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime(2000, 1, 15, 13, 10, 20))
  1024.  
  1025. # sign
  1026. print '{:+d}, {:+d}'.format(1, -1)
  1027. print '{: d}, {: d}'.format(1, -1)
  1028. print '{:-d}, {:-d}'.format(1, -1)
  1029. print '{:d}, {:d}'.format(1, -1)
  1030.  
  1031. '''
  1032. on console
  1033.  
  1034. Hello World!
  1035. World! Hello
  1036. Hello World! Hello World!
  1037. 2, 4
  1038. 10 a 12 1010
  1039. 10 0xa 0o12 0b1010
  1040. 10,000
  1041. 50.0%
  1042. 2000-01-15 13:10:20
  1043. +1, -1
  1044. 1, -1
  1045. 1, -1
  1046. 1, -1
  1047.  
  1048.  
  1049. String items
  1050.  
  1051. string_items.py
  1052. '''
  1053.  
  1054. message = 'Hello World!'
  1055. print message
  1056.  
  1057. # first character
  1058. print message[0]
  1059.  
  1060. # second character
  1061. print message[1]
  1062.  
  1063. # last character
  1064. print message[-1]
  1065.  
  1066. # second to last character
  1067. print message[-2]
  1068.  
  1069. # a range of characters
  1070. print message[2:5]
  1071.  
  1072. '''
  1073. on console
  1074.  
  1075. Hello World!
  1076. H
  1077. e
  1078. !
  1079. d
  1080. llo
  1081.  
  1082.  
  1083. String operations
  1084.  
  1085. string_operations.py
  1086. '''
  1087.  
  1088. # string concatenation
  1089. print 'Hello' + ' World!'
  1090.  
  1091. # repeats the string five times
  1092. print 'Hello World! ' * 5
  1093.  
  1094. message = 'Hello World!'
  1095. print message
  1096.  
  1097. # string length
  1098. print len(message)
  1099.  
  1100. # string slices (returns a substring of the original string)
  1101. print message[1:8]
  1102. print message[:8]
  1103. print message[1:]
  1104.  
  1105. # string comparison
  1106. if message == 'Hello World!':
  1107.     print 'the message is: Hello World!'
  1108.  
  1109. # substring of a string
  1110. if 'Hello' in message:
  1111.     print "the message contains the word 'Hello'"
  1112.  
  1113. # prints all characters
  1114. for ch in message:
  1115.     print ch
  1116.  
  1117. '''
  1118. on console
  1119.  
  1120. Hello World!
  1121. Hello World! Hello World! Hello World! Hello World! Hello World!
  1122. Hello World!
  1123. 12
  1124. ello Wo
  1125. Hello Wo
  1126. ello World!
  1127. the message is: Hello World!
  1128. the message contains the word 'Hello'
  1129. H
  1130. e
  1131. l
  1132. l
  1133. o
  1134.  
  1135. W
  1136. o
  1137. r
  1138. l
  1139. d
  1140. !
  1141.  
  1142.  
  1143. String methods
  1144.  
  1145. string_methods.py
  1146. '''
  1147.  
  1148. message = 'Hello World!'
  1149. print message
  1150.  
  1151. # only the first character in uppercase
  1152. print message.capitalize()
  1153.  
  1154. # number of occurrences
  1155. print message.count('o')
  1156.  
  1157. # finds substring and returns the index of their first occurrence
  1158. print message.find('Hello')
  1159.  
  1160. # is this a digit?
  1161. print message.isdigit()
  1162.  
  1163. # is this in lowercase?
  1164. print message.islower()
  1165.  
  1166. # is this in uppercase?
  1167. print message.isupper()
  1168.  
  1169. # inserts ',' between characters
  1170. print ','.join(message)
  1171.  
  1172. # to lowercase
  1173. print message.lower()
  1174.  
  1175. # to uppercase
  1176. print message.upper()
  1177.  
  1178. # splits on the specified character
  1179. print message.split(' ')
  1180.  
  1181. message = '  Hello World!  '
  1182. print message
  1183.  
  1184. # removes whitespaces on the left
  1185. print message.lstrip()
  1186.  
  1187. # removes whitespaces on the right
  1188. print message.rstrip()
  1189.  
  1190. '''
  1191. on console
  1192.  
  1193. Hello World!
  1194. Hello world!
  1195. 2
  1196. 0
  1197. False
  1198. False
  1199. False
  1200. H,e,l,l,o, ,W,o,r,l,d,!
  1201. hello world!
  1202. HELLO WORLD!
  1203. ['Hello', 'World!']
  1204.  Hello World!  
  1205. Hello World!  
  1206.  Hello World!
  1207.  
  1208.  
  1209. String constants
  1210.  
  1211. string_constants.py
  1212. '''
  1213.  
  1214. import string
  1215.  
  1216. # locale-dependent
  1217. print string.lowercase
  1218. print string.uppercase
  1219. print string.letters
  1220.  
  1221. # not locale-dependent
  1222. print string.ascii_lowercase
  1223. print string.ascii_uppercase
  1224. print string.ascii_letters
  1225.  
  1226. print string.digits
  1227. print string.hexdigits
  1228. print string.octdigits
  1229.  
  1230. print string.punctuation
  1231.  
  1232. print repr(string.whitespace)  # \x0b == \v, \x0c == \f
  1233.  
  1234. print repr(string.printable)
  1235.  
  1236. '''
  1237. on console
  1238.  
  1239. abcdefghijklmnopqrstuvwxyz
  1240. ABCDEFGHIJKLMNOPQRSTUVWXYZ
  1241. abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  1242. abcdefghijklmnopqrstuvwxyz
  1243. ABCDEFGHIJKLMNOPQRSTUVWXYZ
  1244. abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  1245. 0123456789
  1246. 0123456789abcdefABCDEF
  1247. 01234567
  1248. !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
  1249. '\t\n\x0b\x0c\r '
  1250. '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
  1251.  
  1252.  
  1253. Tuples
  1254.  
  1255. tuples are an immutable sequence type, i.e., their items can not be modified, so a tuple can be used as a key in a dict.
  1256.  
  1257. tuples.py
  1258. '''
  1259.  
  1260. # creates a tuple of integers and prints it on the console
  1261. print (1, 2, 3, 4)
  1262.  
  1263. # creates a tuple of strings and prints it on the console
  1264. print ('hello', 'world')
  1265.  
  1266. # crea un tuple con diferentes tipos de datosy lo imprime en la consola
  1267. print (1, 'hello', 2, 3, 'world', 4)
  1268.  
  1269. # creates nested tuples and prints them on the console
  1270. print (('a', 'e', 'i', 'o', 'u'), (1, 2, 3, 4, 5))
  1271.  
  1272. # creates a tuple with a single element and prints it on the console
  1273. print (1,)
  1274.  
  1275. # creates an empty tuple and prints it on the console
  1276. print ()
  1277.  
  1278. '''
  1279. on console
  1280.  
  1281. (1, 2, 3, 4)
  1282. ('hello', 'world')
  1283. (1, 'hello', 2, 3, 'world', 4)
  1284. (('a', 'e', 'i', 'o', 'u'), (1, 2, 3, 4, 5))
  1285. (1,)
  1286. ()
  1287.  
  1288.  
  1289. Tuple items
  1290.  
  1291. To access the items of a tuple we use the bracket operator [], and inside the brackets, we specify the index of the item that we want to get. The indices start at 0. With negative indices, we access the items of the tuple in reverse order.
  1292.  
  1293. tuple_items.py
  1294. '''
  1295.  
  1296. # creates a tuple of integer
  1297. numbers = (0, 1, 2, 3, 4, 5, 6)
  1298.  
  1299. # prints the tuple on the console
  1300. print numbers
  1301.  
  1302. # prints the first item on the console
  1303. print numbers[0]
  1304.  
  1305. # prints the second item on the console
  1306. print numbers[1]
  1307.  
  1308. # prints the last item on the console
  1309. print numbers[-1]
  1310.  
  1311. # prints the second to last item on the console
  1312. print numbers[-2]
  1313.  
  1314. # prints the range of elements every two spaces on the console
  1315. print numbers[::2]
  1316.  
  1317. # prints the range of items [2, 5) on the console
  1318. print numbers[2:5]
  1319.  
  1320. # prints the range of elements (2, 5] in reverse order on the console
  1321. print numbers[5:2:-1]
  1322.  
  1323. '''
  1324. on console
  1325.  
  1326. (0, 1, 2, 3, 4, 5, 6)
  1327. 0
  1328. 1
  1329. 6
  1330. 5
  1331. (0, 2, 4, 6)
  1332. (2, 3, 4)
  1333. (5, 4, 3)
  1334.  
  1335. Tuple items Tuple items Tuple items
  1336.  
  1337.  
  1338. Lists
  1339.  
  1340. lists.py
  1341. '''
  1342.  
  1343. # list of integers
  1344. print [1, 2, 3, 4]
  1345.  
  1346. # list of strings
  1347. print ['hello', 'world']
  1348.  
  1349. # list with different types
  1350. print [1, 'hello', 2, 3, 'world', 4]
  1351.  
  1352. # nested lists
  1353. print [1, [2, 3, 4]]
  1354.  
  1355. # list without items
  1356. print []
  1357.  
  1358. '''
  1359. on console
  1360.  
  1361. [1, 2, 3, 4]
  1362. ['hello', 'world']
  1363. [1, 'hello', 2, 3, 'world', 4]
  1364. [1, [2, 3, 4]]
  1365. []
  1366.  
  1367.  
  1368. List items
  1369.  
  1370. list_items.py
  1371. '''
  1372.  
  1373. numbers = [1, 2, 3, 4, 5, 6]
  1374. print numbers
  1375.  
  1376. # first item
  1377. print numbers[0]
  1378.  
  1379. # second item
  1380. print numbers[1]
  1381.  
  1382. # last item
  1383. print numbers[-1]
  1384.  
  1385. # second to last item
  1386. print numbers[-2]
  1387.  
  1388. # a range of items
  1389. print numbers[2:5]
  1390.  
  1391. '''
  1392. on console
  1393.  
  1394. [1, 2, 3, 4, 5, 6]
  1395. 1
  1396. 2
  1397. 6
  1398. 5
  1399. [3, 4, 5]
  1400.  
  1401.  
  1402. List operations
  1403.  
  1404. list_operations.py
  1405. '''
  1406.  
  1407. numbers = [-1, 0, 1, 2, 3]
  1408. print numbers
  1409.  
  1410. # list length
  1411. print len(numbers)
  1412.  
  1413. # concatenation
  1414. numbers += [4, 5, 6, 7]
  1415. print numbers
  1416.  
  1417. # cloning lists (makes a copy of the original list)
  1418. clone = numbers[:]
  1419. print clone
  1420.  
  1421. # removes the first item
  1422. del numbers[0]
  1423. print numbers
  1424.  
  1425. # removes the last item
  1426. del numbers[-1]
  1427. print numbers
  1428.  
  1429. # removes items every two steps
  1430. del numbers[1:len(numbers):2]
  1431. print numbers
  1432.  
  1433. # removes all items
  1434. numbers[:] = []
  1435. print numbers
  1436.  
  1437. '''
  1438. on console
  1439.  
  1440. [-1, 0, 1, 2, 3]
  1441. 5
  1442. [-1, 0, 1, 2, 3, 4, 5, 6, 7]
  1443. [-1, 0, 1, 2, 3, 4, 5, 6, 7]
  1444. [0, 1, 2, 3, 4, 5, 6, 7]
  1445. [0, 1, 2, 3, 4, 5, 6]
  1446. [0, 2, 4, 6]
  1447. []
  1448.  
  1449.  
  1450. List methods
  1451.  
  1452. list_methods.py
  1453. '''
  1454.  
  1455. numbers = [0, 1, 2, 3, 4]
  1456. print numbers
  1457.  
  1458. # appends an item to the end
  1459. numbers.append(4)
  1460. print numbers
  1461.  
  1462. # returns the total of occurrences of the specified item
  1463. print numbers.count(4)
  1464.  
  1465. # returns the index of the first occurrence of the specified item
  1466. print numbers.index(4)
  1467.  
  1468. # removes the first item and returns their value
  1469. print numbers.pop(0)
  1470.  
  1471. # removes the last item and returns their value
  1472. print numbers.pop(-1)
  1473.  
  1474. # removes the first occurrence of the specified item
  1475. numbers.remove(3)
  1476. print numbers
  1477.  
  1478. # inserts an item 'insert(position, item)'
  1479. numbers.insert(2, 3)
  1480. print numbers
  1481.  
  1482. # extends the list
  1483. numbers.extend([5, 6, 7])
  1484. print numbers
  1485.  
  1486. # reverses the list
  1487. numbers.reverse()
  1488. print numbers
  1489.  
  1490. # sorts the list
  1491. numbers.sort()
  1492. print numbers
  1493.  
  1494. # sorts the list in reverse order
  1495. numbers.sort(reverse=True)
  1496. print numbers
  1497.  
  1498. '''
  1499. on console
  1500.  
  1501. [0, 1, 2, 3, 4]
  1502. [0, 1, 2, 3, 4, 4]
  1503. 2
  1504. 4
  1505. 0
  1506. 4
  1507. [1, 2, 4]
  1508. [1, 2, 3, 4]
  1509. [1, 2, 3, 4, 5, 6, 7]
  1510. [7, 6, 5, 4, 3, 2, 1]
  1511. [1, 2, 3, 4, 5, 6, 7]
  1512. [7, 6, 5, 4, 3, 2, 1]
  1513.  
  1514.  
  1515. List conversion
  1516.  
  1517. list_conversion.py
  1518. '''
  1519.  
  1520. # string conversion
  1521. print list('Hello World!')
  1522.  
  1523. # dictionary conversion
  1524. print list({1: 'one', 2: 'two'})
  1525.  
  1526. # tuple conversion
  1527. print list((1, 2))
  1528.  
  1529. # set conversion
  1530. print list({1, 2})
  1531.  
  1532. # frozenset conversion
  1533. print list(frozenset([1, 2]))
  1534.  
  1535. '''
  1536. on console
  1537.  
  1538. ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
  1539. [1, 2]
  1540. [1, 2]
  1541. [1, 2]
  1542. [1, 2]
  1543.  
  1544.  
  1545. List comprehensions
  1546.  
  1547. List comprehensions are compact expressions used to create a new list (or nested lists), or to perform operations on items in a previously created list, such as selecting items that meet a condition.
  1548.  
  1549. list_comprehensions.py
  1550. '''
  1551.  
  1552. # list comprehensions
  1553.  
  1554. # creates a list
  1555. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1556.  
  1557. # prints the created list
  1558. print numbers
  1559.  
  1560. # -- performs operations on each element of the list created before --
  1561. # squares the number of each number in the list, returns them in a new list and prints the new list
  1562. print [x ** 2 for x in numbers]
  1563.  
  1564. # -- performs operations on each number in the list created before that satisfies a certain condition --
  1565. # squares only the even numbers in the list, returns them in a new list and print the new list
  1566. print [x ** 2 for x in numbers if x % 2 == 0]
  1567.  
  1568. # -- creates a new list --
  1569. # prints the squares of the numbers in the range [1, 11)
  1570. print [x ** 2 for x in xrange(1, 11)]
  1571.  
  1572. # -- creates a new nested list of 4x2 (row x column) --
  1573. # Note: expressions are execute from left to right
  1574. rows = 4  # rows
  1575. cols = 2  # columns
  1576. print [[x + y * cols for x in xrange(cols)] for y in xrange(rows)]
  1577.  
  1578. '''
  1579. on console
  1580.  
  1581. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1582. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  1583. [4, 16, 36, 64, 100]
  1584. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  1585. [[0, 1], [2, 3], [4, 5], [6, 7]]
  1586.  
  1587.  
  1588. Stacks
  1589.  
  1590. stacks.py
  1591. '''
  1592.  
  1593. # stacks: last-in, first-out
  1594.  
  1595. stack = [0, 1, 2, 3, 4]
  1596. print stack
  1597.  
  1598. stack.append(5)
  1599. print stack
  1600.  
  1601. print stack.pop()
  1602. print stack.pop()
  1603.  
  1604. print stack
  1605.  
  1606. '''
  1607. on console
  1608.  
  1609. [0, 1, 2, 3, 4]
  1610. [0, 1, 2, 3, 4, 5]
  1611. 5
  1612. 4
  1613. [0, 1, 2, 3]
  1614.  
  1615.  
  1616. Queues
  1617.  
  1618. queues.py
  1619. '''
  1620.  
  1621. from Queue import Queue, LifoQueue, PriorityQueue
  1622.  
  1623. # FIFO queue example (FIFO: first-in, first-out)
  1624. print 'FIFO queue example'
  1625. fifo_queue = Queue()
  1626.  
  1627. fifo_queue.put(1)
  1628. fifo_queue.put(5)
  1629. fifo_queue.put(3)
  1630.  
  1631. while not fifo_queue.empty():
  1632.     number = fifo_queue.get()
  1633.     print number
  1634.     fifo_queue.task_done()
  1635.  
  1636. fifo_queue.join()
  1637.  
  1638.  
  1639. # LIFO queue example (LIFO: last-in, first-out)
  1640. print '\nLIFO queue example'
  1641. lifo_queue = LifoQueue()
  1642.  
  1643. lifo_queue.put(1)
  1644. lifo_queue.put(5)
  1645. lifo_queue.put(3)
  1646.  
  1647. while not lifo_queue.empty():
  1648.     number = lifo_queue.get()
  1649.     print number
  1650.     lifo_queue.task_done()
  1651.  
  1652. lifo_queue.join()
  1653.  
  1654. # Priority queue example (the lowest valued entries are retrieved first)
  1655. print '\nPriority queue example'
  1656. priority_queue = PriorityQueue()
  1657.  
  1658. priority_queue.put(1)
  1659. priority_queue.put(5)
  1660. priority_queue.put(3)
  1661.  
  1662. while not priority_queue.empty():
  1663.     number = priority_queue.get()
  1664.     print number
  1665.     priority_queue.task_done()
  1666.  
  1667. priority_queue.join()
  1668.  
  1669. '''
  1670. on console
  1671.  
  1672. FIFO queue example
  1673. 1
  1674. 5
  1675. 3
  1676.  
  1677. LIFO queue example
  1678. 3
  1679. 5
  1680. 1
  1681.  
  1682. Priority queue example
  1683. 1
  1684. 3
  1685. 5
  1686.  
  1687.  
  1688. Deque
  1689.  
  1690. deque.py
  1691. '''
  1692.  
  1693. from collections import deque
  1694.  
  1695. # deque: a double-ended queue
  1696.  
  1697. d = deque([3, 4])
  1698. print d
  1699.  
  1700. # appends an item to the right side
  1701. d.append(5)
  1702. print d
  1703.  
  1704. # appends an item to the left side
  1705. d.appendleft(2)
  1706. print d
  1707.  
  1708. # removes and returns one item from the right
  1709. print d.pop()
  1710.  
  1711. # removes and returns one item from the left
  1712. print d.popleft()
  1713.  
  1714. print d
  1715.  
  1716. # returns the total of occurrences of the specified item
  1717. print d.count(3)
  1718.  
  1719. # extends the right side
  1720. d.extend([5, 6, 7])
  1721. print d
  1722.  
  1723. # extends the left side
  1724. d.extendleft([2, 1, 0])
  1725. print d
  1726.  
  1727. # reversed the elements in-place
  1728. d.reverse()
  1729. print d
  1730.  
  1731. # removes all element
  1732. d.clear()
  1733. print d
  1734.  
  1735. # returns the maximum size, None if unbounded
  1736. print d.maxlen
  1737.  
  1738. '''
  1739. on console
  1740.  
  1741. deque([3, 4])
  1742. deque([3, 4, 5])
  1743. deque([2, 3, 4, 5])
  1744. 5
  1745. 2
  1746. deque([3, 4])
  1747. 1
  1748. deque([3, 4, 5, 6, 7])
  1749. deque([0, 1, 2, 3, 4, 5, 6, 7])
  1750. deque([7, 6, 5, 4, 3, 2, 1, 0])
  1751. deque([])
  1752. None
  1753.  
  1754.  
  1755. Dictionaries
  1756.  
  1757. dictionaries.py
  1758. '''
  1759.  
  1760. # empty dictionary
  1761. empty = {}
  1762. print empty
  1763.  
  1764. # dictionary with a list of key-value pairs
  1765. numbers = {1: 'one', 2: 'two'}
  1766. print numbers
  1767.  
  1768. # dictionary with different types
  1769. print {1: 'number', 'a': 'letter'}
  1770.  
  1771. # nested dictionaries
  1772. print {'odd numbers': {1: 'one', 3: 'three', 5: 'five'}, 'even numbers': {2: 'two', 4: 'four', 6: 'six'}}
  1773.  
  1774. '''
  1775. on console
  1776.  
  1777. {}
  1778. {1: 'one', 2: 'two'}
  1779. {'a': 'letter', 1: 'number'}
  1780. {'even numbers': {2: 'two', 4: 'four', 6: 'six'}, 'odd numbers': {1: 'one', 3: 'three', 5: 'five'}}
  1781.  
  1782.  
  1783. Dictionary items
  1784.  
  1785. dictionary_items.py
  1786. '''
  1787.  
  1788. numbers = {1: 'one', 2: 'two', 3: 'three'}
  1789. print numbers
  1790.  
  1791. # returns a value if exists in the dictionary, None otherwise
  1792. print numbers.get(1)
  1793. print numbers.get(4)
  1794.  
  1795. # checks if a key exists in the dictionary
  1796. print 1 in numbers
  1797. print 4 in numbers
  1798.  
  1799. # returns all items in a list
  1800. print numbers.items()
  1801.  
  1802. # returns all keys in a list
  1803. print numbers.keys()
  1804.  
  1805. # returns all values in a list
  1806. print numbers.values()
  1807.  
  1808. '''
  1809. on console
  1810.  
  1811. {1: 'one', 2: 'two', 3: 'three'}
  1812. one
  1813. None
  1814. True
  1815. False
  1816. [(1, 'one'), (2, 'two'), (3, 'three')]
  1817. [1, 2, 3]
  1818. ['one', 'two', 'three']
  1819.  
  1820.  
  1821. Dictionary operations
  1822.  
  1823. dictionary_operations.py
  1824. '''
  1825.  
  1826. numbers = {1: 'one', 2: 'two', 3: 'three'}
  1827. print numbers
  1828.  
  1829. # dictionary length
  1830. print len(numbers)
  1831.  
  1832. # adds an item
  1833. numbers[4] = 'four'
  1834. print numbers
  1835.  
  1836. # changes an item
  1837. numbers[4] = 'FOUR'
  1838. print numbers
  1839.  
  1840. # deletes an item
  1841. del numbers[3]
  1842. print numbers
  1843.  
  1844. # removes the key and returns their value
  1845. print numbers.pop(2)
  1846. print numbers
  1847.  
  1848. # removes all items
  1849. numbers.clear()
  1850. print numbers
  1851.  
  1852. '''
  1853. on console
  1854.  
  1855. {1: 'one', 2: 'two', 3: 'three'}
  1856. 3
  1857. {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
  1858. {1: 'one', 2: 'two', 3: 'three', 4: 'FOUR'}
  1859. {1: 'one', 2: 'two', 4: 'FOUR'}
  1860. two
  1861. {1: 'one', 4: 'FOUR'}
  1862. {}
  1863.  
  1864.  
  1865. Dictionary iteration
  1866.  
  1867. dictionary_iteration.py
  1868. '''
  1869.  
  1870. numbers = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
  1871.  
  1872. print 'keys (returns a list)'
  1873. for key in numbers.keys():
  1874.     print key
  1875.  
  1876. print '\nvalues (returns a list)'
  1877. for value in numbers.values():
  1878.     print value
  1879.  
  1880. print '\nitems (returns a list)'
  1881. for key, value in numbers.items():
  1882.     print key, value
  1883.  
  1884. print '\niterkeys (returns an iterator)'
  1885. for key in numbers.iterkeys():
  1886.     print key
  1887.  
  1888. print '\nitervalues (returns an iterator)'
  1889. for value in numbers.itervalues():
  1890.     print value
  1891.  
  1892. print '\niteritems (returns an iterator)'
  1893. for key, value in numbers.iteritems():
  1894.     print key, value
  1895.  
  1896. '''
  1897. on console
  1898.  
  1899. keys (returns a list)
  1900. 1
  1901. 2
  1902. 3
  1903. 4
  1904.  
  1905. values (returns a list)
  1906. one
  1907. two
  1908. three
  1909. four
  1910.  
  1911. items (returns a list)
  1912. 1 one
  1913. 2 two
  1914. 3 three
  1915. 4 four
  1916.  
  1917. iterkeys (returns an iterator)
  1918. 1
  1919. 2
  1920. 3
  1921. 4
  1922.  
  1923. itervalues (returns an iterator)
  1924. one
  1925. two
  1926. three
  1927. four
  1928.  
  1929. iteritems (returns an iterator)
  1930. 1 one
  1931. 2 two
  1932. 3 three
  1933. 4 four
  1934.  
  1935.  
  1936. Slices
  1937.  
  1938. slices allow us to extract a range of items from sequences: list, tuple, str, unicode and classes that implement the __getitem __() and __setitem __() special methods. The returned values are a copy of the source object.
  1939.  
  1940. slices.py
  1941. '''
  1942.  
  1943. # creates a list
  1944. numbers = [0, 1, 2, 3, 4, 5, 6, 7]
  1945.  
  1946. # prints the list items in the index range [2, 5)
  1947. print numbers[2:5]
  1948.  
  1949. # prints the list items in the index range [0, 4)
  1950. print numbers[:4]
  1951.  
  1952. # prints the list items in the index range [5, len(numbers))
  1953. print numbers[5:]
  1954.  
  1955. # prints the last 4 items in the list
  1956. print numbers[-4:]
  1957.  
  1958. # slices do not produce exceptions of 'list index out of range'
  1959. print numbers[:10]
  1960. print numbers[-10:]
  1961.  
  1962. # copies all items of the 'numbers' list
  1963. other_numbers = numbers[:]
  1964. print other_numbers
  1965.  
  1966. # 'other_numbers' and 'numbers' are two different lists
  1967. print other_numbers is numbers
  1968.  
  1969. # slices can be used in assignments
  1970. numbers[2:] = [2]
  1971. print numbers
  1972.  
  1973. # slices can operate on tuples
  1974. numbers_in_tuple = (0, 1, 2, 3, 4, 5, 6, 7)
  1975. print numbers_in_tuple[2:5]
  1976.  
  1977. # slices can operate on strings
  1978. numbers_in_string = '01234567'
  1979. print numbers_in_string[2:5]
  1980.  
  1981. # slices can operate on unicode strings
  1982. numbers_in_unicode_string = u'01234567'
  1983. print numbers_in_unicode_string[2:5]
  1984.  
  1985. # slices can not operate on sets
  1986. try:
  1987.     numbers_in_set = {0, 1, 2, 3, 4, 5, 6, 7}
  1988.     print numbers_in_set[2:5]
  1989. except TypeError:
  1990.     print 'TypeError exception: slices can not operate on sets.'
  1991.  
  1992. '''
  1993. on console
  1994.  
  1995. [2, 3, 4]
  1996. [0, 1, 2, 3]
  1997. [5, 6, 7]
  1998. [4, 5, 6, 7]
  1999. [0, 1, 2, 3, 4, 5, 6, 7]
  2000. [0, 1, 2, 3, 4, 5, 6, 7]
  2001. [0, 1, 2, 3, 4, 5, 6, 7]
  2002. False
  2003. [0, 1, 2]
  2004. (2, 3, 4)
  2005. 234
  2006. 234
  2007. TypeError exception: slices can not operate on sets.
  2008.  
  2009. list[from_index: to_index], from_index is inclusive, and to_index is exclusive, i.e., the value in from_index is included in the range and the value in to_index is not included.
  2010.  
  2011. When slices are used in assignments, it replaces the values in the original list in the specified range.
  2012.  
  2013.  
  2014. Classes
  2015.  
  2016. classes.py
  2017. '''
  2018.  
  2019. # circle class
  2020. class Circle:
  2021.     def __init__(self, (x, y), radius):
  2022.         self.x = x
  2023.         self.y = y
  2024.         self.radius = radius
  2025.  
  2026.     def diameter(self):
  2027.         return self.radius * 2
  2028.  
  2029.  
  2030. circle = Circle((0, 0), 3)
  2031. print circle.diameter()
  2032.  
  2033. circle.radius = 4
  2034. print circle.diameter()
  2035.  
  2036. '''
  2037. on console
  2038.  
  2039. 6
  2040. 8
  2041.  
  2042.  
  2043. Properties
  2044.  
  2045. properties.py
  2046. '''
  2047.  
  2048. class Circle(object):  # inherits your class from object to use @property decorator
  2049.     def __init__(self, (x, y), radius):
  2050.         self.x = x
  2051.         self.y = y
  2052.         self.radius = radius
  2053.  
  2054.     @property
  2055.     def radius(self):
  2056.         return self.__radius
  2057.  
  2058.     # radius >= 0
  2059.     @radius.setter
  2060.     def radius(self, value):
  2061.         if value < 0:
  2062.             self.__radius = 0
  2063.         else:
  2064.             self.__radius = value
  2065.  
  2066.     def diameter(self):
  2067.         return self.radius * 2
  2068.  
  2069.  
  2070. circle = Circle((0, 0), 3)
  2071. print circle.diameter()
  2072.  
  2073. circle.radius = -4
  2074. print circle.diameter()
  2075.  
  2076. '''
  2077. on console
  2078.  
  2079. 6
  2080. 0
  2081.  
  2082.  
  2083. Inheritance
  2084.  
  2085. inheritance.py
  2086. '''
  2087.  
  2088. # point class
  2089. class Point:
  2090.     def __init__(self, (x, y)):
  2091.         self.x = x
  2092.         self.y = y
  2093.  
  2094.  
  2095. # inheritance
  2096. # circle class
  2097. class Circle(Point):
  2098.     def __init__(self, (x, y), radius):
  2099.         Point.__init__(self, (x, y))
  2100.         self.radius = radius
  2101.  
  2102.  
  2103. circle = Circle((0, 0), 3)
  2104. print circle.x
  2105.  
  2106. circle.x = 4
  2107. print circle.x
  2108.  
  2109. '''
  2110. on console
  2111.  
  2112. 0
  2113. 4
  2114.  
  2115.  
  2116. Polymorphism
  2117.  
  2118. polymorphism.py
  2119. '''
  2120.  
  2121. # polygon class
  2122. class Polygon:
  2123.     def __init__(self, name):
  2124.         self.name = name
  2125.  
  2126.     def number_of_sides(self):
  2127.         raise NotImplementedError
  2128.  
  2129.  
  2130. # triangle class
  2131. class Triangle(Polygon):
  2132.     def number_of_sides(self):
  2133.         return 3
  2134.  
  2135.  
  2136. # square class
  2137. class Square(Polygon):
  2138.     def number_of_sides(self):
  2139.         return 4
  2140.  
  2141.  
  2142. # polymorphism
  2143. polygons = [Triangle('triangle'), Square('square')]
  2144.  
  2145. for p in polygons:
  2146.     print 'A {} has {} sides'.format(p.name, p.number_of_sides())
  2147.  
  2148. '''
  2149. on console
  2150.  
  2151. A triangle has 3 sides
  2152. A square has 4 sides
  2153.  
  2154.  
  2155. Truth value testing
  2156.  
  2157. truth_value_testing.py
  2158. '''
  2159.  
  2160. # this values are considered false:
  2161.  
  2162. if None:
  2163.     print 'this will not be printed'
  2164.  
  2165. if False:
  2166.     print 'this will not be printed'
  2167.  
  2168. if 0:
  2169.     print 'this will not be printed'
  2170.  
  2171. if 0L:
  2172.     print 'this will not be printed'
  2173.  
  2174. if 0.0:
  2175.     print 'this will not be printed'
  2176.  
  2177. if 0J:
  2178.     print 'this will not be printed'
  2179.  
  2180. if '':
  2181.     print 'this will not be printed'
  2182.  
  2183. if ():
  2184.     print 'this will not be printed'
  2185.  
  2186. if []:
  2187.     print 'this will not be printed'
  2188.  
  2189. if {}:
  2190.     print 'this will not be printed'
  2191.  
  2192. '''
  2193. on console
  2194.  
  2195.  
  2196.  
  2197.  
  2198. Escape sequences
  2199.  
  2200. escape_sequences.py
  2201. '''
  2202.  
  2203. print 'Horizontal tab:', '\t'
  2204. print 'Vertical tab:', '\v'
  2205. print 'Backspace:', '\b'
  2206. print 'New line:', '\n'
  2207. print 'Carriage return:', '\r'
  2208. print 'Form feed:', '\f'
  2209. print 'Single quote', '\''
  2210. print 'Double quote:', '\"'
  2211. print 'Backslash:', '\\'
  2212. print 'Bell:', '\a'
  2213.  
  2214. '''
  2215. on console
  2216.  
  2217. Horizontal tab:
  2218. Vertical tab:
  2219. Backspace:
  2220. New line:
  2221.  
  2222. Carriage return:
  2223. Form feed:
  2224. Single quote '
  2225. Double quote: "
  2226. Backslash: \
  2227. Bell:
  2228.  
  2229.  
  2230. Named arguments
  2231.  
  2232. named_arguments.py
  2233. '''
  2234.  
  2235. def numbers(minimum=0, maximum=10):
  2236.     return range(minimum, maximum + 1)
  2237.  
  2238.  
  2239. print numbers()
  2240. print numbers(minimum=5)
  2241. print numbers(maximum=5)
  2242.  
  2243. '''
  2244. on console
  2245.  
  2246. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2247. [5, 6, 7, 8, 9, 10]
  2248. [0, 1, 2, 3, 4, 5]
  2249.  
  2250.  
  2251. Lambda functions
  2252.  
  2253. lambda [arguments]: expression allows us to create anonymous functions. Lambda functions do not need the return statement, since the result of expression is always returned.
  2254.  
  2255. lambda_functions.py
  2256. '''
  2257.  
  2258. # -- a lambda function that takes one argument --
  2259. # squares a number
  2260. square = lambda x: x ** 2
  2261. print square(3)
  2262.  
  2263. # -- a lambda function that takes two arguments --
  2264. # adds two numbers
  2265. sum_ = lambda x, y: x + y
  2266. print sum_(2, 3)
  2267.  
  2268. # -- a lambda function used in 'sorted()' --
  2269. # sorts strings by length from least to greatest
  2270. print sorted(['Python', 'Ruby', 'Perl'], cmp=lambda x, y: cmp(len(x), len(y)))
  2271.  
  2272. # -- a lambda function used in 'filter()' --
  2273. # filters the even numbers
  2274. print filter(lambda n: n % 2 == 0, range(10))
  2275.  
  2276. '''
  2277. on console
  2278.  
  2279. 9
  2280. 5
  2281. ['Ruby', 'Perl', 'Python']
  2282. [0, 2, 4, 6, 8]
  2283.  
  2284. PEP 8 does not recommend using lambda functions in assignments, instead define functions using the def statement. These examples are for demonstration purposes.
  2285.  
  2286.  
  2287. Random numbers
  2288.  
  2289. random_numbers.py
  2290. '''
  2291.  
  2292. import random
  2293. import string
  2294.  
  2295. # returns a random floating point number in the range [0.0, 1.0)
  2296. print random.random()
  2297.  
  2298. # returns a random floating point number in the range [min, max]
  2299. print random.uniform(50, 100)
  2300.  
  2301. # returns a random integer number in the range [a, b]
  2302. print random.randint(50, 100)
  2303.  
  2304. # random.randrange(a, b, c) returns a random integer number in the range [a, b) every c steps
  2305. print random.randrange(0, 100, 3)
  2306.  
  2307. # shuffles a list
  2308. my_list = range(0, 10)
  2309. print my_list
  2310.  
  2311. random.shuffle(my_list)
  2312. print my_list
  2313.  
  2314. # random choices
  2315. print random.choice(my_list)
  2316. print random.choice(string.ascii_lowercase)
  2317.  
  2318. # random seed
  2319. random.seed(54321)  # Default is sys' time or urand
  2320. my_list = range(0, 10)
  2321. random.shuffle(my_list)
  2322. print my_list
  2323. random.seed(54321)
  2324. my_list = range(0, 10)
  2325. random.shuffle(my_list)
  2326. print my_list
  2327.  
  2328. '''
  2329. on console
  2330.  
  2331. 0.217586684321
  2332. 76.7631380262
  2333. 98
  2334. 69
  2335. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2336. [5, 6, 8, 3, 2, 0, 7, 1, 9, 4]
  2337. 5
  2338. a
  2339. [9, 5, 2, 6, 0, 3, 7, 1, 8, 4]
  2340. [9, 5, 2, 6, 0, 3, 7, 1, 8, 4]
  2341.  
  2342.  
  2343. Exceptions
  2344.  
  2345. exceptions.py
  2346. '''
  2347.  
  2348. def division(a, b):
  2349.     try:
  2350.         a / b
  2351.     except ZeroDivisionError:
  2352.         print 'zero division error'
  2353.  
  2354.  
  2355. division(1, 0)
  2356.  
  2357. '''
  2358. on console
  2359.  
  2360. zero division error
  2361.  
  2362.  
  2363. Raise
  2364.  
  2365. raise.py
  2366. '''
  2367.  
  2368. '''
  2369. def division(a, b):
  2370.    if b == 0:
  2371.        # raises a built-in exception
  2372.        raise ZeroDivisionError
  2373.  
  2374.    return a / b
  2375.  
  2376.  
  2377. division(1, 0)
  2378. '''
  2379.  
  2380. '''
  2381. on console
  2382.  
  2383. Traceback (most recent call last):
  2384.  File "raise.py", line 9, in <module>
  2385.    division(1, 0)
  2386.  File "raise.py", line 4, in division
  2387.    raise ZeroDivisionError
  2388. ZeroDivisionError
  2389.  
  2390.  
  2391. Keyboard input
  2392.  
  2393. keyboard_input.py
  2394. '''
  2395.  
  2396. name = raw_input('What is your name?\n')
  2397. print 'Hello', name
  2398.  
  2399. '''
  2400. on console
  2401.  
  2402. What is your name?
  2403.  
  2404.  
  2405. Get documentation
  2406.  
  2407. We can get the documentation of any Python module, function, class or method using the special attribute __doc__. __doc__ returns None if the documentation is not available.
  2408. Source code:
  2409.  
  2410. get_documentation.py
  2411. '''
  2412.  
  2413. # '__doc__' returns the existing documentation of any module, function, class or method
  2414. print int.__doc__
  2415.  
  2416. '''
  2417. on console
  2418.  
  2419. int(x=0) -> int or long
  2420. int(x, base=10) -> int or long
  2421.  
  2422. Convert a number or string to an integer, or return 0 if no arguments
  2423. are given.  If x is floating point, the conversion truncates towards zero.
  2424. If x is outside the integer range, the function returns a long instead.
  2425.  
  2426. If x is not a number or if base is given, then x must be a string or
  2427. Unicode object representing an integer literal in the given base.  The
  2428. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  2429. The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
  2430. interpret the base from the string as an integer literal.
  2431. >>> int('0b100', base=0)
  2432. 4
  2433.  
  2434.  
  2435. Own documentation
  2436.  
  2437. own_documentation.py
  2438. '''
  2439.  
  2440. class Circle:
  2441.     """ Represents a circle """
  2442.  
  2443.     def __init__(self, (x, y), radius):
  2444.         """ Constructs a circle """
  2445.         self._x = x
  2446.         self._y = y
  2447.         self._radius = radius
  2448.  
  2449.     def diameter(self):
  2450.         """ Returns the diameter """
  2451.         return self._radius * 2
  2452.  
  2453.  
  2454. print Circle.__doc__
  2455. print Circle.__init__.__doc__
  2456. print Circle.diameter.__doc__
  2457.  
  2458. '''
  2459. on console
  2460.  
  2461. Represents a circle
  2462. Constructs a circle
  2463. Returns the diameter
  2464.  
  2465.  
  2466. Unit testing
  2467.  
  2468. unit_testing.py
  2469. '''
  2470.  
  2471. def wrong_diameter(radius):
  2472.     """
  2473.        >>> wrong_diameter(2)
  2474.        4
  2475.    """
  2476.  
  2477.     return radius * 3
  2478.  
  2479.  
  2480. def right_diameter(radius):
  2481.     """
  2482.        >>> right_diameter(2)
  2483.        4
  2484.    """
  2485.  
  2486.     return radius * 2
  2487.  
  2488.  
  2489. if __name__ == '__main__':
  2490.     import doctest
  2491.  
  2492.     doctest.testmod()
  2493.  
  2494. '''
  2495. on console
  2496.  
  2497. **********************************************************************
  2498. File "unit_testing.py", line 3, in __main__.wrong_diameter
  2499. Failed example:
  2500.    wrong_diameter(2)
  2501. Expected:
  2502.    4
  2503. Got:
  2504.    6
  2505. **********************************************************************
  2506. 1 items had failures:
  2507.   1 of   1 in __main__.wrong_diameter
  2508. ***Test Failed*** 1 failures.
  2509.  
  2510.  
  2511. JSON string reader
  2512.  
  2513. json_string_reader.py
  2514. '''
  2515.  
  2516. import json
  2517. from pprint import pprint
  2518.  
  2519. # json.loads, not json.load
  2520. data = json.loads(
  2521.     '{"string":"this is a string","integer_number":1,"real_number":1.2,"boolean":true,"null":null,"array":[1,2],'
  2522.     '"object":{"1":"one","2":"two"}}')
  2523.  
  2524. pprint(data)  # pretty-print
  2525.  
  2526. '''
  2527. on console
  2528.  
  2529. {u'array': [1, 2],
  2530. u'boolean': True,
  2531. u'integer_number': 1,
  2532. u'null': None,
  2533. u'object': {u'1': u'one', u'2': u'two'},
  2534. u'real_number': 1.2,
  2535. u'string': u'this is a string'}
  2536.  
  2537.  
  2538. JSON file reader
  2539.  
  2540. json_reader.json
  2541.  
  2542. {
  2543.  "string": "this is a string",
  2544.  "integer number": 1,
  2545.  "real number": 1.2,
  2546.  "boolean": true,
  2547.  "null": null,
  2548.  "array": [
  2549.    1,
  2550.    2
  2551.  ],
  2552.  "object": {
  2553.    "1": "one",
  2554.    "2": "two"
  2555.  }
  2556. }
  2557.  
  2558. json_file_reader.py
  2559. '''
  2560.  
  2561. '''
  2562. import json
  2563. from pprint import pprint
  2564.  
  2565. with open('json_reader.json') as json_file:
  2566.    # json.load, not json.loads
  2567.    data = json.load(json_file)  # returns a dictionary or a list
  2568.  
  2569. pprint(data)  # pretty-print
  2570. '''
  2571.  
  2572. '''
  2573. on console
  2574.  
  2575. {u'array': [1, 2],
  2576. u'boolean': True,
  2577. u'integer number': 1,
  2578. u'null': None,
  2579. u'object': {u'1': u'one', u'2': u'two'},
  2580. u'real number': 1.2,
  2581. u'string': u'this is a string'}
  2582.  
  2583.  
  2584. JSON file writer
  2585.  
  2586. json_writer.py
  2587. '''
  2588.  
  2589. '''
  2590. import json
  2591.  
  2592. # data to save
  2593. data = {
  2594.    "string": "text",
  2595.    "integer number": 1,
  2596.    "real number": 1.2,
  2597.    "boolean": True,
  2598.    "null": None,
  2599.    "array": [1, 2],
  2600.    "object": {"1": "one", "2": "two"}
  2601. }
  2602.  
  2603. # saves the data in a JSON file
  2604. with open('destination.json', 'w') as f:
  2605.    # Note: use the json.dump() method, not the json.dumps() method
  2606.    json.dump(data, f, sort_keys=True, indent=2)
  2607. '''
  2608.  
  2609. '''
  2610. destination.json
  2611.  
  2612. {
  2613.  "array": [
  2614.    1,
  2615.    2
  2616.  ],
  2617.  "boolean": true,
  2618.  "integer number": 1,
  2619.  "null": null,
  2620.  "object": {
  2621.    "1": "one",
  2622.    "2": "two"
  2623.  },
  2624.  "real number": 1.2,
  2625.  "string": "text"
  2626. }
  2627.  
  2628.  
  2629. JSON file helper
  2630.  
  2631. json_helper.py
  2632. '''
  2633.  
  2634. '''
  2635. from collections import OrderedDict
  2636. import json
  2637.  
  2638.  
  2639. class JSONHelper:
  2640.    """
  2641.    Reads and saves JSON files.
  2642.    """
  2643.  
  2644.    @staticmethod
  2645.    def open(path, encoding='utf-8', preserve_order=True):
  2646.        """
  2647.        Opens a JSON file and returns a list or a dict.
  2648.        """
  2649.  
  2650.        object_pairs_hook = None
  2651.  
  2652.        # preserve order of attributes?
  2653.        if preserve_order:
  2654.            object_pairs_hook = OrderedDict
  2655.  
  2656.        # opens the JSON file
  2657.        with open(path) as f:
  2658.            return json.load(f, encoding=encoding, object_pairs_hook=object_pairs_hook)
  2659.  
  2660.    @staticmethod
  2661.    def save(path, data, encoding='utf-8', indentation=2, sort_keys=False, separators=(',', ': ')):
  2662.        """
  2663.        Saves the data in a JSON file.
  2664.        The data can be a list or a dictionary (dict).
  2665.        """
  2666.  
  2667.        # saves the JSON file
  2668.        with open(path, 'w') as f:
  2669.            json.dump(data, f, encoding=encoding, indent=indentation, sort_keys=sort_keys,
  2670.                      separators=separators)
  2671.  
  2672.  
  2673. def main():
  2674.    # gets the data from a JSON file
  2675.    data = JSONHelper.open('source.json')
  2676.  
  2677.    # saves the data in another JSON file
  2678.    JSONHelper.save('destination.json', data)
  2679.  
  2680.  
  2681. if __name__ == '__main__':
  2682.    main()
  2683.  
  2684. '''
  2685.  
  2686. '''
  2687. source.json
  2688.  
  2689. {
  2690.  "string": "text",
  2691.  "integer number": 1,
  2692.  "real number": 1.2,
  2693.  "boolean": true,
  2694.  "null": null,
  2695.  "array": [
  2696.    1,
  2697.    2
  2698.  ],
  2699.  "object": {
  2700.    "1": "one",
  2701.    "2": "two"
  2702.  }
  2703. }
  2704.  
  2705. destination.json
  2706.  
  2707. {
  2708.  "string": "text",
  2709.  "integer number": 1,
  2710.  "real number": 1.2,
  2711.  "boolean": true,
  2712.  "null": null,
  2713.  "array": [
  2714.    1,
  2715.    2
  2716.  ],
  2717.  "object": {
  2718.    "1": "one",
  2719.    "2": "two"
  2720.  }
  2721. }
  2722.  
  2723.  
  2724. Hash functions
  2725.  
  2726. hash_functions.py
  2727. '''
  2728.  
  2729. import hashlib
  2730.  
  2731. message = 'Hello World!'
  2732.  
  2733. # MD5
  2734. print hashlib.md5(message).hexdigest()
  2735.  
  2736. # SHA-1
  2737. print hashlib.sha1(message).hexdigest()
  2738.  
  2739. # SHA-224
  2740. print hashlib.sha224(message).hexdigest()
  2741.  
  2742. # SHA-256
  2743. print hashlib.sha256(message).hexdigest()
  2744.  
  2745. # SHA-384
  2746. print hashlib.sha384(message).hexdigest()
  2747.  
  2748. # SHA-512
  2749. print hashlib.sha512(message).hexdigest()
  2750.  
  2751. '''
  2752. on console
  2753.  
  2754. ed076287532e86365e841e92bfc50d8c
  2755. 2ef7bde608ce5404e97d5f042f95f89f1c232871
  2756. 4575bb4ec129df6380cedde6d71217fe0536f8ffc4e18bca530a7a1b
  2757. 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069
  2758. bfd76c0ebbd006fee583410547c1887b0292be76d582d96c242d2a792723e3fd6fd061f9d5cfd13b8f961358e6adba4a
  2759. 861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8
  2760.  
  2761.  
  2762. Argument parser
  2763.  
  2764. argument_parser.py
  2765. '''
  2766.  
  2767. import argparse
  2768. import hashlib
  2769.  
  2770. parser = argparse.ArgumentParser(description='Hash functions utility')
  2771.  
  2772. parser.add_argument('-hf', '--hash', help='hash function')
  2773. parser.add_argument('-s', '--string', help='string to hash')
  2774.  
  2775. args = parser.parse_args()
  2776.  
  2777. if args.string:
  2778.     if args.hash == 'md5':
  2779.         print hashlib.md5(args.string).hexdigest()
  2780.     elif args.hash == 'sha1':
  2781.         print hashlib.sha1(args.string).hexdigest()
  2782.     elif args.hash == 'sha224':
  2783.         print hashlib.sha224(args.string).hexdigest()
  2784.     elif args.hash == 'sha256':
  2785.         print hashlib.sha256(args.string).hexdigest()
  2786.     elif args.hash == 'sha384':
  2787.         print hashlib.sha384(args.string).hexdigest()
  2788.     elif args.hash == 'sha512':
  2789.         print hashlib.sha512(args.string).hexdigest()
  2790.     else:
  2791.         parser.print_help()
  2792. else:
  2793.     parser.print_help()
  2794.  
  2795. '''
  2796. on console
  2797.  
  2798. python argument_parser.py
  2799. '''
  2800.  
  2801. '''
  2802. usage: argument_parser.py [-h] [-hf HASH] [-s STRING]
  2803.  
  2804. Hash functions utility
  2805.  
  2806. optional arguments:
  2807.  -h, --help            show this help message and exit
  2808.  -hf HASH, --hash HASH
  2809.                        hash function
  2810.  -s STRING, --string STRING
  2811.                        string to hash
  2812.  
  2813.  
  2814.  
  2815. python argument_parser.py -s "Hello World!" -hf md5
  2816.  
  2817. '''
  2818.  
  2819. '''
  2820. on console
  2821.  
  2822. ed076287532e86365e841e92bfc50d8c
  2823.  
  2824.  
  2825. Version
  2826.  
  2827. To determine the Python version, type python --version in the command line, or run the following script to see more details about the version.
  2828.  
  2829. version.py
  2830. '''
  2831.  
  2832. import sys
  2833.  
  2834. # prints the Python version in a string
  2835. print sys.version
  2836. print
  2837.  
  2838. # to extract information about the Python version use 'sys.version_info'
  2839. info_version = sys.version_info
  2840. print info_version
  2841. print 'major:', info_version[0]
  2842. print 'minor:', info_version[1]
  2843. print 'micro:', info_version[2]
  2844. print 'release level:', info_version[3]
  2845. print 'serial:', info_version[4]
  2846.  
  2847. '''
  2848. on console
  2849.  
  2850. 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)]
  2851.  
  2852. sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)
  2853. major: 2
  2854. minor: 7
  2855. micro: 13
  2856. release level: final
  2857. serial: 0
  2858.  
  2859. sys.version prints the Python version in a string. It includes the build number and compiler used. However, to extract information about the version use sys.version_info instead. The components can be accessed by index (sys.version_info[0]) or by name (sys.version_info.mayor).
  2860. sys.version_info is available since version 2.0. sys.version_info components can be accessed by name since version 2.7.
  2861.  
  2862.  
  2863. Keywords
  2864.  
  2865. keywords.py
  2866. '''
  2867.  
  2868. import keyword
  2869.  
  2870. print str(len(keyword.kwlist)) + ' keywords\n'
  2871.  
  2872. for kw in keyword.kwlist:
  2873.     print kw
  2874.  
  2875. '''
  2876. on console
  2877.  
  2878. 31 keywords
  2879.  
  2880. and
  2881. as
  2882. assert
  2883. break
  2884. class
  2885. continue
  2886. def
  2887. del
  2888. elif
  2889. else
  2890. except
  2891. exec
  2892. finally
  2893. for
  2894. from
  2895. global
  2896. if
  2897. import
  2898. in
  2899. is
  2900. lambda
  2901. not
  2902. or
  2903. pass
  2904. print
  2905. raise
  2906. return
  2907. try
  2908. while
  2909. with
  2910. yield
  2911.  
  2912.  
  2913. continue
  2914.  
  2915. continue.py
  2916. '''
  2917.  
  2918. # prints only the even numbers
  2919. for i in xrange(10):
  2920.     if i % 2 != 0:
  2921.         continue
  2922.     print i
  2923.  
  2924. '''
  2925. on console
  2926.  
  2927. 0
  2928. 2
  2929. 4
  2930. 6
  2931. 8
  2932.  
  2933.  
  2934. break
  2935.  
  2936. break ends the loop immediately.
  2937.  
  2938. break.py
  2939. '''
  2940.  
  2941.  
  2942. def search_character(character, text):
  2943.     """
  2944.    Prints the index of the first occurrence of the specified character inside the text, otherwise it does not print anything.
  2945.    """
  2946.  
  2947.     # walks through every character in the text
  2948.     for index, ch in enumerate(text):
  2949.         # if the character has been found in the text
  2950.         if character == ch:
  2951.             # prints on the console the character and its index inside the text
  2952.             print '"{}" (index: {})'.format(character, index)
  2953.  
  2954.             # ends the loop immediately
  2955.             break
  2956.  
  2957.  
  2958. def main():
  2959.     # creates a text
  2960.     text = 'Hello World!'
  2961.  
  2962.     # searches the specified characters inside the text
  2963.     search_character(u'o', text)
  2964.     search_character(u'n', text)
  2965.     search_character(u'z', text)
  2966.  
  2967.  
  2968. if __name__ == '__main__':
  2969.     main()
  2970.  
  2971. '''
  2972. on console
  2973.  
  2974. "o" (index: 4)
  2975. "r" (index: 8)
  2976.  
  2977.  
  2978. return
  2979.  
  2980. return allows us to return a value in a function. If return is omitted, the function returns None.
  2981.  
  2982. return.py
  2983. '''
  2984.  
  2985. def find_character(character, text):
  2986.     """
  2987.    Returns 'True' if the specified character is in the text, if not returns 'False'.
  2988.    """
  2989.  
  2990.     return character in text
  2991.  
  2992.  
  2993. def main():
  2994.     text = 'Hello World!'
  2995.     print 'character found:', find_character('o', text)
  2996.     print 'character found:', find_character('n', text)
  2997.     print 'character found:', find_character('z', text)
  2998.  
  2999.  
  3000. if __name__ == '__main__':
  3001.     main()
  3002.  
  3003. '''
  3004. on console
  3005.  
  3006. character found: True
  3007. character found: False
  3008. character found: False
  3009.  
  3010.  
  3011. Built-in functions
  3012.  
  3013. built_in_functions.py
  3014. '''
  3015.  
  3016. # returns the absolute value of a number
  3017. print 'abs(-5)'
  3018. print abs(-5)
  3019.  
  3020. # returns an empty dictionary
  3021. print '\ndict()'
  3022. print dict()
  3023.  
  3024. # returns the memory address of the specified object
  3025. print '\nid(5)'
  3026. print id(5)
  3027.  
  3028. # returns an empty list
  3029. print '\nlist()'
  3030. print list()
  3031.  
  3032. # returns the maximum value
  3033. print '\nmax([93, 86, 38, 23, 46, 32])'
  3034. print max([93, 86, 38, 23, 46, 32])
  3035.  
  3036. # returns the minimum value
  3037. print '\nmin([93, 86, 38, 23, 46, 32])'
  3038. print min([93, 86, 38, 23, 46, 32])
  3039.  
  3040. # returns the ASCII code of the specified character
  3041. print "\nord('a')"
  3042. print ord('a')
  3043.  
  3044. # returns 2 ** 3 (exponentiation)
  3045. print '\npow(2, 3)'
  3046. print pow(2, 3)
  3047.  
  3048. # returns a list of values
  3049. print '\nrange(0, 10)'
  3050. print range(0, 10)
  3051. print 'range(0, 10, 2)'
  3052. print range(0, 10, 2)
  3053.  
  3054. # returns a rounded value
  3055. print '\nprint round(1.234, 2)'
  3056. print round(1.234, 2)
  3057. print 'round(1.235, 2)'
  3058. print round(1.235, 2)
  3059. print 'round(1.245, 2)'
  3060. print round(1.245, 2)
  3061.  
  3062. # returns the total sum of all values
  3063. print '\nsum([93, 86, 38, 23, 46, 32])'
  3064. print sum([93, 86, 38, 23, 46, 32])
  3065.  
  3066. # returns a tuple
  3067. print '\ntuple([1, 2])'
  3068. print tuple([1, 2])
  3069. print "tuple({1: 'One', 2: 'Two'})"
  3070. print tuple({1: 'One', 2: 'Two'})
  3071.  
  3072. '''
  3073. on console
  3074.  
  3075. abs(-5)
  3076. 5
  3077.  
  3078. dict()
  3079. {}
  3080.  
  3081. id(5)
  3082. 5154456
  3083.  
  3084. list()
  3085. []
  3086.  
  3087. max([93, 86, 38, 23, 46, 32])
  3088. 93
  3089.  
  3090. min([93, 86, 38, 23, 46, 32])
  3091. 23
  3092.  
  3093. ord('a')
  3094. 97
  3095.  
  3096. pow(2, 3)
  3097. 8
  3098.  
  3099. range(0, 10)
  3100. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  3101. range(0, 10, 2)
  3102. [0, 2, 4, 6, 8]
  3103.  
  3104. print round(1.234, 2)
  3105. 1.23
  3106. round(1.235, 2)
  3107. 1.24
  3108. round(1.245, 2)
  3109. 1.25
  3110.  
  3111. sum([93, 86, 38, 23, 46, 32])
  3112. 318
  3113.  
  3114. tuple([1, 2])
  3115. (1, 2)
  3116. tuple({1: 'One', 2: 'Two'})
  3117. (1, 2)
  3118.  
  3119.  
  3120. type()
  3121.  
  3122. type() returns the data type of the specified object.
  3123.  
  3124. type.py
  3125. '''
  3126.  
  3127. # imports a module for demonstration purposes
  3128. import sys
  3129.  
  3130.  
  3131. # a class for demonstration purposes
  3132. class CustomClass:
  3133.     def __init__(self):
  3134.         pass
  3135.  
  3136.     def custom_method(self):
  3137.         pass
  3138.  
  3139.  
  3140. # a function for demonstration purposes
  3141. def custom_function():
  3142.     pass
  3143.  
  3144.  
  3145. # a generator for demonstration purposes
  3146. def custom_generator():
  3147.     yield 1
  3148.  
  3149.  
  3150. # instance of a class for demonstration purposes
  3151. cc = CustomClass()
  3152.  
  3153. # type() returns the data type of the specified object
  3154.  
  3155. # 'str' type
  3156. print type('string')
  3157.  
  3158. # 'unicode' type
  3159. print type(u'unicode string')
  3160.  
  3161. # 'int' type
  3162. print type(0)
  3163.  
  3164. # 'long' type
  3165. print type(1L)
  3166.  
  3167. # 'float' type
  3168. print type(1.2)
  3169.  
  3170. # 'complex' type
  3171. print type(1.2J)
  3172.  
  3173. # 'bool' type
  3174. print type(True)
  3175.  
  3176. # 'tuple' type
  3177. print type((1, 2))
  3178.  
  3179. # 'list' type
  3180. print type([1, 2])
  3181.  
  3182. # 'set' type
  3183. print type({1, 2})
  3184.  
  3185. # 'frozenset' type
  3186. print type(frozenset([1, 2]))
  3187.  
  3188. # 'dict' type
  3189. print type({1: 'one', 2: 'two'})
  3190.  
  3191. # 'NoneType' type
  3192. print type(None)
  3193.  
  3194. # 'type' type
  3195. print type(type(None))
  3196.  
  3197. # 'classobj' type
  3198. print type(CustomClass)
  3199.  
  3200. # 'function' type
  3201. print type(custom_function)
  3202.  
  3203. # 'function' type
  3204. print type(lambda: None)
  3205.  
  3206. # 'generator' type
  3207. print type(custom_generator())
  3208.  
  3209. # 'module' type
  3210. print type(sys)
  3211.  
  3212. # 'instance' type
  3213. print type(cc)
  3214.  
  3215. # 'instancemethod' type
  3216. print type(cc.custom_method)
  3217.  
  3218. # 'NotImplementedType' type
  3219. print type(NotImplemented)
  3220.  
  3221. '''
  3222. on console
  3223.  
  3224. <type 'str'>
  3225. <type 'unicode'>
  3226. <type 'int'>
  3227. <type 'long'>
  3228. <type 'float'>
  3229. <type 'complex'>
  3230. <type 'bool'>
  3231. <type 'tuple'>
  3232. <type 'list'>
  3233. <type 'set'>
  3234. <type 'frozenset'>
  3235. <type 'dict'>
  3236. <type 'NoneType'>
  3237. <type 'type'>
  3238. <type 'classobj'>
  3239. <type 'function'>
  3240. <type 'function'>
  3241. <type 'generator'>
  3242. <type 'module'>
  3243. <type 'instance'>
  3244. <type 'instancemethod'>
  3245. <type 'NotImplementedType'>
  3246.  
  3247.  
  3248. sorted()
  3249.  
  3250. sorted.py
  3251. '''
  3252.  
  3253. letters = ['a', 'd', 'c', 'b']
  3254.  
  3255. for letter in sorted(letters):
  3256.     print letter
  3257.  
  3258. print
  3259.  
  3260. for letter in sorted(letters, reverse=True):
  3261.     print letter
  3262.  
  3263. '''
  3264. on console
  3265.  
  3266. a
  3267. b
  3268. c
  3269. d
  3270.  
  3271. d
  3272. c
  3273. b
  3274. a
  3275.  
  3276.  
  3277. reversed()
  3278.  
  3279. reversed(sequence) returns a reverse iterator. sequence must be an object that has the __reversed __() special method or support the sequence protocol (having the __len __() and __getitem__() special methods with integer arguments starting at 0).
  3280.  
  3281. reversed.py
  3282. '''
  3283.  
  3284. # creates a list of letters
  3285. letters = ['a', 'b', 'c', 'd']
  3286.  
  3287. # prints the object type
  3288. print type(reversed(letters))
  3289.  
  3290. # prints the letters in reverse order
  3291. for letter in reversed(letters):
  3292.     # if the 'b' letter is found
  3293.     if letter == 'b':
  3294.         # stops the loop
  3295.         break
  3296.  
  3297.     # prints the letter
  3298.     print letter
  3299.  
  3300. '''
  3301. on console
  3302.  
  3303. <type 'listreverseiterator'>
  3304. d
  3305. c
  3306.  
  3307.  
  3308. map()
  3309.  
  3310. map(function, iterable, [iterable2, iterable3, ...]) applies function to every item of iterable and returns a list object with the results. If more iterables are provided, function must accept the same number of arguments, being iterables processed in parallel. If iterables have different lengths, iterables with shorter lengths will be extended with None items. The iterable arguments may be a sequence or any iterable object; the result is always a list.
  3311.  
  3312. map.py
  3313. '''
  3314.  
  3315. import math
  3316.  
  3317.  
  3318. # user-defined function
  3319. def square(a):
  3320.     """
  3321.    Returns the square of the specified number.
  3322.    """
  3323.  
  3324.     return a ** 2
  3325.  
  3326.  
  3327. # 'map()' with a built-in function that takes one argument
  3328. print map(math.factorial, [1, 2, 3, 4])
  3329.  
  3330. # 'map()' with a built-in function that takes two arguments
  3331. print map(math.pow, [2, 2, 2], [1, 2, 3])
  3332.  
  3333. # 'map()' with an anonymous function (lambda) that takes one argument
  3334. print map(lambda x: x ** 2, [1, 2, 3, 4])
  3335.  
  3336. # 'map()' with an anonymous function (lambda) that takes two arguments
  3337. print map(lambda x, y: x + y, [1, 2, 3, 4], [-1, -2, -3, -4])
  3338.  
  3339. # 'map()' with a user-defined function that takes one argument
  3340. print map(square, [1, 2, 3, 4])
  3341.  
  3342. '''
  3343. on console
  3344.  
  3345. [1, 2, 6, 24]
  3346. [2.0, 4.0, 8.0]
  3347. [1, 4, 9, 16]
  3348. [0, 0, 0, 0]
  3349. [1, 4, 9, 16]
  3350.  
  3351.  
  3352. enumerate()
  3353.  
  3354. enumerate.py
  3355. '''
  3356.  
  3357. letters = ['a', 'b', 'c', 'd']
  3358.  
  3359. for index, letter in enumerate(letters):
  3360.     print '{}. {}'.format(index + 1, letter)
  3361.  
  3362. '''
  3363. on console
  3364.  
  3365. 1. a
  3366. 2. b
  3367. 3. c
  3368. 4. d
  3369.  
  3370.  
  3371. filter()
  3372.  
  3373. filter(function, iterable) returns a list with items where function returns True. iterable can be a sequence, a container that supports iteration, or an iterator. If iterable is a string (str or unicode) or tuple, it returns a string or tuple respectively; otherwise it always returns a list. If function is None all items of iterable that are considered False are removed.
  3374. filter(function, iterable) is equivalent to the list comprehension [item for item in iterable if function(item)] if function is not None, and [item for item in iterable if function(item)] if function is None.
  3375.  
  3376. filter.py
  3377. '''
  3378.  
  3379. # -- definition of functions for demonstration purposes --
  3380.  
  3381. def only_odd_numbers(number):
  3382.     """
  3383.    Filters the odd numbers. Use with 'filter()'.
  3384.    """
  3385.  
  3386.     return not number % 2 == 0
  3387.  
  3388.  
  3389. def remove_spaces(character):
  3390.     """
  3391.    Remove whitespaces. Use with 'filter()'.
  3392.    """
  3393.  
  3394.     return character != ' '
  3395.  
  3396.  
  3397. def only_ints(data):
  3398.     """
  3399.    Filters 'int' data types. Use with 'filter()'.
  3400.    """
  3401.  
  3402.     return type(data) is int
  3403.  
  3404.  
  3405. # 'filter()' with an anonymous function (lambda) that takes a 'list' argument; returns a 'list'
  3406. # prints only the even numbers
  3407. print filter(lambda x: x % 2 == 0, range(10))
  3408.  
  3409. # 'filter()' with a user-defined function that takes a 'list' argument; returns a 'list'
  3410. # prints only the odd numbers
  3411. print filter(only_odd_numbers, range(10))
  3412.  
  3413. # 'filter()' with a user-defined function that takes a 'xrange' argument; returns a 'list'
  3414. # prints only the odd numbers
  3415. print filter(only_odd_numbers, xrange(10))
  3416.  
  3417. # 'filter()' with a user-defined function that takes a 'str' argument; returns a 'str'
  3418. # prints the string without whitespaces
  3419. print filter(remove_spaces, 'a string')
  3420.  
  3421. # 'filter()' with a user-defined function that takes a 'tuple' argument; returns a 'tuple'
  3422. # prints only 'int' data types
  3423. print filter(only_ints, (2, 2.0, 'a', 4))
  3424.  
  3425. # 'filter()' with 'None' in its first parameter
  3426. # removes items that are considered 'False'
  3427. print filter(None, [0, [], (), {}, False, True, 1, '', 'abc'])
  3428.  
  3429. '''
  3430. on console
  3431.  
  3432. [0, 2, 4, 6, 8]
  3433. [1, 3, 5, 7, 9]
  3434. [1, 3, 5, 7, 9]
  3435. astring
  3436. (2, 4)
  3437. [True, 1, 'abc']
  3438.  
  3439.  
  3440. reduce()
  3441.  
  3442. reduce(function, iterable[, initializer]) returns the cumulative result of function on each item of iterable, from left to right. initializer represents the initial value by default.
  3443.  
  3444. reduce.py
  3445. '''
  3446.  
  3447. # user-defined function
  3448. def product(x, y):
  3449.     """
  3450.    Returns the product of two numbers.
  3451.    """
  3452.  
  3453.     return x * y
  3454.  
  3455.  
  3456. # creates a list of integers
  3457. numbers = [1, 2, 3, 4]
  3458.  
  3459. # 'reduce()' that takes a lambda function (anonymous function) in its first argument
  3460. # returns the sum of the elements of the 'numbers' list ; it is equivalent to (((1+2)+3)+4)
  3461. print reduce(lambda x, y: x + y, numbers)
  3462.  
  3463. # 'reduce()' that takes a user-defined function in its first argument
  3464. # returns the product of the elements of the 'numbers' list ; it is equivalent to (((1*2)*3)*4)
  3465. print reduce(product, numbers)
  3466.  
  3467. # 'reduce()' that takes an 'xrange' object in its second argument
  3468. # returns the product of the numbers in the range [1, 5); it is equivalent to (((1*2)*3)*4)
  3469. print reduce(product, xrange(1, 5))
  3470.  
  3471. # 'reduce()' with an initial value equal to 10
  3472. # returns the product of the initial value and the items of the 'numbers' list; it is equivalent to (((10*1)*2)*3)*4)
  3473. print reduce(product, numbers, 10)
  3474.  
  3475. '''
  3476. on console
  3477.  
  3478. 10
  3479. 24
  3480. 24
  3481. 240
  3482.  
  3483.  
  3484. zip()
  3485.  
  3486. zip.py
  3487. '''
  3488.  
  3489. letters = ['a', 'b', 'c', 'd']
  3490. numbers = [1, 2, 3, 4]
  3491.  
  3492. # zip (returns a list with tuples)
  3493. for letter, number in zip(letters, numbers):
  3494.     print letter, number
  3495.  
  3496. '''
  3497. on console
  3498.  
  3499. a 1
  3500. b 2
  3501. c 3
  3502. d 4
  3503.  
  3504.  
  3505. izip()
  3506.  
  3507. izip.py
  3508. '''
  3509.  
  3510. from itertools import izip
  3511.  
  3512. letters = ['a', 'b', 'c', 'd']
  3513. numbers = [1, 2, 3, 4]
  3514.  
  3515. # izip (returns an iterator with tuples)
  3516. for letter, number in izip(letters, numbers):
  3517.     print letter, number
  3518.  
  3519. '''
  3520. on console
  3521.  
  3522. a 1
  3523. b 2
  3524. c 3
  3525. d 4
  3526.  
  3527.  
  3528. Built-in list
  3529.  
  3530. built_in_list.py
  3531. '''
  3532.  
  3533. import __builtin__
  3534.  
  3535. print str(len(dir(__builtin__))) + ' built-in functions and variables\n'
  3536.  
  3537. for name in dir(__builtin__):
  3538.     print name
  3539.  
  3540. '''
  3541. on console
  3542.  
  3543. 144 built-in functions and variables
  3544.  
  3545. ArithmeticError
  3546. AssertionError
  3547. AttributeError
  3548. BaseException
  3549. BufferError
  3550. BytesWarning
  3551. DeprecationWarning
  3552. EOFError
  3553. Ellipsis
  3554. EnvironmentError
  3555. Exception
  3556. False
  3557. FloatingPointError
  3558. FutureWarning
  3559. GeneratorExit
  3560. IOError
  3561. ImportError
  3562. ImportWarning
  3563. IndentationError
  3564. IndexError
  3565. KeyError
  3566. KeyboardInterrupt
  3567. LookupError
  3568. MemoryError
  3569. NameError
  3570. None
  3571. NotImplemented
  3572. NotImplementedError
  3573. OSError
  3574. OverflowError
  3575. PendingDeprecationWarning
  3576. ReferenceError
  3577. RuntimeError
  3578. RuntimeWarning
  3579. StandardError
  3580. StopIteration
  3581. SyntaxError
  3582. SyntaxWarning
  3583. SystemError
  3584. SystemExit
  3585. TabError
  3586. True
  3587. TypeError
  3588. UnboundLocalError
  3589. UnicodeDecodeError
  3590. UnicodeEncodeError
  3591. UnicodeError
  3592. UnicodeTranslateError
  3593. UnicodeWarning
  3594. UserWarning
  3595. ValueError
  3596. Warning
  3597. WindowsError
  3598. ZeroDivisionError
  3599. __debug__
  3600. __doc__
  3601. __import__
  3602. __name__
  3603. __package__
  3604. abs
  3605. all
  3606. any
  3607. apply
  3608. basestring
  3609. bin
  3610. bool
  3611. buffer
  3612. bytearray
  3613. bytes
  3614. callable
  3615. chr
  3616. classmethod
  3617. cmp
  3618. coerce
  3619. compile
  3620. complex
  3621. copyright
  3622. credits
  3623. delattr
  3624. dict
  3625. dir
  3626. divmod
  3627. enumerate
  3628. eval
  3629. execfile
  3630. exit
  3631. file
  3632. filter
  3633. float
  3634. format
  3635. frozenset
  3636. getattr
  3637. globals
  3638. hasattr
  3639. hash
  3640. help
  3641. hex
  3642. id
  3643. input
  3644. int
  3645. intern
  3646. isinstance
  3647. issubclass
  3648. iter
  3649. len
  3650. license
  3651. list
  3652. locals
  3653. long
  3654. map
  3655. max
  3656. memoryview
  3657. min
  3658. next
  3659. object
  3660. oct
  3661. open
  3662. ord
  3663. pow
  3664. print
  3665. property
  3666. quit
  3667. range
  3668. raw_input
  3669. reduce
  3670. reload
  3671. repr
  3672. reversed
  3673. round
  3674. set
  3675. setattr
  3676. slice
  3677. sorted
  3678. staticmethod
  3679. str
  3680. sum
  3681. super
  3682. tuple
  3683. type
  3684. unichr
  3685. unicode
  3686. vars
  3687. xrange
  3688. zip
  3689.  
  3690.  
  3691. Run script
  3692.  
  3693. first_program.py
  3694. '''
  3695.  
  3696. print 'Hello World!'
  3697.  
  3698. '''
  3699. run_script.py
  3700. '''
  3701.  
  3702. import os
  3703. import subprocess
  3704.  
  3705. # method 1
  3706. os.system('python first_program.py')
  3707.  
  3708. # method 2
  3709. subprocess.call(['python', 'first_program.py'])
  3710.  
  3711. '''
  3712. on console
  3713.  
  3714. Hello World!
  3715. Hello World!
  3716.  
  3717.  
  3718. Run script and check output
  3719.  
  3720. first_program.py
  3721. '''
  3722.  
  3723. print 'Hello World!'
  3724.  
  3725. '''
  3726. run_script_and_check_output.py
  3727. '''
  3728.  
  3729. '''
  3730. import subprocess
  3731.  
  3732. # method 1
  3733. print subprocess.check_output(['python', 'first_program.py']),
  3734.  
  3735. # method 2
  3736. process = subprocess.Popen(['python', 'first_program.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  3737.                           stderr=subprocess.PIPE)
  3738. print process.stdout.read(),
  3739. '''
  3740.  
  3741. '''
  3742. on console
  3743.  
  3744. Hello World!
  3745. Hello World!
  3746.  
  3747.  
  3748. Save output
  3749.  
  3750. save_output.py
  3751. '''
  3752.  
  3753. '''
  3754. import sys
  3755.  
  3756. sys.stdout = open('output.txt', 'w')
  3757. print 'Hello World!'
  3758.  
  3759. output.txt
  3760. '''
  3761.  
  3762. '''
  3763. on console
  3764.  
  3765. Hello World!
  3766. '''
  3767.  
  3768. # ------------ LIBRARIES --------------
  3769. '''
  3770. Python has a large set of function by default, but also some functions that can
  3771. be imported to your code through the 'import' statement
  3772. Once you import a library you will be able to use all the public functions available
  3773. in that library.
  3774.  
  3775. A library (or module) is a python script that exports functions and/or data to other scripts.
  3776. In python any script can become a module ( we will explore this later).
  3777.  
  3778. You can also import specific functions to your code as opposed to the whole lib
  3779. to do so you use this statement
  3780.  
  3781. from libX import functionName
  3782.  
  3783. This can make you code faster in some implementation, since Python doesn't
  3784. have to import all the functions from the library libX
  3785.  
  3786.  
  3787. Some libraries do not come with the main installation of Python.
  3788. In that case you will have to manually install the library before
  3789. being able to import it to you code.
  3790.  
  3791. '''
Add Comment
Please, Sign In to add comment