Chapter 1: Getting started with Python Language

Python 3.x

Version Release Date









Python 2.x

Version Release Date









Section 1.1: Getting Started

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 and supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library.

Two major versions of Python are currently in active use:

 Python 3.x is the current version and is under active development.

 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 oer 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 ocial site.

Verify if Python is installed

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 using it in command prompt):

$ python –version

Python 3.x Version ≥ 3.0

If you have Python 3 installed, and it is your default version (see Troubleshooting for more details) you should see something like this:

$python –versionPython 3.6.0

Python 2.x Version ≤ 2.7

If you have Python 2 installed, and it is your default version (see Troubleshooting for more details) you should see something like this:

$python –versionPython 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.

Hello, World in Python using IDLE

IDLE is a simple editor for Python, that comes bundled with Python.

How to create Hello, World program in IDLE

 Open IDLE on your system of choice.

 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

 It will open a shell with options along the top.

In the shell, there is a prompt of three right angle brackets:


Now write the following code in the prompt:

>>>print(“Hello, World”)

Hit Enter .

>>>print(“Hello, World”) HelloWorld

Hello World Python file

Create a new file that contains the following line:

Python 3.x Version ≥ 3.0

print(‘Hello, World’)

Python 2.x Version ≥ 2.6

You can use the Python 3 print function in Python 2 with the following import statement:


from __future__ import print_function

Python 2 has a number of functionalities that can be optionally imported from Python 3 using the __future__ module, as discussed here.

Python 2.x Version ≤ 2.7

If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus not recommended because it reduces cross-version code compatibility.

print ‘Hello, World’

In your terminal, navigate to the directory containing the file

Type python, then hit the Enter key.

$python HelloWorld

You should see HelloWorld printed to the console.

You can also substitute 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/

Launch an interactive Python shell

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

Python 2.7.12 (defaultJun 28 201608:46:01) [GCC 6.1.1 20160602] on linux

Type “help”“copyright”“credits” or “license” for more information.

>>>print ‘Hello, World’ HelloWorld

If you want to run Python 3 from your terminal, execute the command python3.

$ python3

Python 3.6.0 (defaultJan 13 201700:00:00) [GCC 6.1.1 20160602] on linux

Type “help”“copyright”“credits” or “license” for more information.

>>>print(‘Hello, World’) HelloWorld

Alternatively, start the interactive prompt and load file with python -i <>.

In command line, run:

$python -i “Hello World”


There are multiple ways to close the Python shell:





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 staying inside the Interpreter shell, use CTRL + C .

Try an interactive Python shell online.

Other Online Shells

Various websites provide online access to Python shells.

Online shells may be useful for the following purposes:

 Run a small code snippet from a machine which lacks python installation(smartphones, tablets etc).

 Learn or teach basic Python. Solve online judge problems.


Disclaimer: documentation author(s) are not aliated with any resources listed below. – The online Python shell hosted by the ocial Python website. – Widely used on the Net to illustrate code snippet behavior. – Powerful and simple online compiler, IDE and interpreter. Code, compile, and run code in Python. – Full-featured UNIX shell, and a user-friendly project explorer. – Simple and easy to use IDE which shows execution time

Run commands as a string

Python can be passed arbitrary code as a string in the shell:

$python -c ‘print(“Hello, World”)’ HelloWorld

This can be useful when concatenating the results of scripts together in the shell.

Shells and Beyond

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 dierent 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

GUI, IPython – known for extending the interactive experience, etc.

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 sucient for getting started.

Python tutor allows you to step through Python code so you can visualize how the program will flow, and helps you to understand where your program went wrong.

PEP8 defines guidelines for formatting Python code. Formatting code well is important so you can quickly read what the code does.

Section 1.2: Creating variables and assigning values

To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it.


Python uses = to assign values to variables. There’s no need to declare a variable in advance (or to assign a data type to it), assigning a value to a variable itself declares and initializes the variable with that value. There’s no way to declare a variable without assigning it an initial value.

#Integer print(a)

#Output: 2


9223372036854775807 print(b)

#Output: 9223372036854775807

#Floating point

pi 3.14 print(pi)

#Output: 3.14


