Python

History

Python is an all-purpose programming language created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands as a successor of a language called ABC. Guido remains Python’s principal author, although it includes many contributions from others.

WHY THE NAME PYTHON?

According to the principal author (Guido van Rossum), he chose the name "Python" because he is a big fan of the British comedy movie - 'Monty Python's Flying Circus'. Here is what the author had to say: "Over six years ago, in December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. ... I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus)."

APPLICATIONS FOR PYTHON

Python is used successfully in thousands of real-world business applications around the world, including many large and mission critical systems. Although the applications for Python are numerous they can be broadly categorized into:

  • Web and Internet Development
  • Scientific and Numeric Computing
  • Education
  • Desktop Graphical User Interfaces (GUIs)
  • Software Development

Quotes

Here are some QUOTES about python from some companies.

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

Python Keywords

Keywords are special words that are reserved by Python and cannot be used by you to name things. They indicate commands to the Python interpreter. The following is a complete list of Python keywords:

and del from not
while as elif global
or with assert else
if pass yield break
except import nonlocal class
lambda in raise continue
finally is return def
for try True False
None

Python Operators

Operators are special tokens (sequence of characters) that have meaning to the Python Interpreter. Using them implies some form of mathematical operation. The following is the complete list of Operators.
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
// Floor Division
% Modulus
<< Left Shift
>> Right Shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
== Equal To
!= Not Equal To
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
//= Floor Division Assignment
%= Modulus Assignment
&= Bitwise AND Assignment
|= Bitwise OR Assignment
^= Bitwise XOR Assignment
>>= Right Shift Assignment
<<= Left Shift Assignment
**= Exponentiation Assignment

Punctuators and Delimiters

