Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Demos-In-General.txt --
- # Python 2.7.13
- '''
- CONTENT:
- The Zen of Python
- First program
- Comments
- Data types
- Data type conversions
- Variables
- Arithmetic operators
- Comparison operators
- Logical operators
- Bitwise operators
- Import
- Functions
- Math functions
- if
- if-else
- if-elif
- if-elif-else
- for
- for-else
- while
- Recursion
- Strings
- String format
- String items
- String operations
- String methods
- String constants
- Tuples
- Tuple items
- Lists
- List items
- List operations
- List methods
- List conversion
- List comprehensions
- Stacks
- Queues
- Deque
- Dictionaries
- Dictionary items
- Dictionary operations
- Dictionary iteration
- Slices
- Classes
- Properties
- Inheritance
- Polymorphism
- Truth value testing
- Escape sequences
- Named arguments
- Lambda functions
- Random numbers
- Exceptions
- Raise
- Keyboard input
- Get documentation
- Own documentation
- Unit testing
- CSV files
- JSON string reader
- JSON file reader
- JSON file writer
- JSON file helper
- Hash functions
- Argument parser
- Version
- Keywords
- continue
- break
- return
- Built-in functions
- type()
- sorted()
- reversed()
- map()
- enumerate()
- filter()
- reduce()
- zip()
- izip()
- Built-in list
- Run script
- Run script and check output
- Save output
- Variables, data types, functions, operators and comments in Python
- The Zen of Python
- Import the this module to read The Zen of Python by Tim Peters.
- Description:
- The Zen of Python is a list of good practices for writing code in Python.
- Source code:
- zen.py
- '''
- # shows The Zen of Python by Tim Peters
- import this
- '''
- on console
- The Zen of Python, by Tim Peters
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than *right* now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
- First program:
- This example shows how to print a string on the console using the print statement.
- 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.
- Source code:
- first_program.py
- '''
- print u'Hello World!'
- '''
- on console
- Hello World!
- ### prints the string u'Hello World! on the console. u means that it is a unicode string.
- Comments
- This example shows how to write comments in a Python script.
- comments.py
- '''
- # This is a single-line comment
- # This is a
- # multi-line comment
- '''
- 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.
- Data types
- This example shows some data types available in Python.
- data_types.py
- '''
- # strings
- print 'This is a string'
- print "This is a string"
- print '''This is a string'''
- print """This is a string"""
- # unicode strings
- print u'This is a unicode string'
- print u"This is a unicode string"
- print u'''This is a unicode string'''
- print u"""This is a unicode string"""
- # integer
- print 0
- # long
- print 9999999999L
- # float
- print 1.2
- # complex
- print 1.2J
- # booleans
- print True
- print False
- # none
- print None
- # list (mutable list)
- print [1, 2]
- # tuple (immutable list)
- print (1, 2)
- # set (mutable set)
- print {1, 2}
- # frozenset (inmutable set)
- print frozenset([1, 2])
- # dictionary
- print {1: 'one', 2: 'two'}
- '''
- on console
- This is a string
- This is a string
- This is a string
- This is a string
- This is a unicode string
- This is a unicode string
- This is a unicode string
- This is a unicode string
- 0
- 9999999999
- 1.2
- 1.2j
- True
- False
- None
- [1, 2]
- (1, 2)
- set([1, 2])
- frozenset([1, 2])
- {1: 'one', 2: 'two'}
- Data type Description Example
- str string 'string'
- unicode unicode string u'unicode string'
- int integer number 1
- long long integer number 9999999999L
- float floating-point number 1.0
- complex complex number 1.1J
- bool boolean value True
- None none None
- list mutable list [0, 1]
- tuple immutable list (0, 1)
- set mutable list without duplicates {0, 1} or set([0, 1])
- frozenset immutable list frozenset([0, 1])
- without duplicates
- dict dictionary {0: 'cero', 1: 'uno'}
- Data type conversions
- data_type_conversions.py
- '''
- # int()
- print 'int() examples'
- print int(2.1)
- print int(2.6)
- print int('2')
- # long()
- print '\nlong() examples'
- print long(2)
- print long('2')
- # float()
- print '\nfloat() examples'
- print float(2)
- print float('2')
- print float('2.1')
- # complex()
- print '\ncomplex() examples'
- print complex(2)
- print complex(2.1)
- print complex('2.1')
- # str()
- print '\nstr() examples'
- print str(2)
- print str(2L)
- print str(2.1)
- print str(2.1J)
- print str(True)
- # bool()
- print '\nbool() examples'
- print bool(0)
- print bool(1)
- print bool(-1)
- print bool('True')
- print bool('False')
- print bool('')
- '''
- on console
- int() examples
- 2
- 2
- 2
- long() examples
- 2
- 2
- float() examples
- 2.0
- 2.0
- 2.1
- complex() examples
- (2+0j)
- (2.1+0j)
- (2.1+0j)
- str() examples
- 2
- 2
- 2.1
- 2.1j
- True
- bool() examples
- False
- True
- True
- True
- True
- False
- Variables
- variables.py
- '''
- string = 'This is a string'
- integer_number = 0
- long_number = 1L
- float_number = 1.2
- complex_number = 1.2J
- boolean_value = True
- my_tuple = (1, 2)
- my_list = [1, 2]
- my_set = {1, 2}
- my_frozen_set = frozenset([1, 2])
- my_dictionary = {1: 'one', 2: 'two'}
- print string
- print integer_number
- print long_number
- print float_number
- print complex_number
- print boolean_value
- print my_tuple
- print my_list
- print my_set
- print my_frozen_set
- print my_dictionary
- '''
- on console
- This is a string
- 0
- 1
- 1.2
- 1.2j
- True
- (1, 2)
- [1, 2]
- set([1, 2])
- frozenset([1, 2])
- {1: 'one', 2: 'two'}
- Arithmetic operators
- arithmetic_operators.py
- '''
- # addition
- print 2 + 3
- # subtraction
- print 3 - 2
- # multiplication
- print 2 * 3
- # integer division
- print 3 / 2
- # float division
- print 3 / 2.0
- # exponentiation
- print 2 ** 3
- # modulus operator (returns the remainder of a division)
- print 3 % 2
- # use parentheses for grouping
- print 1 + 2 * 3 + 4
- print (1 + 2) * (3 + 4)
- '''
- on console
- 5
- 1
- 6
- 1
- 1.5
- 8
- 1
- 11
- 21
- Comparison operators
- comparison_operators.py
- '''
- # is equal to
- print 1 == 1
- # is not equal to
- print 1 != 1
- # is greater than
- print 2 > 1
- # is less than
- print 2 < 1
- # is greater than or equal to
- print 2 >= 1
- # is less than or equal to
- print 2 <= 1
- # object identity
- print 2 is int(2)
- # negated object identity
- print 2.0 is not int(2)
- '''
- on console
- True
- False
- True
- False
- True
- False
- True
- True
- operator description
- < strictly less than
- <= less than or equal
- > strictly greater than
- >= greater than or equal
- == equal
- != not equal
- is object identity
- is not negated object identity
- Logical operators
- logical_operators.py
- '''
- # AND
- print 'AND operator'
- print True and True
- print True and False
- print False and True
- print False and False
- # OR
- print '\nOR operator'
- print True or True
- print True or False
- print False or True
- print False or False
- # NOT
- print '\nNOT operator'
- print not True
- print not False
- '''
- on console
- AND operator
- True
- False
- False
- False
- OR operator
- True
- True
- True
- False
- NOT operator
- False
- True
- Bitwise operators
- bitwise_operators.py
- '''
- # 15 == 0000 1111
- # 3 == 0000 0011
- # binary AND
- print 15 & 3 # 0000 0011 == 3
- # binary OR
- print 15 | 3 # 0000 1111 == 15
- # binary XOR
- print 15 ^ 3 # 0000 1100 == 12
- # binary NOT
- print ~3 # 1111 1100 == -4
- # binary LEFT SHIFT
- print 3 << 1 # 0000 0110 == 6
- # binary RIGHT SHIFT
- print 3 >> 1 # 0000 0001 == 1
- '''
- on console
- 3
- 15
- 12
- -4
- 6
- 1
- Import
- import.py
- '''
- # imports the 'math' module
- import math
- # imports the 'sqrt' function from the 'math' module
- from math import sqrt
- # PI constant
- print math.pi
- # returns the square root of a number
- print sqrt(9)
- '''
- on console
- 3.14159265359
- 3.0
- Functions
- functions.py
- '''
- # function
- def addition(a, b):
- return a + b
- print addition(2, 3)
- '''
- on console
- 5
- Math functions
- math_functions.py
- '''
- import math
- # Euler's constant
- print 'math.e'
- print math.e
- # PI constant
- print '\nmath.pi'
- print math.pi
- # return the absolute value of a number
- print '\nmath.fabs(-5)'
- print math.fabs(-5)
- # exponentiation
- print '\nmath.pow(2, 3)'
- print math.pow(2, 3)
- # returns the square root of a number
- print '\nmath.sqrt(9)'
- print math.sqrt(9)
- # converts radians to degrees
- print '\nmath.degrees(math.pi)'
- print math.degrees(math.pi)
- # converts degrees to radians
- print '\nmath.radians(180)'
- print math.radians(180)
- # returns the trigonometric sine of an angle
- print '\nmath.sin(math.radians(90))'
- print math.sin(math.radians(90))
- # returns the trigonometric cosine of an angle
- print '\nmath.cos(math.radians(0))'
- print math.cos(math.radians(0))
- # returns the trigonometric tangent of an angle
- print '\nmath.tan(math.radians(0))'
- print math.tan(math.radians(0))
- # returns the factorial of a number
- print '\nmath.factorial(10)'
- print math.factorial(10)
- # modulus operator (returns a remainder of a division)
- print '\nmath.fmod(3, 2)'
- print math.fmod(3, 2)
- # returns the total sum of all values and avoids loss of precision
- print '\nmath.fsum([93, 86, 38, 23, 46, 32])'
- print math.fsum([93, 86, 38, 23, 46, 32])
- '''
- on console
- math.e
- 2.71828182846
- math.pi
- 3.14159265359
- math.fabs(-5)
- 5.0
- math.pow(2, 3)
- 8.0
- math.sqrt(9)
- 3.0
- math.degrees(math.pi)
- 180.0
- math.radians(180)
- 3.14159265359
- math.sin(math.radians(90))
- 1.0
- math.cos(math.radians(0))
- 1.0
- math.tan(math.radians(0))
- 0.0
- math.factorial(10)
- 3628800
- math.fmod(3, 2)
- 1.0
- math.fsum([93, 86, 38, 23, 46, 32])
- 318.0
- if
- In an if statement, action is executed if condition is True.
- Flowchart:
- Flowchart if
- Source code:
- if.py
- '''
- # condition
- is_running = True
- if is_running:
- # if condition is True, executes action
- print u'Running...'
- '''
- on console
- Running...
- if-else
- In an if-else statement, action 1 is executed if condition is True, otherwise action 2 is executed.
- Flowchart:
- Flowchart if-else
- Source code:
- if_else.py
- '''
- # condition
- is_running = False
- if is_running:
- # if condition is True, executes action 1
- print u'Running...'
- else:
- # if condition is False, executes action 2
- print u'Not running'
- '''
- on console
- Not running
- if-elif
- In an if-elif statement, action n is executed if any condition n is True, where n is the number of nested conditions.
- Flowchart:
- Flowchart if-elif
- Source code:
- if_elif.py
- '''
- number = 2
- # condition 1
- if number == 1:
- # if condition 1 is True, executes action 1
- print u'One'
- # if condition 1 is False, condition 2 is checked
- elif number == 2:
- # if condition 2 is True, executes action 2
- print u'Two'
- # if condition 2 is False, condition 3 is checked
- elif number == 3:
- # if condition 3 is True, executes action 3
- print u'Three'
- '''
- on console
- Two
- if-elif-else
- 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.
- Flowchart:
- Flowchart if-elif-else
- Source code:
- if_elif_else.py
- '''
- number_1 = 2
- number_2 = 3
- # condition 1
- if number_1 == number_2:
- # if condition 1 is True, executes action 1
- print unicode(number_1) + u' is equal to ' + unicode(number_2)
- # if condition 1 is False, condition 2 is checked
- elif number_1 > number_2:
- # if condition 2 is True, executes action 2
- print unicode(number_1) + u' is greater than ' + unicode(number_2)
- else:
- # if no condition is True, executes action 3
- print unicode(number_1) + u' is less than ' + unicode(number_2)
- '''
- on console
- 2 is less than 3
- for
- for.py
- '''
- print 'example #1'
- for i in xrange(5):
- print i
- print '\nexample #2'
- for i in xrange(1, 5):
- print i
- print '\nexample #3'
- for i in xrange(1, 5, 2):
- print i
- print '\nexample #4'
- for i in xrange(5, 0, -1):
- print i
- print '\nexample #5'
- for i in [1, 2, 3, 2, 1]:
- print i
- '''
- on console
- example #1
- 0
- 1
- 2
- 3
- 4
- example #2
- 1
- 2
- 3
- 4
- example #3
- 1
- 3
- example #4
- 5
- 4
- 3
- 2
- 1
- example #5
- 1
- 2
- 3
- 2
- 1
- for-else
- for_else.py
- '''
- def find_character(ch, string):
- """
- prints the index within this string of the first occurrence of the specified character, else prints a message
- that the specified character has not been found
- """
- for index, character in enumerate(string):
- if character == ch:
- print '"{}" (index: {})'.format(ch, index)
- break
- else:
- print '"{}" has not been found'.format(ch)
- message = 'Hello World!'
- find_character('o', message)
- find_character('r', message)
- find_character('z', message)
- '''
- on console
- "o" (index: 4)
- "r" (index: 8)
- "z" has not been found
- while
- while repeats the statements inside its block while its condition is True.
- while.py
- '''
- # initializes the variable 'i'
- i = 0
- # the condition should be 'False' at some point, otherwise it will produce an infinite loop
- while i < 5:
- # prints the variable 'i' on the console
- print i
- # increases by 1 the value of the variable 'i'
- i += 1
- '''
- on console
- 0
- 1
- 2
- 3
- 4
- Recursion
- recursion.py
- '''
- def factorial(n): # without optimization
- if n == 0:
- return 1
- return n * factorial(n - 1) # recursion
- print factorial(10)
- '''
- on console
- 3628800
- Strings
- strings.py
- '''
- message = 'Hello World!'
- print message
- message = "'Hello' World!"
- print message
- message = '"Hello" World!'
- print message
- message = """single quote (') and double quote (")"""
- print message
- message = '''single quote (') and double quote (")'''
- print message
- '''
- on console
- Hello World!
- 'Hello' World!
- "Hello" World!
- single quote (') and double quote (")
- single quote (') and double quote (")
- String format
- string_format.py
- '''
- import datetime
- print '{} {}'.format('Hello', 'World!')
- # arguments by position
- print '{1} {0}'.format('Hello', 'World!')
- print '{0} {1} {0} {1}'.format('Hello', 'World!')
- # arguments by name
- print '{x}, {y}'.format(x='2', y='4')
- # decimal hexadecimal octal binary
- print '{0:d} {0:x} {0:o} {0:b}'.format(10)
- print '{0:d} {0:#x} {0:#o} {0:#b}'.format(10)
- # leading zeros
- print '{:04d}'.format(1)
- # thousand separator
- print '{:,}'.format(10000)
- # percentage
- print '{:.1%}'.format(.5)
- # datetime
- print '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime(2000, 1, 15, 13, 10, 20))
- # sign
- print '{:+d}, {:+d}'.format(1, -1)
- print '{: d}, {: d}'.format(1, -1)
- print '{:-d}, {:-d}'.format(1, -1)
- print '{:d}, {:d}'.format(1, -1)
- '''
- on console
- Hello World!
- World! Hello
- Hello World! Hello World!
- 2, 4
- 10 a 12 1010
- 10 0xa 0o12 0b1010
- 10,000
- 50.0%
- 2000-01-15 13:10:20
- +1, -1
- 1, -1
- 1, -1
- 1, -1
- String items
- string_items.py
- '''
- message = 'Hello World!'
- print message
- # first character
- print message[0]
- # second character
- print message[1]
- # last character
- print message[-1]
- # second to last character
- print message[-2]
- # a range of characters
- print message[2:5]
- '''
- on console
- Hello World!
- H
- e
- !
- d
- llo
- String operations
- string_operations.py
- '''
- # string concatenation
- print 'Hello' + ' World!'
- # repeats the string five times
- print 'Hello World! ' * 5
- message = 'Hello World!'
- print message
- # string length
- print len(message)
- # string slices (returns a substring of the original string)
- print message[1:8]
- print message[:8]
- print message[1:]
- # string comparison
- if message == 'Hello World!':
- print 'the message is: Hello World!'
- # substring of a string
- if 'Hello' in message:
- print "the message contains the word 'Hello'"
- # prints all characters
- for ch in message:
- print ch
- '''
- on console
- Hello World!
- Hello World! Hello World! Hello World! Hello World! Hello World!
- Hello World!
- 12
- ello Wo
- Hello Wo
- ello World!
- the message is: Hello World!
- the message contains the word 'Hello'
- H
- e
- l
- l
- o
- W
- o
- r
- l
- d
- !
- String methods
- string_methods.py
- '''
- message = 'Hello World!'
- print message
- # only the first character in uppercase
- print message.capitalize()
- # number of occurrences
- print message.count('o')
- # finds substring and returns the index of their first occurrence
- print message.find('Hello')
- # is this a digit?
- print message.isdigit()
- # is this in lowercase?
- print message.islower()
- # is this in uppercase?
- print message.isupper()
- # inserts ',' between characters
- print ','.join(message)
- # to lowercase
- print message.lower()
- # to uppercase
- print message.upper()
- # splits on the specified character
- print message.split(' ')
- message = ' Hello World! '
- print message
- # removes whitespaces on the left
- print message.lstrip()
- # removes whitespaces on the right
- print message.rstrip()
- '''
- on console
- Hello World!
- Hello world!
- 2
- 0
- False
- False
- False
- H,e,l,l,o, ,W,o,r,l,d,!
- hello world!
- HELLO WORLD!
- ['Hello', 'World!']
- Hello World!
- Hello World!
- Hello World!
- String constants
- string_constants.py
- '''
- import string
- # locale-dependent
- print string.lowercase
- print string.uppercase
- print string.letters
- # not locale-dependent
- print string.ascii_lowercase
- print string.ascii_uppercase
- print string.ascii_letters
- print string.digits
- print string.hexdigits
- print string.octdigits
- print string.punctuation
- print repr(string.whitespace) # \x0b == \v, \x0c == \f
- print repr(string.printable)
- '''
- on console
- abcdefghijklmnopqrstuvwxyz
- ABCDEFGHIJKLMNOPQRSTUVWXYZ
- abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
- abcdefghijklmnopqrstuvwxyz
- ABCDEFGHIJKLMNOPQRSTUVWXYZ
- abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
- 0123456789
- 0123456789abcdefABCDEF
- 01234567
- !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
- '\t\n\x0b\x0c\r '
- '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
- Tuples
- 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.
- tuples.py
- '''
- # creates a tuple of integers and prints it on the console
- print (1, 2, 3, 4)
- # creates a tuple of strings and prints it on the console
- print ('hello', 'world')
- # crea un tuple con diferentes tipos de datosy lo imprime en la consola
- print (1, 'hello', 2, 3, 'world', 4)
- # creates nested tuples and prints them on the console
- print (('a', 'e', 'i', 'o', 'u'), (1, 2, 3, 4, 5))
- # creates a tuple with a single element and prints it on the console
- print (1,)
- # creates an empty tuple and prints it on the console
- print ()
- '''
- on console
- (1, 2, 3, 4)
- ('hello', 'world')
- (1, 'hello', 2, 3, 'world', 4)
- (('a', 'e', 'i', 'o', 'u'), (1, 2, 3, 4, 5))
- (1,)
- ()
- Tuple items
- 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.
- tuple_items.py
- '''
- # creates a tuple of integer
- numbers = (0, 1, 2, 3, 4, 5, 6)
- # prints the tuple on the console
- print numbers
- # prints the first item on the console
- print numbers[0]
- # prints the second item on the console
- print numbers[1]
- # prints the last item on the console
- print numbers[-1]
- # prints the second to last item on the console
- print numbers[-2]
- # prints the range of elements every two spaces on the console
- print numbers[::2]
- # prints the range of items [2, 5) on the console
- print numbers[2:5]
- # prints the range of elements (2, 5] in reverse order on the console
- print numbers[5:2:-1]
- '''
- on console
- (0, 1, 2, 3, 4, 5, 6)
- 0
- 1
- 6
- 5
- (0, 2, 4, 6)
- (2, 3, 4)
- (5, 4, 3)
- Tuple items Tuple items Tuple items
- Lists
- lists.py
- '''
- # list of integers
- print [1, 2, 3, 4]
- # list of strings
- print ['hello', 'world']
- # list with different types
- print [1, 'hello', 2, 3, 'world', 4]
- # nested lists
- print [1, [2, 3, 4]]
- # list without items
- print []
- '''
- on console
- [1, 2, 3, 4]
- ['hello', 'world']
- [1, 'hello', 2, 3, 'world', 4]
- [1, [2, 3, 4]]
- []
- List items
- list_items.py
- '''
- numbers = [1, 2, 3, 4, 5, 6]
- print numbers
- # first item
- print numbers[0]
- # second item
- print numbers[1]
- # last item
- print numbers[-1]
- # second to last item
- print numbers[-2]
- # a range of items
- print numbers[2:5]
- '''
- on console
- [1, 2, 3, 4, 5, 6]
- 1
- 2
- 6
- 5
- [3, 4, 5]
- List operations
- list_operations.py
- '''
- numbers = [-1, 0, 1, 2, 3]
- print numbers
- # list length
- print len(numbers)
- # concatenation
- numbers += [4, 5, 6, 7]
- print numbers
- # cloning lists (makes a copy of the original list)
- clone = numbers[:]
- print clone
- # removes the first item
- del numbers[0]
- print numbers
- # removes the last item
- del numbers[-1]
- print numbers
- # removes items every two steps
- del numbers[1:len(numbers):2]
- print numbers
- # removes all items
- numbers[:] = []
- print numbers
- '''
- on console
- [-1, 0, 1, 2, 3]
- 5
- [-1, 0, 1, 2, 3, 4, 5, 6, 7]
- [-1, 0, 1, 2, 3, 4, 5, 6, 7]
- [0, 1, 2, 3, 4, 5, 6, 7]
- [0, 1, 2, 3, 4, 5, 6]
- [0, 2, 4, 6]
- []
- List methods
- list_methods.py
- '''
- numbers = [0, 1, 2, 3, 4]
- print numbers
- # appends an item to the end
- numbers.append(4)
- print numbers
- # returns the total of occurrences of the specified item
- print numbers.count(4)
- # returns the index of the first occurrence of the specified item
- print numbers.index(4)
- # removes the first item and returns their value
- print numbers.pop(0)
- # removes the last item and returns their value
- print numbers.pop(-1)
- # removes the first occurrence of the specified item
- numbers.remove(3)
- print numbers
- # inserts an item 'insert(position, item)'
- numbers.insert(2, 3)
- print numbers
- # extends the list
- numbers.extend([5, 6, 7])
- print numbers
- # reverses the list
- numbers.reverse()
- print numbers
- # sorts the list
- numbers.sort()
- print numbers
- # sorts the list in reverse order
- numbers.sort(reverse=True)
- print numbers
- '''
- on console
- [0, 1, 2, 3, 4]
- [0, 1, 2, 3, 4, 4]
- 2
- 4
- 0
- 4
- [1, 2, 4]
- [1, 2, 3, 4]
- [1, 2, 3, 4, 5, 6, 7]
- [7, 6, 5, 4, 3, 2, 1]
- [1, 2, 3, 4, 5, 6, 7]
- [7, 6, 5, 4, 3, 2, 1]
- List conversion
- list_conversion.py
- '''
- # string conversion
- print list('Hello World!')
- # dictionary conversion
- print list({1: 'one', 2: 'two'})
- # tuple conversion
- print list((1, 2))
- # set conversion
- print list({1, 2})
- # frozenset conversion
- print list(frozenset([1, 2]))
- '''
- on console
- ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
- [1, 2]
- [1, 2]
- [1, 2]
- [1, 2]
- List comprehensions
- 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.
- list_comprehensions.py
- '''
- # list comprehensions
- # creates a list
- numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- # prints the created list
- print numbers
- # -- performs operations on each element of the list created before --
- # squares the number of each number in the list, returns them in a new list and prints the new list
- print [x ** 2 for x in numbers]
- # -- performs operations on each number in the list created before that satisfies a certain condition --
- # squares only the even numbers in the list, returns them in a new list and print the new list
- print [x ** 2 for x in numbers if x % 2 == 0]
- # -- creates a new list --
- # prints the squares of the numbers in the range [1, 11)
- print [x ** 2 for x in xrange(1, 11)]
- # -- creates a new nested list of 4x2 (row x column) --
- # Note: expressions are execute from left to right
- rows = 4 # rows
- cols = 2 # columns
- print [[x + y * cols for x in xrange(cols)] for y in xrange(rows)]
- '''
- on console
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
- [4, 16, 36, 64, 100]
- [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
- [[0, 1], [2, 3], [4, 5], [6, 7]]
- Stacks
- stacks.py
- '''
- # stacks: last-in, first-out
- stack = [0, 1, 2, 3, 4]
- print stack
- stack.append(5)
- print stack
- print stack.pop()
- print stack.pop()
- print stack
- '''
- on console
- [0, 1, 2, 3, 4]
- [0, 1, 2, 3, 4, 5]
- 5
- 4
- [0, 1, 2, 3]
- Queues
- queues.py
- '''
- from Queue import Queue, LifoQueue, PriorityQueue
- # FIFO queue example (FIFO: first-in, first-out)
- print 'FIFO queue example'
- fifo_queue = Queue()
- fifo_queue.put(1)
- fifo_queue.put(5)
- fifo_queue.put(3)
- while not fifo_queue.empty():
- number = fifo_queue.get()
- print number
- fifo_queue.task_done()
- fifo_queue.join()
- # LIFO queue example (LIFO: last-in, first-out)
- print '\nLIFO queue example'
- lifo_queue = LifoQueue()
- lifo_queue.put(1)
- lifo_queue.put(5)
- lifo_queue.put(3)
- while not lifo_queue.empty():
- number = lifo_queue.get()
- print number
- lifo_queue.task_done()
- lifo_queue.join()
- # Priority queue example (the lowest valued entries are retrieved first)
- print '\nPriority queue example'
- priority_queue = PriorityQueue()
- priority_queue.put(1)
- priority_queue.put(5)
- priority_queue.put(3)
- while not priority_queue.empty():
- number = priority_queue.get()
- print number
- priority_queue.task_done()
- priority_queue.join()
- '''
- on console
- FIFO queue example
- 1
- 5
- 3
- LIFO queue example
- 3
- 5
- 1
- Priority queue example
- 1
- 3
- 5
- Deque
- deque.py
- '''
- from collections import deque
- # deque: a double-ended queue
- d = deque([3, 4])
- print d
- # appends an item to the right side
- d.append(5)
- print d
- # appends an item to the left side
- d.appendleft(2)
- print d
- # removes and returns one item from the right
- print d.pop()
- # removes and returns one item from the left
- print d.popleft()
- print d
- # returns the total of occurrences of the specified item
- print d.count(3)
- # extends the right side
- d.extend([5, 6, 7])
- print d
- # extends the left side
- d.extendleft([2, 1, 0])
- print d
- # reversed the elements in-place
- d.reverse()
- print d
- # removes all element
- d.clear()
- print d
- # returns the maximum size, None if unbounded
- print d.maxlen
- '''
- on console
- deque([3, 4])
- deque([3, 4, 5])
- deque([2, 3, 4, 5])
- 5
- 2
- deque([3, 4])
- 1
- deque([3, 4, 5, 6, 7])
- deque([0, 1, 2, 3, 4, 5, 6, 7])
- deque([7, 6, 5, 4, 3, 2, 1, 0])
- deque([])
- None
- Dictionaries
- dictionaries.py
- '''
- # empty dictionary
- empty = {}
- print empty
- # dictionary with a list of key-value pairs
- numbers = {1: 'one', 2: 'two'}
- print numbers
- # dictionary with different types
- print {1: 'number', 'a': 'letter'}
- # nested dictionaries
- print {'odd numbers': {1: 'one', 3: 'three', 5: 'five'}, 'even numbers': {2: 'two', 4: 'four', 6: 'six'}}
- '''
- on console
- {}
- {1: 'one', 2: 'two'}
- {'a': 'letter', 1: 'number'}
- {'even numbers': {2: 'two', 4: 'four', 6: 'six'}, 'odd numbers': {1: 'one', 3: 'three', 5: 'five'}}
- Dictionary items
- dictionary_items.py
- '''
- numbers = {1: 'one', 2: 'two', 3: 'three'}
- print numbers
- # returns a value if exists in the dictionary, None otherwise
- print numbers.get(1)
- print numbers.get(4)
- # checks if a key exists in the dictionary
- print 1 in numbers
- print 4 in numbers
- # returns all items in a list
- print numbers.items()
- # returns all keys in a list
- print numbers.keys()
- # returns all values in a list
- print numbers.values()
- '''
- on console
- {1: 'one', 2: 'two', 3: 'three'}
- one
- None
- True
- False
- [(1, 'one'), (2, 'two'), (3, 'three')]
- [1, 2, 3]
- ['one', 'two', 'three']
- Dictionary operations
- dictionary_operations.py
- '''
- numbers = {1: 'one', 2: 'two', 3: 'three'}
- print numbers
- # dictionary length
- print len(numbers)
- # adds an item
- numbers[4] = 'four'
- print numbers
- # changes an item
- numbers[4] = 'FOUR'
- print numbers
- # deletes an item
- del numbers[3]
- print numbers
- # removes the key and returns their value
- print numbers.pop(2)
- print numbers
- # removes all items
- numbers.clear()
- print numbers
- '''
- on console
- {1: 'one', 2: 'two', 3: 'three'}
- 3
- {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
- {1: 'one', 2: 'two', 3: 'three', 4: 'FOUR'}
- {1: 'one', 2: 'two', 4: 'FOUR'}
- two
- {1: 'one', 4: 'FOUR'}
- {}
- Dictionary iteration
- dictionary_iteration.py
- '''
- numbers = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
- print 'keys (returns a list)'
- for key in numbers.keys():
- print key
- print '\nvalues (returns a list)'
- for value in numbers.values():
- print value
- print '\nitems (returns a list)'
- for key, value in numbers.items():
- print key, value
- print '\niterkeys (returns an iterator)'
- for key in numbers.iterkeys():
- print key
- print '\nitervalues (returns an iterator)'
- for value in numbers.itervalues():
- print value
- print '\niteritems (returns an iterator)'
- for key, value in numbers.iteritems():
- print key, value
- '''
- on console
- keys (returns a list)
- 1
- 2
- 3
- 4
- values (returns a list)
- one
- two
- three
- four
- items (returns a list)
- 1 one
- 2 two
- 3 three
- 4 four
- iterkeys (returns an iterator)
- 1
- 2
- 3
- 4
- itervalues (returns an iterator)
- one
- two
- three
- four
- iteritems (returns an iterator)
- 1 one
- 2 two
- 3 three
- 4 four
- Slices
- 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.
- slices.py
- '''
- # creates a list
- numbers = [0, 1, 2, 3, 4, 5, 6, 7]
- # prints the list items in the index range [2, 5)
- print numbers[2:5]
- # prints the list items in the index range [0, 4)
- print numbers[:4]
- # prints the list items in the index range [5, len(numbers))
- print numbers[5:]
- # prints the last 4 items in the list
- print numbers[-4:]
- # slices do not produce exceptions of 'list index out of range'
- print numbers[:10]
- print numbers[-10:]
- # copies all items of the 'numbers' list
- other_numbers = numbers[:]
- print other_numbers
- # 'other_numbers' and 'numbers' are two different lists
- print other_numbers is numbers
- # slices can be used in assignments
- numbers[2:] = [2]
- print numbers
- # slices can operate on tuples
- numbers_in_tuple = (0, 1, 2, 3, 4, 5, 6, 7)
- print numbers_in_tuple[2:5]
- # slices can operate on strings
- numbers_in_string = '01234567'
- print numbers_in_string[2:5]
- # slices can operate on unicode strings
- numbers_in_unicode_string = u'01234567'
- print numbers_in_unicode_string[2:5]
- # slices can not operate on sets
- try:
- numbers_in_set = {0, 1, 2, 3, 4, 5, 6, 7}
- print numbers_in_set[2:5]
- except TypeError:
- print 'TypeError exception: slices can not operate on sets.'
- '''
- on console
- [2, 3, 4]
- [0, 1, 2, 3]
- [5, 6, 7]
- [4, 5, 6, 7]
- [0, 1, 2, 3, 4, 5, 6, 7]
- [0, 1, 2, 3, 4, 5, 6, 7]
- [0, 1, 2, 3, 4, 5, 6, 7]
- False
- [0, 1, 2]
- (2, 3, 4)
- 234
- 234
- TypeError exception: slices can not operate on sets.
- 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.
- When slices are used in assignments, it replaces the values in the original list in the specified range.
- Classes
- classes.py
- '''
- # circle class
- class Circle:
- def __init__(self, (x, y), radius):
- self.x = x
- self.y = y
- self.radius = radius
- def diameter(self):
- return self.radius * 2
- circle = Circle((0, 0), 3)
- print circle.diameter()
- circle.radius = 4
- print circle.diameter()
- '''
- on console
- 6
- 8
- Properties
- properties.py
- '''
- class Circle(object): # inherits your class from object to use @property decorator
- def __init__(self, (x, y), radius):
- self.x = x
- self.y = y
- self.radius = radius
- @property
- def radius(self):
- return self.__radius
- # radius >= 0
- @radius.setter
- def radius(self, value):
- if value < 0:
- self.__radius = 0
- else:
- self.__radius = value
- def diameter(self):
- return self.radius * 2
- circle = Circle((0, 0), 3)
- print circle.diameter()
- circle.radius = -4
- print circle.diameter()
- '''
- on console
- 6
- 0
- Inheritance
- inheritance.py
- '''
- # point class
- class Point:
- def __init__(self, (x, y)):
- self.x = x
- self.y = y
- # inheritance
- # circle class
- class Circle(Point):
- def __init__(self, (x, y), radius):
- Point.__init__(self, (x, y))
- self.radius = radius
- circle = Circle((0, 0), 3)
- print circle.x
- circle.x = 4
- print circle.x
- '''
- on console
- 0
- 4
- Polymorphism
- polymorphism.py
- '''
- # polygon class
- class Polygon:
- def __init__(self, name):
- self.name = name
- def number_of_sides(self):
- raise NotImplementedError
- # triangle class
- class Triangle(Polygon):
- def number_of_sides(self):
- return 3
- # square class
- class Square(Polygon):
- def number_of_sides(self):
- return 4
- # polymorphism
- polygons = [Triangle('triangle'), Square('square')]
- for p in polygons:
- print 'A {} has {} sides'.format(p.name, p.number_of_sides())
- '''
- on console
- A triangle has 3 sides
- A square has 4 sides
- Truth value testing
- truth_value_testing.py
- '''
- # this values are considered false:
- if None:
- print 'this will not be printed'
- if False:
- print 'this will not be printed'
- if 0:
- print 'this will not be printed'
- if 0L:
- print 'this will not be printed'
- if 0.0:
- print 'this will not be printed'
- if 0J:
- print 'this will not be printed'
- if '':
- print 'this will not be printed'
- if ():
- print 'this will not be printed'
- if []:
- print 'this will not be printed'
- if {}:
- print 'this will not be printed'
- '''
- on console
- Escape sequences
- escape_sequences.py
- '''
- print 'Horizontal tab:', '\t'
- print 'Vertical tab:', '\v'
- print 'Backspace:', '\b'
- print 'New line:', '\n'
- print 'Carriage return:', '\r'
- print 'Form feed:', '\f'
- print 'Single quote', '\''
- print 'Double quote:', '\"'
- print 'Backslash:', '\\'
- print 'Bell:', '\a'
- '''
- on console
- Horizontal tab:
- Vertical tab:
- Backspace:
- New line:
- Carriage return:
- Form feed:
- Single quote '
- Double quote: "
- Backslash: \
- Bell:
- Named arguments
- named_arguments.py
- '''
- def numbers(minimum=0, maximum=10):
- return range(minimum, maximum + 1)
- print numbers()
- print numbers(minimum=5)
- print numbers(maximum=5)
- '''
- on console
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- [5, 6, 7, 8, 9, 10]
- [0, 1, 2, 3, 4, 5]
- Lambda functions
- 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.
- lambda_functions.py
- '''
- # -- a lambda function that takes one argument --
- # squares a number
- square = lambda x: x ** 2
- print square(3)
- # -- a lambda function that takes two arguments --
- # adds two numbers
- sum_ = lambda x, y: x + y
- print sum_(2, 3)
- # -- a lambda function used in 'sorted()' --
- # sorts strings by length from least to greatest
- print sorted(['Python', 'Ruby', 'Perl'], cmp=lambda x, y: cmp(len(x), len(y)))
- # -- a lambda function used in 'filter()' --
- # filters the even numbers
- print filter(lambda n: n % 2 == 0, range(10))
- '''
- on console
- 9
- 5
- ['Ruby', 'Perl', 'Python']
- [0, 2, 4, 6, 8]
- PEP 8 does not recommend using lambda functions in assignments, instead define functions using the def statement. These examples are for demonstration purposes.
- Random numbers
- random_numbers.py
- '''
- import random
- import string
- # returns a random floating point number in the range [0.0, 1.0)
- print random.random()
- # returns a random floating point number in the range [min, max]
- print random.uniform(50, 100)
- # returns a random integer number in the range [a, b]
- print random.randint(50, 100)
- # random.randrange(a, b, c) returns a random integer number in the range [a, b) every c steps
- print random.randrange(0, 100, 3)
- # shuffles a list
- my_list = range(0, 10)
- print my_list
- random.shuffle(my_list)
- print my_list
- # random choices
- print random.choice(my_list)
- print random.choice(string.ascii_lowercase)
- # random seed
- random.seed(54321) # Default is sys' time or urand
- my_list = range(0, 10)
- random.shuffle(my_list)
- print my_list
- random.seed(54321)
- my_list = range(0, 10)
- random.shuffle(my_list)
- print my_list
- '''
- on console
- 0.217586684321
- 76.7631380262
- 98
- 69
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- [5, 6, 8, 3, 2, 0, 7, 1, 9, 4]
- 5
- a
- [9, 5, 2, 6, 0, 3, 7, 1, 8, 4]
- [9, 5, 2, 6, 0, 3, 7, 1, 8, 4]
- Exceptions
- exceptions.py
- '''
- def division(a, b):
- try:
- a / b
- except ZeroDivisionError:
- print 'zero division error'
- division(1, 0)
- '''
- on console
- zero division error
- Raise
- raise.py
- '''
- '''
- def division(a, b):
- if b == 0:
- # raises a built-in exception
- raise ZeroDivisionError
- return a / b
- division(1, 0)
- '''
- '''
- on console
- Traceback (most recent call last):
- File "raise.py", line 9, in <module>
- division(1, 0)
- File "raise.py", line 4, in division
- raise ZeroDivisionError
- ZeroDivisionError
- Keyboard input
- keyboard_input.py
- '''
- name = raw_input('What is your name?\n')
- print 'Hello', name
- '''
- on console
- What is your name?
- Get documentation
- 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.
- Source code:
- get_documentation.py
- '''
- # '__doc__' returns the existing documentation of any module, function, class or method
- print int.__doc__
- '''
- on console
- int(x=0) -> int or long
- int(x, base=10) -> int or long
- Convert a number or string to an integer, or return 0 if no arguments
- are given. If x is floating point, the conversion truncates towards zero.
- If x is outside the integer range, the function returns a long instead.
- If x is not a number or if base is given, then x must be a string or
- Unicode object representing an integer literal in the given base. The
- literal can be preceded by '+' or '-' and be surrounded by whitespace.
- The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
- interpret the base from the string as an integer literal.
- >>> int('0b100', base=0)
- 4
- Own documentation
- own_documentation.py
- '''
- class Circle:
- """ Represents a circle """
- def __init__(self, (x, y), radius):
- """ Constructs a circle """
- self._x = x
- self._y = y
- self._radius = radius
- def diameter(self):
- """ Returns the diameter """
- return self._radius * 2
- print Circle.__doc__
- print Circle.__init__.__doc__
- print Circle.diameter.__doc__
- '''
- on console
- Represents a circle
- Constructs a circle
- Returns the diameter
- Unit testing
- unit_testing.py
- '''
- def wrong_diameter(radius):
- """
- >>> wrong_diameter(2)
- 4
- """
- return radius * 3
- def right_diameter(radius):
- """
- >>> right_diameter(2)
- 4
- """
- return radius * 2
- if __name__ == '__main__':
- import doctest
- doctest.testmod()
- '''
- on console
- **********************************************************************
- File "unit_testing.py", line 3, in __main__.wrong_diameter
- Failed example:
- wrong_diameter(2)
- Expected:
- 4
- Got:
- 6
- **********************************************************************
- 1 items had failures:
- 1 of 1 in __main__.wrong_diameter
- ***Test Failed*** 1 failures.
- JSON string reader
- json_string_reader.py
- '''
- import json
- from pprint import pprint
- # json.loads, not json.load
- data = json.loads(
- '{"string":"this is a string","integer_number":1,"real_number":1.2,"boolean":true,"null":null,"array":[1,2],'
- '"object":{"1":"one","2":"two"}}')
- pprint(data) # pretty-print
- '''
- on console
- {u'array': [1, 2],
- u'boolean': True,
- u'integer_number': 1,
- u'null': None,
- u'object': {u'1': u'one', u'2': u'two'},
- u'real_number': 1.2,
- u'string': u'this is a string'}
- JSON file reader
- json_reader.json
- {
- "string": "this is a string",
- "integer number": 1,
- "real number": 1.2,
- "boolean": true,
- "null": null,
- "array": [
- 1,
- 2
- ],
- "object": {
- "1": "one",
- "2": "two"
- }
- }
- json_file_reader.py
- '''
- '''
- import json
- from pprint import pprint
- with open('json_reader.json') as json_file:
- # json.load, not json.loads
- data = json.load(json_file) # returns a dictionary or a list
- pprint(data) # pretty-print
- '''
- '''
- on console
- {u'array': [1, 2],
- u'boolean': True,
- u'integer number': 1,
- u'null': None,
- u'object': {u'1': u'one', u'2': u'two'},
- u'real number': 1.2,
- u'string': u'this is a string'}
- JSON file writer
- json_writer.py
- '''
- '''
- import json
- # data to save
- data = {
- "string": "text",
- "integer number": 1,
- "real number": 1.2,
- "boolean": True,
- "null": None,
- "array": [1, 2],
- "object": {"1": "one", "2": "two"}
- }
- # saves the data in a JSON file
- with open('destination.json', 'w') as f:
- # Note: use the json.dump() method, not the json.dumps() method
- json.dump(data, f, sort_keys=True, indent=2)
- '''
- '''
- destination.json
- {
- "array": [
- 1,
- 2
- ],
- "boolean": true,
- "integer number": 1,
- "null": null,
- "object": {
- "1": "one",
- "2": "two"
- },
- "real number": 1.2,
- "string": "text"
- }
- JSON file helper
- json_helper.py
- '''
- '''
- from collections import OrderedDict
- import json
- class JSONHelper:
- """
- Reads and saves JSON files.
- """
- @staticmethod
- def open(path, encoding='utf-8', preserve_order=True):
- """
- Opens a JSON file and returns a list or a dict.
- """
- object_pairs_hook = None
- # preserve order of attributes?
- if preserve_order:
- object_pairs_hook = OrderedDict
- # opens the JSON file
- with open(path) as f:
- return json.load(f, encoding=encoding, object_pairs_hook=object_pairs_hook)
- @staticmethod
- def save(path, data, encoding='utf-8', indentation=2, sort_keys=False, separators=(',', ': ')):
- """
- Saves the data in a JSON file.
- The data can be a list or a dictionary (dict).
- """
- # saves the JSON file
- with open(path, 'w') as f:
- json.dump(data, f, encoding=encoding, indent=indentation, sort_keys=sort_keys,
- separators=separators)
- def main():
- # gets the data from a JSON file
- data = JSONHelper.open('source.json')
- # saves the data in another JSON file
- JSONHelper.save('destination.json', data)
- if __name__ == '__main__':
- main()
- '''
- '''
- source.json
- {
- "string": "text",
- "integer number": 1,
- "real number": 1.2,
- "boolean": true,
- "null": null,
- "array": [
- 1,
- 2
- ],
- "object": {
- "1": "one",
- "2": "two"
- }
- }
- destination.json
- {
- "string": "text",
- "integer number": 1,
- "real number": 1.2,
- "boolean": true,
- "null": null,
- "array": [
- 1,
- 2
- ],
- "object": {
- "1": "one",
- "2": "two"
- }
- }
- Hash functions
- hash_functions.py
- '''
- import hashlib
- message = 'Hello World!'
- # MD5
- print hashlib.md5(message).hexdigest()
- # SHA-1
- print hashlib.sha1(message).hexdigest()
- # SHA-224
- print hashlib.sha224(message).hexdigest()
- # SHA-256
- print hashlib.sha256(message).hexdigest()
- # SHA-384
- print hashlib.sha384(message).hexdigest()
- # SHA-512
- print hashlib.sha512(message).hexdigest()
- '''
- on console
- ed076287532e86365e841e92bfc50d8c
- 2ef7bde608ce5404e97d5f042f95f89f1c232871
- 4575bb4ec129df6380cedde6d71217fe0536f8ffc4e18bca530a7a1b
- 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069
- bfd76c0ebbd006fee583410547c1887b0292be76d582d96c242d2a792723e3fd6fd061f9d5cfd13b8f961358e6adba4a
- 861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8
- Argument parser
- argument_parser.py
- '''
- import argparse
- import hashlib
- parser = argparse.ArgumentParser(description='Hash functions utility')
- parser.add_argument('-hf', '--hash', help='hash function')
- parser.add_argument('-s', '--string', help='string to hash')
- args = parser.parse_args()
- if args.string:
- if args.hash == 'md5':
- print hashlib.md5(args.string).hexdigest()
- elif args.hash == 'sha1':
- print hashlib.sha1(args.string).hexdigest()
- elif args.hash == 'sha224':
- print hashlib.sha224(args.string).hexdigest()
- elif args.hash == 'sha256':
- print hashlib.sha256(args.string).hexdigest()
- elif args.hash == 'sha384':
- print hashlib.sha384(args.string).hexdigest()
- elif args.hash == 'sha512':
- print hashlib.sha512(args.string).hexdigest()
- else:
- parser.print_help()
- else:
- parser.print_help()
- '''
- on console
- python argument_parser.py
- '''
- '''
- usage: argument_parser.py [-h] [-hf HASH] [-s STRING]
- Hash functions utility
- optional arguments:
- -h, --help show this help message and exit
- -hf HASH, --hash HASH
- hash function
- -s STRING, --string STRING
- string to hash
- python argument_parser.py -s "Hello World!" -hf md5
- '''
- '''
- on console
- ed076287532e86365e841e92bfc50d8c
- Version
- To determine the Python version, type python --version in the command line, or run the following script to see more details about the version.
- version.py
- '''
- import sys
- # prints the Python version in a string
- print sys.version
- print
- # to extract information about the Python version use 'sys.version_info'
- info_version = sys.version_info
- print info_version
- print 'major:', info_version[0]
- print 'minor:', info_version[1]
- print 'micro:', info_version[2]
- print 'release level:', info_version[3]
- print 'serial:', info_version[4]
- '''
- on console
- 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)]
- sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)
- major: 2
- minor: 7
- micro: 13
- release level: final
- serial: 0
- 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).
- sys.version_info is available since version 2.0. sys.version_info components can be accessed by name since version 2.7.
- Keywords
- keywords.py
- '''
- import keyword
- print str(len(keyword.kwlist)) + ' keywords\n'
- for kw in keyword.kwlist:
- print kw
- '''
- on console
- 31 keywords
- and
- as
- assert
- break
- class
- continue
- def
- del
- elif
- else
- except
- exec
- finally
- for
- from
- global
- if
- import
- in
- is
- lambda
- not
- or
- pass
- print
- raise
- return
- try
- while
- with
- yield
- continue
- continue.py
- '''
- # prints only the even numbers
- for i in xrange(10):
- if i % 2 != 0:
- continue
- print i
- '''
- on console
- 0
- 2
- 4
- 6
- 8
- break
- break ends the loop immediately.
- break.py
- '''
- def search_character(character, text):
- """
- Prints the index of the first occurrence of the specified character inside the text, otherwise it does not print anything.
- """
- # walks through every character in the text
- for index, ch in enumerate(text):
- # if the character has been found in the text
- if character == ch:
- # prints on the console the character and its index inside the text
- print '"{}" (index: {})'.format(character, index)
- # ends the loop immediately
- break
- def main():
- # creates a text
- text = 'Hello World!'
- # searches the specified characters inside the text
- search_character(u'o', text)
- search_character(u'n', text)
- search_character(u'z', text)
- if __name__ == '__main__':
- main()
- '''
- on console
- "o" (index: 4)
- "r" (index: 8)
- return
- return allows us to return a value in a function. If return is omitted, the function returns None.
- return.py
- '''
- def find_character(character, text):
- """
- Returns 'True' if the specified character is in the text, if not returns 'False'.
- """
- return character in text
- def main():
- text = 'Hello World!'
- print 'character found:', find_character('o', text)
- print 'character found:', find_character('n', text)
- print 'character found:', find_character('z', text)
- if __name__ == '__main__':
- main()
- '''
- on console
- character found: True
- character found: False
- character found: False
- Built-in functions
- built_in_functions.py
- '''
- # returns the absolute value of a number
- print 'abs(-5)'
- print abs(-5)
- # returns an empty dictionary
- print '\ndict()'
- print dict()
- # returns the memory address of the specified object
- print '\nid(5)'
- print id(5)
- # returns an empty list
- print '\nlist()'
- print list()
- # returns the maximum value
- print '\nmax([93, 86, 38, 23, 46, 32])'
- print max([93, 86, 38, 23, 46, 32])
- # returns the minimum value
- print '\nmin([93, 86, 38, 23, 46, 32])'
- print min([93, 86, 38, 23, 46, 32])
- # returns the ASCII code of the specified character
- print "\nord('a')"
- print ord('a')
- # returns 2 ** 3 (exponentiation)
- print '\npow(2, 3)'
- print pow(2, 3)
- # returns a list of values
- print '\nrange(0, 10)'
- print range(0, 10)
- print 'range(0, 10, 2)'
- print range(0, 10, 2)
- # returns a rounded value
- print '\nprint round(1.234, 2)'
- print round(1.234, 2)
- print 'round(1.235, 2)'
- print round(1.235, 2)
- print 'round(1.245, 2)'
- print round(1.245, 2)
- # returns the total sum of all values
- print '\nsum([93, 86, 38, 23, 46, 32])'
- print sum([93, 86, 38, 23, 46, 32])
- # returns a tuple
- print '\ntuple([1, 2])'
- print tuple([1, 2])
- print "tuple({1: 'One', 2: 'Two'})"
- print tuple({1: 'One', 2: 'Two'})
- '''
- on console
- abs(-5)
- 5
- dict()
- {}
- id(5)
- 5154456
- list()
- []
- max([93, 86, 38, 23, 46, 32])
- 93
- min([93, 86, 38, 23, 46, 32])
- 23
- ord('a')
- 97
- pow(2, 3)
- 8
- range(0, 10)
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- range(0, 10, 2)
- [0, 2, 4, 6, 8]
- print round(1.234, 2)
- 1.23
- round(1.235, 2)
- 1.24
- round(1.245, 2)
- 1.25
- sum([93, 86, 38, 23, 46, 32])
- 318
- tuple([1, 2])
- (1, 2)
- tuple({1: 'One', 2: 'Two'})
- (1, 2)
- type()
- type() returns the data type of the specified object.
- type.py
- '''
- # imports a module for demonstration purposes
- import sys
- # a class for demonstration purposes
- class CustomClass:
- def __init__(self):
- pass
- def custom_method(self):
- pass
- # a function for demonstration purposes
- def custom_function():
- pass
- # a generator for demonstration purposes
- def custom_generator():
- yield 1
- # instance of a class for demonstration purposes
- cc = CustomClass()
- # type() returns the data type of the specified object
- # 'str' type
- print type('string')
- # 'unicode' type
- print type(u'unicode string')
- # 'int' type
- print type(0)
- # 'long' type
- print type(1L)
- # 'float' type
- print type(1.2)
- # 'complex' type
- print type(1.2J)
- # 'bool' type
- print type(True)
- # 'tuple' type
- print type((1, 2))
- # 'list' type
- print type([1, 2])
- # 'set' type
- print type({1, 2})
- # 'frozenset' type
- print type(frozenset([1, 2]))
- # 'dict' type
- print type({1: 'one', 2: 'two'})
- # 'NoneType' type
- print type(None)
- # 'type' type
- print type(type(None))
- # 'classobj' type
- print type(CustomClass)
- # 'function' type
- print type(custom_function)
- # 'function' type
- print type(lambda: None)
- # 'generator' type
- print type(custom_generator())
- # 'module' type
- print type(sys)
- # 'instance' type
- print type(cc)
- # 'instancemethod' type
- print type(cc.custom_method)
- # 'NotImplementedType' type
- print type(NotImplemented)
- '''
- on console
- <type 'str'>
- <type 'unicode'>
- <type 'int'>
- <type 'long'>
- <type 'float'>
- <type 'complex'>
- <type 'bool'>
- <type 'tuple'>
- <type 'list'>
- <type 'set'>
- <type 'frozenset'>
- <type 'dict'>
- <type 'NoneType'>
- <type 'type'>
- <type 'classobj'>
- <type 'function'>
- <type 'function'>
- <type 'generator'>
- <type 'module'>
- <type 'instance'>
- <type 'instancemethod'>
- <type 'NotImplementedType'>
- sorted()
- sorted.py
- '''
- letters = ['a', 'd', 'c', 'b']
- for letter in sorted(letters):
- print letter
- print
- for letter in sorted(letters, reverse=True):
- print letter
- '''
- on console
- a
- b
- c
- d
- d
- c
- b
- a
- reversed()
- 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).
- reversed.py
- '''
- # creates a list of letters
- letters = ['a', 'b', 'c', 'd']
- # prints the object type
- print type(reversed(letters))
- # prints the letters in reverse order
- for letter in reversed(letters):
- # if the 'b' letter is found
- if letter == 'b':
- # stops the loop
- break
- # prints the letter
- print letter
- '''
- on console
- <type 'listreverseiterator'>
- d
- c
- map()
- 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.
- map.py
- '''
- import math
- # user-defined function
- def square(a):
- """
- Returns the square of the specified number.
- """
- return a ** 2
- # 'map()' with a built-in function that takes one argument
- print map(math.factorial, [1, 2, 3, 4])
- # 'map()' with a built-in function that takes two arguments
- print map(math.pow, [2, 2, 2], [1, 2, 3])
- # 'map()' with an anonymous function (lambda) that takes one argument
- print map(lambda x: x ** 2, [1, 2, 3, 4])
- # 'map()' with an anonymous function (lambda) that takes two arguments
- print map(lambda x, y: x + y, [1, 2, 3, 4], [-1, -2, -3, -4])
- # 'map()' with a user-defined function that takes one argument
- print map(square, [1, 2, 3, 4])
- '''
- on console
- [1, 2, 6, 24]
- [2.0, 4.0, 8.0]
- [1, 4, 9, 16]
- [0, 0, 0, 0]
- [1, 4, 9, 16]
- enumerate()
- enumerate.py
- '''
- letters = ['a', 'b', 'c', 'd']
- for index, letter in enumerate(letters):
- print '{}. {}'.format(index + 1, letter)
- '''
- on console
- 1. a
- 2. b
- 3. c
- 4. d
- filter()
- 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.
- 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.
- filter.py
- '''
- # -- definition of functions for demonstration purposes --
- def only_odd_numbers(number):
- """
- Filters the odd numbers. Use with 'filter()'.
- """
- return not number % 2 == 0
- def remove_spaces(character):
- """
- Remove whitespaces. Use with 'filter()'.
- """
- return character != ' '
- def only_ints(data):
- """
- Filters 'int' data types. Use with 'filter()'.
- """
- return type(data) is int
- # 'filter()' with an anonymous function (lambda) that takes a 'list' argument; returns a 'list'
- # prints only the even numbers
- print filter(lambda x: x % 2 == 0, range(10))
- # 'filter()' with a user-defined function that takes a 'list' argument; returns a 'list'
- # prints only the odd numbers
- print filter(only_odd_numbers, range(10))
- # 'filter()' with a user-defined function that takes a 'xrange' argument; returns a 'list'
- # prints only the odd numbers
- print filter(only_odd_numbers, xrange(10))
- # 'filter()' with a user-defined function that takes a 'str' argument; returns a 'str'
- # prints the string without whitespaces
- print filter(remove_spaces, 'a string')
- # 'filter()' with a user-defined function that takes a 'tuple' argument; returns a 'tuple'
- # prints only 'int' data types
- print filter(only_ints, (2, 2.0, 'a', 4))
- # 'filter()' with 'None' in its first parameter
- # removes items that are considered 'False'
- print filter(None, [0, [], (), {}, False, True, 1, '', 'abc'])
- '''
- on console
- [0, 2, 4, 6, 8]
- [1, 3, 5, 7, 9]
- [1, 3, 5, 7, 9]
- astring
- (2, 4)
- [True, 1, 'abc']
- reduce()
- 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.
- reduce.py
- '''
- # user-defined function
- def product(x, y):
- """
- Returns the product of two numbers.
- """
- return x * y
- # creates a list of integers
- numbers = [1, 2, 3, 4]
- # 'reduce()' that takes a lambda function (anonymous function) in its first argument
- # returns the sum of the elements of the 'numbers' list ; it is equivalent to (((1+2)+3)+4)
- print reduce(lambda x, y: x + y, numbers)
- # 'reduce()' that takes a user-defined function in its first argument
- # returns the product of the elements of the 'numbers' list ; it is equivalent to (((1*2)*3)*4)
- print reduce(product, numbers)
- # 'reduce()' that takes an 'xrange' object in its second argument
- # returns the product of the numbers in the range [1, 5); it is equivalent to (((1*2)*3)*4)
- print reduce(product, xrange(1, 5))
- # 'reduce()' with an initial value equal to 10
- # returns the product of the initial value and the items of the 'numbers' list; it is equivalent to (((10*1)*2)*3)*4)
- print reduce(product, numbers, 10)
- '''
- on console
- 10
- 24
- 24
- 240
- zip()
- zip.py
- '''
- letters = ['a', 'b', 'c', 'd']
- numbers = [1, 2, 3, 4]
- # zip (returns a list with tuples)
- for letter, number in zip(letters, numbers):
- print letter, number
- '''
- on console
- a 1
- b 2
- c 3
- d 4
- izip()
- izip.py
- '''
- from itertools import izip
- letters = ['a', 'b', 'c', 'd']
- numbers = [1, 2, 3, 4]
- # izip (returns an iterator with tuples)
- for letter, number in izip(letters, numbers):
- print letter, number
- '''
- on console
- a 1
- b 2
- c 3
- d 4
- Built-in list
- built_in_list.py
- '''
- import __builtin__
- print str(len(dir(__builtin__))) + ' built-in functions and variables\n'
- for name in dir(__builtin__):
- print name
- '''
- on console
- 144 built-in functions and variables
- ArithmeticError
- AssertionError
- AttributeError
- BaseException
- BufferError
- BytesWarning
- DeprecationWarning
- EOFError
- Ellipsis
- EnvironmentError
- Exception
- False
- FloatingPointError
- FutureWarning
- GeneratorExit
- IOError
- ImportError
- ImportWarning
- IndentationError
- IndexError
- KeyError
- KeyboardInterrupt
- LookupError
- MemoryError
- NameError
- None
- NotImplemented
- NotImplementedError
- OSError
- OverflowError
- PendingDeprecationWarning
- ReferenceError
- RuntimeError
- RuntimeWarning
- StandardError
- StopIteration
- SyntaxError
- SyntaxWarning
- SystemError
- SystemExit
- TabError
- True
- TypeError
- UnboundLocalError
- UnicodeDecodeError
- UnicodeEncodeError
- UnicodeError
- UnicodeTranslateError
- UnicodeWarning
- UserWarning
- ValueError
- Warning
- WindowsError
- ZeroDivisionError
- __debug__
- __doc__
- __import__
- __name__
- __package__
- abs
- all
- any
- apply
- basestring
- bin
- bool
- buffer
- bytearray
- bytes
- callable
- chr
- classmethod
- cmp
- coerce
- compile
- complex
- copyright
- credits
- delattr
- dict
- dir
- divmod
- enumerate
- eval
- execfile
- exit
- file
- filter
- float
- format
- frozenset
- getattr
- globals
- hasattr
- hash
- help
- hex
- id
- input
- int
- intern
- isinstance
- issubclass
- iter
- len
- license
- list
- locals
- long
- map
- max
- memoryview
- min
- next
- object
- oct
- open
- ord
- pow
- print
- property
- quit
- range
- raw_input
- reduce
- reload
- repr
- reversed
- round
- set
- setattr
- slice
- sorted
- staticmethod
- str
- sum
- super
- tuple
- type
- unichr
- unicode
- vars
- xrange
- zip
- Run script
- first_program.py
- '''
- print 'Hello World!'
- '''
- run_script.py
- '''
- import os
- import subprocess
- # method 1
- os.system('python first_program.py')
- # method 2
- subprocess.call(['python', 'first_program.py'])
- '''
- on console
- Hello World!
- Hello World!
- Run script and check output
- first_program.py
- '''
- print 'Hello World!'
- '''
- run_script_and_check_output.py
- '''
- '''
- import subprocess
- # method 1
- print subprocess.check_output(['python', 'first_program.py']),
- # method 2
- process = subprocess.Popen(['python', 'first_program.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
- print process.stdout.read(),
- '''
- '''
- on console
- Hello World!
- Hello World!
- Save output
- save_output.py
- '''
- '''
- import sys
- sys.stdout = open('output.txt', 'w')
- print 'Hello World!'
- output.txt
- '''
- '''
- on console
- Hello World!
- '''
- # ------------ LIBRARIES --------------
- '''
- Python has a large set of function by default, but also some functions that can
- be imported to your code through the 'import' statement
- Once you import a library you will be able to use all the public functions available
- in that library.
- A library (or module) is a python script that exports functions and/or data to other scripts.
- In python any script can become a module ( we will explore this later).
- You can also import specific functions to your code as opposed to the whole lib
- to do so you use this statement
- from libX import functionName
- This can make you code faster in some implementation, since Python doesn't
- have to import all the functions from the library libX
- Some libraries do not come with the main installation of Python.
- In that case you will have to manually install the library before
- being able to import it to you code.
- '''
Add Comment
Please, Sign In to add comment