‘A’ print(c)

#Output: A


name ‘John Doe’ print(name)

#Output: John Doe


True print(q)

#Output: True

#Empty value or null data type None


#Output: None

Variable assignment works from left to right. So the following will give you an syntax error.



=> Output: SyntaxError: can‘t assign to literal

You can not use python’s keywords as a valid variable name. You can see the list of keyword by:

import keyword


Rules for variable naming:

1. Variables names must start with a letter or an underscore.





_y =




9x False # starts with numeral => SyntaxError: invalid syntax

$y False # starts with symbol => SyntaxError: invalid syntax

2. The remainder of your variable name may consist of letters, numbers and underscores.

has_0_in_it “Still Valid”

3.Names are case sensitive.9


=>NameError: name ‘X’ is not defined

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 type for it:



# Output: <type ‘int’>

9223372036854775807 print(type(b))

# Output: <type ‘int’>

pi 3.14


# Output: <type ‘float’>



# Output: <type ‘str’>

name ‘John Doe’ print(type(name))

# Output: <type ‘str’>

True print(type(q))

# Output: <type ‘bool’>

None print(type(x))

# Output: <type ‘NoneType’>

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 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 arguments on the right and left sides of the = operator:


# Output: 1 2 3




=> Traceback

(most recent call last):



“”line Nin <module>





=> ValueError: need more than values to unpack




=> Traceback

(most recent call last):



“”line Nin <module>




=> ValueError: too many values to unpack

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:


# Output: 1, 2

Note that the number of _ and number of remaining values must be equal. Otherwise ‘too many values to unpack error’ is thrown as above:


=>Traceback (most recent call last): =>File “”line Nin <module> =>ab1,2,3,4

=>ValueError: too many values to unpack (expected 3)

You can also assign a single value to several variables simultaneously.


# Output: 1 1 1

When using such cascading assignment, it is important to note that all three variables ab and c refer to the same object in memory, an int object with the value of 1. In other words, ab and c are three dierent names given to the same int object. Assigning a dierent object to one of them afterwards doesn’t change the others, just as expected:




# all three names a, b and c refer to same int

object with value 1





# Output: 1 1 1






# b now refers to another int object, one with

a value of 2





# Output: 1 2 1 # so output is as expected.

The above is also true for mutable types (like listdict, etc.) just as it is true for immutable types (like intstringtuple, etc.):



# x and y

refer to the same list object just created, [7, 8, 9]



# x now refers to a

different list object just created, [13, 8, 9]


# y still

refers to

the list it was first assigned

# Output: [7, 8, 9]









So far so good. Things are a bit dierent when it comes to modifying the object (in contrast to assigning the name to a dierent object, which we did above) when the cascading assignment is used for mutable types. Take a look below, and you will see it first hand:


# x and y are two different names for the same list object just created, [7,





# we are updating the value of the list [7, 8, 9] through one of its names, x

in this case



# printing the value of the list using its other name

# Output: [13, 8, 9]

# hence, naturally the change is reflected




Nested lists are also valid in python. This means that a list can contain another list as an element.