Punctuators which are also known as delimiters, separate different elements in Python statements and expressions. Here is the complete list:
Punctuator/Delimiter Description
( Left Parenthesis
) Right Parenthesis
[ Left Square Bracket
] Right Square Bracket
{ Left Curly Brace
} Right Curly Brace
, Comma
: Colon
. Period
` Backtick
= Equals
; Semicolon
' Single Quote
'' Double Quote
# Hash
\ Backslash
@ At Symbol

Python Arithmetic Operators

Operator Meaning Usage
+ Addition or unary plus x + y
- Subtraction or unary minus x - y
* Multiplication x * y
/ Division (result is always a float) x / y
% Modulus x % y (remainder of x/y)
// Floor division x // y
** Exponent x**y (x to the power y)

Python Operators Precedence Table

Operator Description
** Exponentiation
~, +, - Complement, unary plus and unary minus
*, /, %, // Multiply, divide, modulo and whole (floor) division
+, - Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise and
^ ,| Bitwise exclusive or and bitwise or
<=, < ,> ,>=, Relational operators
<> ,== ,!= Equality operators
= ,%= ,/= ,//= ,-= ,+= ,*=, **= Assignment operators
is , is not Identity operators
in not in Membership operators
not , or , and Logical operators

Python Relational Ooperators

Operator Meaning Usage
> Greater than x > y
< Less than x < y
== Equal to x == y
!= Not equal to x != y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Ooperators

Operator Meaning Usage
and True if both operands are true x and y
or True if either operand is true x or y
not Complements the operand not x

Python Boolean Ooperators

The basic Boolean operators are: not, and, or. The following is the truth table for each of these operators respectively. Note that A and B in the tables below are the names of the operands that represent a Boolean Expression
A not A
True False
False True
A B A and B
True True True
True False False
False True False
False False False
A B A or B
True True True
True False True
False True True
False False False

Python Membership Operators

Operator Meaning Usage
in Check to see if value is in the sequence 5 in [2, 5, 3, 7]
not in Check to see if value is not in the sequence 5 not in [2, 5, 3, 7]

Complete Precedence Table

The following table shows the complete precedence of Python Operators: Highest to Lowest
Operator Description
() Parenthesis (grouping)
f(args...), x[i:i], x[i], x.attr Function call, slicing, subscript, dot
** Exponentiation
+, -, ~ Unary Positive, Unary Negative, bitwise NOT
*, /, % Multiplication, Division, Remainder
+, - Addition, Subtraction
<<, >> Shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
<, <=, >, >=, !=, ==, is, is not, in, not in Comparisons, identity, membership
not Boolean NOT
and Boolean AND
or Boolean OR
lambda Lambda Expression

Functions

Most of the time we provide some arguments to a function and it returns something. However, this may not always be the case. While trying to write a function we need to decide if the function needs any arguments or not and if the function needs to return something or not. Broadly, we can attempt to classify the combination of function parameters and their return types as follows:

1. Nothing goes in, nothing comes out.
2. Nothing goes in, something comes out.
3. Something goes in, nothing comes out.
4. Something goes in, something comes out.

Built-in Functions

The python interpreter has a number of functions built into it that are always available.

abs() dict() help() min()
set() all() dir() hex()
next() slice() any() divmod()
id() object() sorted() ascii()
enumerate() input() oct() staticmethod()
bin() eval() int() open()
str() bool() exec() isinstance()
ord() sum() bytearray() filter()
issubclass() pow() super() bytes()
float() iter() print() tuple()
callable() format() len() property()
type() chr() frozenset() list()
range() vars() classmethod() getattr()
locals() repr() zip() compile()
globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()

List Methods

list.append(x)	                        Add an item to the end of the list. Equivalent to a[len(a):] = [x].
list.extend(L)	                        Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.
list.insert(i, x)	                    Insert an item at a given position. The first argument is the index of the element to insert.
list.remove(x)	                        Remove the first item from the list whose value is x. It is an error if there is no such item.
list.copy()	                            Return a shallow copy of the list. Equivalent to a[:].
list.pop([i])	                        Remove the item at the given position and return it. If no index is specified, removes the last item.
list.clear()	                        Remove all items from the list. Equivalent to del a[:].
list.index(x)	                        Return the index in the list of the first item whose value is x. error if no such item.
list.count(x)	                        Return the number of times x appears in the list.
list.reverse()	                        Reverse the elements of the list in place.
list.sort(key=None, reverse=False)      Sort the items of the list in place (the arguments can be used for sort customization).

String Methods

Method	                            Description
s.capitalize()	                    The first character of s is put in uppercase
s.center([width])	                Centers s in a field of length width
s.count(sub [,start [, end]])	    Counts occurrences of sub between start and end
s.encode([encoding [, errors]])	    Encode s using encoding as code and error
s.expandtabs([tabsize])	            Expands tabs
s.find(sub [, start [, end]])	    Finds the first occurrence of sub between start and end
s.index(sub [,start [, end]])	    same as find but raises an exception if no occurrence is found
s.islower()	                        Returns True if all chracters are lowercase, False otherwise
s.isupper()	                        Returns True if all chracters are uppercase, False otherwise
s.join(words)	                    Joins the list of words with s as delimiter
s.ljust(width)	                    Left align s in a string of length width
s.lower()	                        Returns a lowercase version of s
s.lstrip()	                        Removes all leading whitespace characters of s
s.replace(old, new [, maxrep])	    Replace maximal maxrep versions of substring old with substring new
s.rfind(sub [, start [, end]])	    Finds the last occurrence of substring sub between start and end
s.rindex(sub [,start [, end]])	    Same as rfind but raise an exception if sub does not exists
s.rjust(width)	                    Right-align s in a string of length width
s.rstrip()	                        Removes trailing whitespace characters
s.split([sep [, maxsplit]]))	    Split s into maximal maxsplit words using sep as separator (default whitespace)
s.splitlines([keepends])	        Split s into lines, if keepends is 1 keep the trailing newline
s.strip()	                        Removes trailing and leading whitespace characters
s.swapcase()	                    Returns a copy of s with lowercase letters turn into uppercase and vice versa
s.title()	                        Returns a title-case version of s (all words capitalized)
s.upper()	                        Returns an uppercase version of s

Dictionary Methods

Method Name                         Description
dict.clear()	                    Removes all elements of dictionary.
dict.copy()	                        Returns a shallow copy of dictionary.
dict.fromkeys(seq[,value])	        Create a new dictionary with keys from seq and values set to value.
dict.get(key, default=None)	        For key key, returns value or default if key not in dictionary
dict.items()	                    Returns a view object of dict items.
dict.keys()	                        Returns a view object of dict keys.
dict.pop(key)	                    Remove key, Return value
dict.setdefault(key, default=None)	Similar to get(), but will set dict[key]=default if key is not already in dict
dict.update(dict2)	                Adds dictionary dict2's key-values pairs to dict
dict.values()	                    Returns a view object of dict_values.

File Access Modes

Mode     Description
r		 Opens a file for reading only. This is the default mode.
rb		 Opens a file for reading only in binary format
r+		 Opens a file for both reading and writing.
rb+		 Opens a file for both reading and writing in binary format.
w		 Opens a file for writing only. Overwrites the file if the file exists. Create a new file if it does not exist.
wb		 Opens a file for writing only in binary format.
w+		 Opens a file for both writing and reading. Overwrites the file if the file exists. Create a new file if it does not exist.
wb+		 Opens a file for both writing and reading in binary format.
a		 Opens a file for appending. The file pointer is at the end of the file if the file exists.
ab		 Opens a file for appending in binary format.
a+		 Opens a file for both appending and reading.
ab+		 Opens a file for both appending and reading in binary format. 

File Functions and Methods

Methods and Functions	    Description
open()	                    returns a file object, and is most commonly used with two arguments: open(filename, mode).
file.close()	            Close the file
file.read([size])  	        Read entire file. If size is specified then read at most size bytes.
file.readline([size])	    Read one line from file. If size is specified then read at most size bytes.
file.readlines([size]) 	    Read all the lines from the file and return a list of lines. If size is specified then read at most size bytes.
file.write()	            Writes the contents of string to the file, returning the number of characters written.
file.tell()                 Returns an integer giving the file object’s current position in the file
file.seek()	                Changes the file object’s position
References:
Rossum, Guido Van. "Foreword for "Programming Python" Python.org, May 1996. Web. 22 Dec. 2015.
"About Python." About Python | Python.org  Python.org, n.d. Web.
"32.6. Keyword — Testing for Python Keywords." 32.6. Keyword. Python Software Foundation, 1 Jan. 2016. Web. 10 Jan. 2016.
Punch, W. F., and Richard J. Enbody. "Beginnings." The Practice of Computing Using Python. Boston, MA: Addison-Wesley/Pearson, 2011. 47. Print.