Python Chapter 1
Python Chapter 1
Language
Python 3.x
3.8 2020-04-29
3.7 2018-06-27
3.6 2016-12-23
3.5 2015-09-13
3.4 2014-03-17
3.3 2012-09-29
3.2 2011-02-20
3.1 2009-06-26
3.0 2008-12-03
Python 2.x
2.7 2010-07-03
2.6 2008-10-02
2.5 2006-09-19
2.4 2004-11-30
2.3 2003-07-29
2.2 2001-12-21
2.1 2001-04-15
2.0 2000-10-16
Python is a widely used high-level programming language for general-purpose programming, created
by Guido van
Rossum and first released in 1991. Python features a dynamic type system and automatic memory
management
Python 2.x is the legacy version and will receive only security updates until 2020. No new features
will be
implemented. Note that many projects still use Python 2, although migrating to Python 3 is getting
easier.
You can download and install either version of Python here. See Python 3 vs. Python 2 for a
comparison between
them. In addition, some third-parties offer re-packaged versions of Python that add commonly used
libraries and
other features to ease setup for common use cases, such as math, data analysis or scientific use. See
the list at the
official site.
To confirm that Python was installed correctly, you can verify that by running the following
command in your
favorite terminal (If you are using Windows OS, you need to add path of python to the environment
variable before
$ python --version
If you have Python 3 installed, and it is your default version (see Troubleshooting for more details)
you should see
$ python --version
Python 3.6.0
If you have Python 2 installed, and it is your default version (see Troubleshooting for more details)
you should see
$ python --version
Python 2.7.13
If you have installed Python 3, but $ python --version outputs a Python 2 version, you also have
Python 2
installed. This is often the case on MacOS, and many Linux distributions. Use $ python3 instead to
explicitly use the
Python 3 interpreter.
IDLE is a simple editor for Python, that comes bundled with Python.
In older versions of Windows, it can be found at All Programs under the Windows menu.
In Windows 8+, search for IDLE or find it in the apps that are present in your system.
On Unix-based (including Mac) systems you can open it from the shell by typing $ idle
python_file.py.
>>>
Hit Enter .
Hello, World
print('Hello, World')
You can use the Python 3 print function in Python 2 with the following import statement:
Python 2 has a number of functionalities that can be optionally imported from Python 3 using the
__future__
$ python hello.py
Hello, World
You can also substitute hello.py with the path to your file. For example, if you have the file in your
home directory
and your user is "user" on Linux, you can type python /home/user/hello.py.
By executing (running) the python command in your terminal, you are presented with an interactive
Python shell.
This is also known as the Python Interpreter or a REPL (for 'Read Evaluate Print Loop').
$ python
Hello, World
>>>
If you want to run Python 3 from your terminal, execute the command python3.
$ python3
Hello, World
>>>
Alternatively, start the interactive prompt and load file with python -i <file.py>.
In command line, run:
$ python -i hello.py
"Hello World"
>>>
>>> exit()
or
>>> quit()
Alternatively, CTRL + D will close the shell and put you back on your terminal's command line.
If you want to cancel a command you're in the middle of typing and get back to a clean command
prompt, while
Run a small code snippet from a machine which lacks python installation(smartphones, tablets etc).
Examples:
Disclaimer: documentation author(s) are not affiliated with any resources listed below.
https://www.python.org/shell/ - The online Python shell hosted by the official Python website.
https://repl.it/languages/python3 - Powerful and simple online compiler, IDE and interpreter. Code,
compile,
project explorer.
Hello, World
This can be useful when concatenating the results of scripts together in the shell.
Package Management - The PyPA recommended tool for installing Python packages is PIP. To install,
on your
command line execute pip install <the package name>. For instance, pip install numpy. (Note: On
windows
you must add pip to your PATH environment variables. To avoid this, use python -m pip install <the
package
name>)
Shells - So far, we have discussed different ways to run code using Python's native interactive shell.
Shells use
Python's interpretive power for experimenting with code real-time. Alternative shells include IDLE - a
pre-bundled
Programs - For long-term storage you can save content to .py files and edit/execute them as scripts
or programs
with external tools e.g. shell, IDEs (such as PyCharm), Jupyter notebooks, etc. Intermediate users
may use these
tools; however, the methods discussed here are sufficient for getting started.
Python tutor allows you to step through Python code so you can visualize how the program will flow,
and helps you
PEP8 defines guidelines for formatting Python code. Formatting code well is important so you can
quickly read what
To create a variable in Python, all you need to do is specify the variable name, and then assign a
value to it.
type to it), assigning a value to a variable itself declares and initializes the variable with that value.
There's no way to
# Integer
a=2
print(a)
# Output: 2
# Integer
b = 9223372036854775807
print(b)
# Output: 9223372036854775807
# Floating point
pi = 3.14
print(pi)
# Output: 3.14
# String
c = 'A'
print(c)
# Output: A
# String
print(name)
# Boolean
q = True
print(q)
# Output: True
x = None
print(x)
# Output: None
Variable assignment works from left to right. So the following will give you an syntax error.
0=x
You can not use python's keywords as a valid variable name. You can see the list of keyword by:
import keyword
print(keyword.kwlist)
x = True # valid
_y = True # valid
2. The remainder of your variable name may consist of letters, numbers and underscores.
x=9
y = X*5
Even though there's no need to specify a data type when declaring a variable in Python, while
allocating the
necessary area in memory for the variable, the Python interpreter automatically picks the most
suitable built-in
a=2
print(type(a))
b = 9223372036854775807
print(type(b))
# Output: <type 'int'>
pi = 3.14
print(type(pi))
c = 'A'
print(type(c))
print(type(name))
q = True
print(type(q))
x = None
print(type(x))
Now you know the basics of assignment, let's get this subtlety about assignment in python out of the
way.
When you use = to do an assignment operation, what's on the left of = is a name for the object on
the right. Finally,
what = does is assign the reference of the object on the right to the name on the left.
That is:
a_name = an_object # "a_name" is now a name for the reference to the object "an_object"
So, from many assignment examples above, if we pick pi = 3.14, then pi is a name (not the name,
since an object
can have multiple names) for the object 3.14. If you don't understand something below, come back
to this point
and read this again! Also, you can take a look at this for a better understanding.
You can assign multiple values to multiple variables in one line. Note that there must be the same
number of
a, b, c = 1, 2, 3
print(a, b, c)
# Output: 1 2 3
a, b, c = 1, 2
=> a, b, c = 1, 2
a, b = 1, 2, 3
=> a, b = 1, 2, 3
The error in last example can be obviated by assigning remaining values to equal number of arbitrary
variables.
This dummy variable can have any name, but it is conventional to use the underscore (_) for
assigning unwanted
values:
a, b, _ = 1, 2, 3
print(a, b)
# Output: 1, 2
Note that the number of _ and number of remaining values must be equal. Otherwise 'too many
values to unpack
a, b, _ = 1,2,3,4
=>a, b, _ = 1,2,3,4
a=b=c=1
print(a, b, c)
# Output: 1 1 1
When using such cascading assignment, it is important to note that all three variables a, b and c
refer to the same
object in memory, an int object with the value of 1. In other words, a, b and c are three different
names given to the
same int object. Assigning a different object to one of them afterwards doesn't change the others,
just as expected:
a = b = c = 1 # all three names a, b and c refer to same int object with value 1
print(a, b, c)
# Output: 1 1 1
print(a, b, c)
The above is also true for mutable types (like list, dict, etc.) just as it is true for immutable types (like
int, string,
tuple, etc.):
x = y = [7, 8, 9] # x and y refer to the same list object just created, [7, 8, 9]
# Output: [7, 8, 9]
So far so good. Things are a bit different when it comes to modifying the object (in contrast to
assigning the name to
a different object, which we did above) when the cascading assignment is used for mutable types.
Take a look
x = y = [7, 8, 9] # x and y are two different names for the same list object just created, [7,
8, 9]
x[0] = 13 # we are updating the value of the list [7, 8, 9] through one of its names, x
in this case
print(y) # printing the value of the list using its other name
Nested lists are also valid in python. This means that a list can contain another list as an element.
# Output: [3, 4, 5]
print x[2][1]
# Output: 4
Lastly, variables in Python do not have to stay the same type as which they were first defined -- you
can simply use
a=2
print(a)
# Output: 2
a = "New value"
print(a)
If this bothers you, think about the fact that what's on the left of = is just a name for an object. First
you call the int
object with value 2 a, then you change your mind and decide to give the name a to a string object,
having value
Python uses indentation to define control and loop constructs. This contributes to Python's
readability, however, it
requires the programmer to pay close attention to the use of whitespace. Thus, editor miscalibration
could result in
Python uses the colon symbol (:) and indentation for showing where blocks of code begin and end (If
you come
from another language, do not confuse this with somehow being related to the ternary operator).
That is, blocks in
Python, such as functions, loops, if clauses and other constructs, have no ending identifiers. All
blocks start with a
For example:
or
Blocks that contain exactly one single-line statement may be put on the same line, though this form
is generally not
if a > b: print(a)
else: print(b)
Attempting to do this with more than a single statement will not work:
if x > y: y = x
An empty block causes an IndentationError. Use pass (a command that does nothing) when you have
a block with
no content:
def will_be_implemented_later():
pass
Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are
preferred.
Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time
error is
generated: Inconsistent use of tabs and spaces in indentation and the program will not run.
the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured
to show tabs
Citing PEP 8:
When invoking the Python 2 command line interpreter with the -t option, it issues warnings about
code
that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are
highly recommended!
Many editors have "tabs to spaces" configuration. When configuring the editor, one should
differentiate between
The tab character should be configured to show 8 spaces, to match the language semantics - at least
in cases
when (accidental) mixed indentation is possible. Editors can also automatically convert the tab
character to
spaces.
However, it might be helpful to configure the editor so that pressing the Tab key will insert 4 spaces,
Python source code written with a mix of tabs and spaces, or with non-standard number of
indentation spaces can
be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python
installations:
reindent.py)
Built-in Types
Booleans
bool: A boolean value of either True or False. Logical operations like and, or, not can be performed
on booleans.
If boolean values are used in arithmetic operations, their integer values (1 and 0 for True and False)
will be used to
True + False == 1 # 1 + 0 == 1
True * True == 1 # 1 * 1 == 1
Numbers
a=2
b = 100
c = 123456789
d = 38563846326424324
Note: in older versions of Python, a long type was available and this was distinct from int. The two
have
been unified.
float: Floating point number; precision depends on the implementation and system architecture, for
a = 2.0
b = 100.e0
c = 123456789.e1
a = 2 + 1j
b = 100 + 10j
The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex
number.
Strings
Python differentiates between ordered sequences and unordered collections (such as set and dict).
a = reversed('hello')
a = (1, 2, 3)
a = [1, 2, 3]
a = {1, 2, 'a'}
a = {1: 'one',
2: 'two'}
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects
which
Built-in constants
In conjunction with the built-in datatypes there are a small number of built-in constants in the built-
in namespace:
Ellipsis or ...: used in core Python3+ anywhere and limited usage in Python2.7+ as part of array
notation.
numpy and related packages use this as a 'include everything' reference in arrays.
NotImplemented: a singleton used to indicate to Python that a special method doesn't support the
specific
a = None # No value will be assigned. Any valid datatype can be assigned later
None doesn't have any natural ordering. Using ordering comparison operators (<, <=, >=, >) isn't
supported anymore
None is always less than any number (None < -32 evaluates to True).
In python, we can check the datatype of an object using the built-in function type.
a = '123'
print(type(a))
b = 123
print(type(b))
i=7
if isinstance(i, int):
i += 1
i = int(i)
i += 1
For information on the differences between type() and isinstance() read: Differences between
isinstance and
type in Python
x = None
if x is None:
For example, '123' is of str type and it can be converted to integer using int function.
a = '123'
b = int(a)
Converting from a float string such as '123.456' can be done using float function.
a = '123.456'
b = float(a)
c = int(a) # ValueError: invalid literal for int() with base 10: '123.456'
d = int(b) # 123
a = 'hello'
r'foo bar': results so called raw string, where escaping special characters is not necessary, everything
is
# bar
An object is called mutable if it can be changed. For example, when you pass a list to some function,
the list can be
changed:
def f(m):
x = [1, 2]
f(x)
An object is called immutable if it cannot be changed in any way. For example, integers are
immutable, since there's
def bar():
x = (1, 2)
g(x)
x == (1, 2) # Will always be True, since no function can change the object (1, 2)
Note that variables themselves are mutable, so we can reassign the variable x, but this does not
change the object
that x had previously pointed to. It only made x point to a new object.
Data types whose instances are mutable are called mutable data types, and similarly for immutable
objects and
datatypes.
str
bytes
tuple
frozenset
bytearray
list
set
dict
There are a number of collection types in Python. While types such as int and str hold a single value,
collection
Lists
The list type is probably the most commonly used collection type in Python. Despite its name, a list is
more like an
array in other languages, mostly JavaScript. In Python, a list is merely an ordered collection of valid
Python values. A
int_list = [1, 2, 3]
empty_list = []
The elements of a list are not restricted to a single data type, which makes sense given that Python is
a dynamic
language:
The elements of a list can be accessed via an index, or numeric representation of their position. Lists
in Python are
zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1
and so on:
print(names[0]) # Alice
print(names[2]) # Craig
Indices can also be negative which means counting from the end of the list (-1 being the index of the
last element).
print(names[-1]) # Eric
print(names[-4]) # Bob
names[0] = 'Ann'
print(names)
names.append("Sia")
print(names)
names.insert(1, "Nikki")
print(names)
names.remove("Bob")
name.index("Alice")
len(names)
a = [1, 1, 1, 2, 3, 4]
a.count(1)
a.reverse()
[4, 3, 2, 1, 1, 1]
# or
a[::-1]
[4, 3, 2, 1, 1, 1]
Remove and return item at index (defaults to the last item) with L.pop([index]), returns the item
print (element)
Tuples
A tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple
cannot be changed
nor the values be added to or removed from the tuple. Tuples are commonly used for small
collections of values
that will not need to change, such as an IP address and port. Tuples are represented with
parentheses instead of
square brackets:
The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can
be any valid
Python valid.
A tuple with only one member must be defined (note the comma) this way:
or
Dictionaries
A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces.
Each pair is
separated by a comma and the key and value are separated by a colon. Here is an example:
state_capitals = {
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'
ca_capital = state_capitals['California']
You can also get all of the keys in a dictionary and then iterate over them:
for k in state_capitals.keys():
Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library
can be used to
set
A set is a collection of elements with no repeats and without insertion order but sorted order. They
are used in
situations where it is only important that some things are grouped together, and not what order
they were
included. For large groups of data, it is much faster to check whether or not an element is in a set
than it is to do
the same for a list.
my_list = [1,2,3]
my_set = set(my_list)
if name in first_names:
print(name)
You can iterate over a set exactly like a list, but remember: the values will be in an arbitrary,
implementationdefined order.
defaultdict
A defaultdict is a dictionary with a default value for keys, so that keys for which no value has been
explicitly
defined can be accessed without errors. defaultdict is especially useful when the values in the
dictionary are
collections (lists, dicts, etc) in the sense that it does not need to be initialized every time when a new
key is used.
A defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.
>>> state_capitals = {
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'
>>> state_capitals['Alabama']
state_capitals['Alabama']
KeyError: 'Alabama'
What we did here is to set a default value (Boston) in case the give key does not exist. Now populate
the dict as
before:
If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston
>>> state_capitals['Alabama']
'Boston'
and returns the created values for existing key just like a normal dictionary
>>> state_capitals['Arkansas']
'Little Rock'
IDLE is Python’s Integrated Development and Learning Environment and is an alternative to the
command line. As
the name may imply, IDLE is very useful for developing new code or learning python. On Windows
this comes with
the Python interpreter, but in other operating systems you may need to install it through your
package manager.
Multi-window text editor with syntax highlighting, autocompletion, and smart indent
Integrated debugger with stepping, persistent breakpoints, and call stack visibility
Saving the Python program as .py files and run them and edit them later at any them using IDLE.
In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning
experience for
new users because code is interpreted as the user writes.
Note that there are lots of alternatives, see for example this discussion or this list.
Troubleshooting
Windows
If you're on Windows, the default command is python. If you receive a "'python' is not recognized"
error,
the most likely cause is that Python's location is not in your system's PATH environment variable.
This can be
'Control Panel'. Click on 'Advanced system settings' and then 'Environment Variables...'. Edit the
PATH variable
to include the directory of your Python installation, as well as the Script folder (usually
When using multiple versions of Python on the same machine, a possible solution is to rename one
of the
python.exe files. For example, naming one version python27.exe would cause python27 to become
the
You can also use the Python Launcher for Windows, which is available through the installer and
comes by
default. It allows you to select the version of Python to run by using py -[x.y] instead of python[x.y].
You
can use the latest version of Python 2 by running scripts with py -2 and the latest version of Python 3
by
Debian/Ubuntu/MacOS
This section assumes that the location of the python executable has been added to the PATH
environment
variable.
If you're on Debian/Ubuntu/MacOS, open the terminal and type python for Python 2.x or python3
for Python
3.x.
Arch Linux
The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for
Python 3.x and
Other systems
Python 3 is sometimes bound to python instead of python3. To use Python 2 on these systems
where it is
Interactive input
To get input from the user, use the input function (note: in Python 2.x, the function is called
raw_input instead,
although Python 2.x has its own version of input that is completely different):
Security Remark Do not use input() in Python2 - the entered text will be evaluated as if it were a
See this article for further information on the risks of using this function.
The function takes a string argument, which displays it as a prompt and returns a string. The above
code provides a
If the user types "Bob" and hits enter, the variable name will be assigned to the string "Bob":
print(name)
# Out: Bob
Note that the input is always of type str, which is important if you want the user to enter numbers.
Therefore, you
x = input("Write a number:")
x/2
float(x) / 2
# Out: 5.0
NB: It's recommended to use try/except blocks to catch exceptions when dealing with user inputs.
For instance, if
your code wants to cast a raw_input into an int, and what the user writes is uncastable, it raises a
ValueError.
A module is a file containing Python definitions and statements. Function is a piece of code which
execute some
logic.
>>> pow(2,3) #8
To check the built in function in python we can use dir(). If called without an argument, return the
names in the
current scope. Else, return an alphabetized list of names comprising (some of) the attribute of the
given object, and
>>> dir(__builtins__)
'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',
'ZeroDivisionError',
'__debug__',
'__doc__',
GoalKicker.com – Python
'__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'
To know the functionality of any function, we can use built in function help .
>>> help(max)
max(...)
Built in modules contains extra functionalities. For example to get square root of a number we need
to include math
module.
To know all the functions in a module we can assign the functions list to a variable, and then print
the variable.
>>> import math
>>> dir(math)
>>> math.__doc__
In addition to functions, documentation can also be provided in modules. So, if you have a file
named
def sayHello():
>>> helloWorld.__doc__
>>> helloWorld.sayHello.__doc__
For any user defined type, its attributes, its class's attributes, and recursively the attributes of its
class's base
... pass
...
>>> dir(MyClassObject)
Any data type can be simply converted to string using a builtin function called str. This function is
called by default
# hello.py
def say_hello():
print("Hello!")
For modules that you have made, they will need to be in the same directory as the file that you are
importing them
into. (However, you can also put them into the Python lib directory with the pre-included modules,
but should be
avoided if possible.)
$ python
>>> hello.say_hello()
=> "Hello!"
# greet.py
import hello
hello.say_hello()
# greet.py
from hello import say_hello
say_hello()
# greet.py
import hello as ai
ai.say_hello()
# run_hello.py
if __name__ == '__main__':
say_hello()
Run it!
$ python run_hello.py
=> "Hello!"
If the module is inside a directory and needs to be detected by python, the directory should contain
a file named
__init__.py.
Note: Following instructions are written for Python 2.7 (unless specified): instructions for Python 3.x
are
similar.
Windows
First, download the latest version of Python 2.7 from the official Website
(https://www.python.org/downloads/).
Version is provided as an MSI package. To install it manually, just double-click the file.
C:\Python27\
Warning: installation does not automatically modify the PATH environment variable.
Assuming that your Python installation is in C:\Python27, add this to your PATH:
C:\Python27\;C:\Python27\Scripts\
To install and use both Python 2.x and 3.x side-by-side on a Windows machine:
Optional: add Python to PATH to make Python 2.x callable from the command-line using python.
Optional: add Python to PATH to make Python 3.x callable from the command-line using python. This
may override Python 2.x PATH settings, so double-check your PATH and ensure it's configured to
your
preferences.
Python 3 will install the Python launcher which can be used to launch Python 2.x and Python 3.x
interchangeably
P:\>py -3
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
>>>
C:\>py -2
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 Intel)] on win32
>>>
To use the corresponding version of pip for a specific Python version, use:
C:\>py -3 -m pip -V
C:\>py -2 -m pip -V
Linux
The latest versions of CentOS, Fedora, Red Hat Enterprise (RHEL) and Ubuntu come with Python 2.7.
cd Python-2.7.X
./configure
make
Also add the path of new python in PATH environment variable. If new python is in /root/python-
2.7.X then run
python --version
If you need Python 3.6 you can install it from source as shown below (Ubuntu 16.10 and 17.04 have
3.6 version in
the universal repository). Below steps have to be followed for Ubuntu 16.04 and lower versions:
wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz
cd Python-3.6.1/
./configure --enable-optimizations
macOS
As we speak, macOS comes installed with Python 2.7.10, but this version is outdated and slightly
modified from the
regular Python.
The version of Python that ships with OS X is great for learning but it’s not good for development.
The
version shipped with OS X may be out of date from the official current Python release, which is
Install Homebrew:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
For Python 3.x, use the command brew install python3 instead.
There are two functions that can be used to obtain a readable representation of an object.
repr(x) calls x.__repr__(): a representation of x. eval will usually convert the result of this function
back to the
original object.
str(x) calls x.__str__(): a human-readable string that describes the object. This may elide some
technical detail.
repr()
For many types, this function makes an attempt to return a string that would yield an object with the
same value
when passed to eval(). Otherwise, the representation is a string enclosed in angle brackets that
contains the name
of the type of the object along with additional information. This often includes the name and
address of the object.
str()
For strings, this returns the string itself. The difference between this and repr(object) is that
str(object) does
not always attempt to return a string that is acceptable to eval(). Rather, its goal is to return a
printable or 'human
readable' string. If no argument is given, this returns the empty string, ''.
Example 1:
s = """w'o"w"""
Example 2:
import datetime
today = datetime.datetime.now()
When writing a class, you can override these methods to do whatever you want:
class Represent(object):
self.x, self.y = x, y
def __repr__(self):
def __str__(self):
r = Represent(1, "Hopper")
Represent(x=1,y="Hopper")>'
pip is your friend when you need to install any package from the plethora of choices available at the
python
package index (PyPI). pip is already installed if you're using Python 2 >= 2.7.9 or Python 3 >= 3.4
downloaded from
python.org. For computers running Linux or another *nix with a native package manager, pip must
often be
manually installed.
On instances with both Python 2 and Python 3 installed, pip often refers to Python 2 and pip3 to
Python 3. Using
pip will only install packages for Python 2 and pip3 will only install packages for Python 3.
Installing a package is as simple as typing (in a terminal / command-prompt, not in the Python
interpreter)
where x.x.x is the version number of the package you want to install.
When your server is behind proxy, you can install package by using below command:
When new versions of installed packages appear they are not automatically installed to your system.
To get an
Upgrading pip
You can upgrade your existing pip installation by using the following commands
On Linux or macOS X:
You may need to use sudo with pip on some Linux Systems
On Windows:
or
Python has several functions built into the interpreter. If you want to get information of keywords,
built-in
>>> help()
>>> help(help)
help> help
class _Helper(builtins.object)
| __repr__(self)
| ----------------------------------------------------------------------
| __dict__
| __weakref__
help(pymysql.connections)
You can use help to access the docstrings of the different modules you have imported, e.g., try the
following:
>>> help(math)
>>> help(math)
And now you will get a list of the available methods in the module, but only AFTER you have
imported it.