[12[345]67# this is nested list print x[2]

#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

=to assign a new value to a variable, even if that value is of a dierent type.


# Output: 2

“New value” print(a)

# Output: New value

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 ‘New value’. Simple, right?

Section 1.3: Block Indentation

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 code that behaves in unexpected ways.

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 colon and then contain the indented lines below it.

For example:

def my_function():

# This is a function definition. Note the colon (:)


# This line belongs to the function because it’s indented

return a

# This line also belongs to the same function


# This line is OUTSIDE the function block







if b:

# If block starts here


# This is part of the if block


# else must be at the same level as if


# This line is part of the else block



Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style:

if b: print(a)


Attempting to do this with more than a single statement will not work:

if y: y x

print(y) # IndentationError: unexpected indent

if y: while != z: y = # SyntaxError: invalid syntax

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

Spaces vs. Tabs

In short: always use 4 spaces for indentation.

Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.

Python 3.x Version ≥ 3.0

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.

Python 2.x Version ≤ 2.7

Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of spaces. Since it is common that editors are configured to show tabs as multiple of spaces, this can cause subtle bugs.

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 dierentiate between the tab character (‘\t’) and the Tab key.

 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, instead of inserting a tab character.

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:

Section 1.4: Datatypes

Built-in Types


bool: A boolean value of either True or False. Logical operations like andornot can be performed on booleans.


or y

# if x is

False then y






# if x


False then x



not x


# if x


True then False, otherwise True









In Python 2.x and in Python 3.x, a boolean is also an int. The bool type is a subclass of the int type and True and False are its only instances:

issubclass(boolint# True

isinstance(Truebool# True isinstance(Falsebool# True

If boolean values are used in arithmetic operations, their integer values (1 and 0 for True and False) will be used to return an integer result:

True False == # 1 + 0 == 1

True True == # 1 * 1 == 1


 int: Integer number














Integers in Python are of arbitrary sizes.

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 CPython the float datatype corresponds to a C double.












 complex: Complex numbers

+ 1j

100 + 10j

The <<=> and >= operators will raise a TypeError exception when any operand is a complex number.


Python 3.x Version ≥ 3.0

 str: a unicode string. The type of ‘hello’

 bytes: a byte string. The type of b‘hello’

Python 2.x Version ≤ 2.7

 str: a byte string. The type of ‘hello’ bytes: synonym for str

 unicode: a unicode string. The type of u‘hello’

Sequences and collections

Python dierentiates between ordered sequences and unordered collections (such as set and dict).

 strings (strbytesunicode) are sequences

 reversed: A reversed order of str with reversed function


 tuple: An ordered collection of n values of any type (>= 0).



b[2‘something else’ # returns a TypeError

Supports indexing; immutable; hashable if all its members are hashable

 list: An ordered collection of n values (>= 0)


[‘a’1‘python’(12)[12]] b[2‘something else’ # allowed

Not hashable; mutable.

 set: An unordered collection of unique values. Items must be hashable.


 dict: An unordered collection of unique key-value pairs; keys must be hashable.


{‘a’: [123]‘b’‘a string’}

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equality must have the same hash value.

Built-in constants

In conjunction with the built-in datatypes there are a small number of built-in constants in the built-in namespace:

 True: The true value of the built-in type bool

 False: The false value of the built-in type bool

 None: A singleton object used to signal that a value is absent.

 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 arguments, and Python will try alternatives if available.

None # No value will be assigned. Any valid datatype can be assigned later

Python 3.x Version ≥ 3.0

None doesn’t have any natural ordering. Using ordering comparison operators (<<=>=>) isn’t supported anymore and will raise a TypeError.

Python 2.x Version ≤ 2.7

None is always less than any number (None 32 evaluates to True).

Testing the type of variables

In python, we can check the datatype of an object using the built-in function type.

‘123’ print(type(a))

#Out: <class ‘str’> 123 print(type(b))

#Out: <class ‘int’>

In conditional statements it is possible to test the datatype with isinstance. However, it is usually not encouraged to rely on the type of the variable.


if isinstance(iint): i +1

elif isinstance(istr): i int(i)

i +1

For information on the dierences between type() and isinstance() read: Dierences between isinstance and type in Python

To test if something is of NoneType:


if is None:

print(‘Not a surprise, I just defined x as None.’)

Converting between datatypes

You can perform explicit datatype conversion.

For example, ‘123’ is of str type and it can be converted to integer using int function.

‘123’ int(a)

Converting from a float string such as ‘123.456’ can be done using float function.










# ValueError: invalid literal for int() with base 10: ‘123.456’




# 123





You can also convert sequence or collection types


list(a) # [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] set(a) # {‘o’, ‘e’, ‘l’, ‘h’} tuple(a) # (‘h’, ‘e’, ‘l’, ‘l’, ‘o’)

Explicit string type at definition of literals

With one letter labels just in front of the quotes you can tell what type of string you want to define.

 b‘foo bar’: results bytes in Python 3, str in Python 2  u‘foo bar’: results str in Python 3, unicode in Python 2

 ‘foo bar’: results str

 r‘foo bar’: results so called raw string, where escaping special characters is not necessary, everything is taken verbatim as you typed

normal ‘foo\nbar’ # foo


escaped ‘foo\\nbar’ # foo\nbar


r‘foo\nbar’ # foo\nbar

Mutable and Immutable Data Types

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):

m.append(3# adds a number to the list. This is a mutation.

[12] f(x)

== [12# False now, since an item was added to the list

An object is called immutable if it cannot be changed in any way. For example, integers are immutable, since there’s no way to change them:

def bar():

(12) g(x)

== (12# 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 xhad 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.

Examples of immutable Data Types:




 tuple frozenset

Examples of mutable Data Types:



 set dict

Section 1.5: Collection Types

There are a number of collection types in Python. While types such as int and str hold a single value, collection types hold multiple values.


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 list can be created by enclosing values, separated by commas, in square brackets:


int_list [123]

string_list [‘abc’‘defghi’]

A list can be empty:

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:

mixed_list [1‘abc’True2.34None]

A list can contain another list as its element:

nested_list [[‘a’‘b’‘c’][123]]

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:

names [‘Alice’‘Bob’‘Craig’‘Diana’‘Eric’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). So, using the list from the above example:

print(names[-1]) # Eric print(names[-4]) # Bob

Lists are mutable, so you can change the values in a list:

names[0‘Ann’ print(names)

# Outputs [‘Ann’, ‘Bob’, ‘Craig’, ‘Diana’, ‘Eric’]

Besides, it is possible to add and/or remove elements from a list:

Append object to end of list with L.append(object), returns None.

names [‘Alice’‘Bob’‘Craig’‘Diana’‘Eric’] names.append(“Sia”)


# Outputs [‘Alice’, ‘Bob’, ‘Craig’, ‘Diana’, ‘Eric’, ‘Sia’]

Add a new element to list at a specific index. L.insert(indexobject)


# Outputs [‘Alice’, ‘Nikki’, ‘Bob’, ‘Craig’, ‘Diana’, ‘Eric’, ‘Sia’]

Remove the first occurrence of a value with L.remove(value), returns None


print(names) # Outputs [‘Alice’, ‘Nikki’, ‘Craig’, ‘Diana’, ‘Eric’, ‘Sia’]

Get the index in the list of the first item whose value is x. It will show an error if there is no such item.


Count length of list

len(names) 6

count occurrence of any item in list

[111234] a.count(1)


Reverse the list





Remove and return item at index (defaults to the last item) with L.pop([index]), returns the item

names.pop() # Outputs ‘Sia’

You can iterate over the list elements like below:

for element in my_list:

print (element)


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:

ip_address (‘’8080)

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:

one_member_tuple (‘Only member’,)


one_member_tuple ‘Only member’# No brackets

or just using tuple syntax


one_member_tuple tuple([‘Only member’])


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 ‘Arkansas’‘Little Rock’‘Colorado’‘Denver’‘California’‘Sacramento’‘Georgia’‘Atlanta’


To get a value, refer to it by its key:

ca_capital state_capitals[‘California’]

You can also get all of the keys in a dictionary and then iterate over them:

for in state_capitals.keys():

print(‘{} is the capital of {}’.format(state_capitals[k]k))

Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library can be used to convert between JSON and dictionaries.


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.

Defining a set is very similar to defining a dictionary:

first_names {‘Adam’‘Beth’‘Charlie’}

Or you can build a set using an existing list:

my_list [1,2,3]

my_set set(my_list)

Check membership of the set using in:

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, implementation- defined order.


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.

defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.

For example, consider the following dictionary

>>>state_capitals ‘Arkansas’‘Little Rock’‘Colorado’‘Denver’‘California’‘Sacramento’‘Georgia’‘Atlanta’


If we try to access a non-existent key, python returns us an error as follows

>>>state_capitals[‘Alabama’] Traceback (most recent call last):

File “”, line 1in <modulestate_capitals[‘Alabama’]


Let us try with a defaultdict. It can be found in the collections module.

>>>from collections import defaultdict

>>>state_capitals defaultdict(lambda‘Boston’)

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:

>>>state_capitals[‘Arkansas’‘Little Rock’




If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston


and returns the created values for existing key just like a normal dictionary

>>>state_capitals[‘Arkansas’‘Little Rock’