Python Keywords, Identifiers and Variables - Fundamentals

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 179

Python Keywords, Identifiers and

Variables – Fundamentals

Python Keywords.
Keywords are special words which are reserved and have a specific meaning.
Python has a set of keywords that cannot be used as variables in programs.

All keywords in Python are case sensitive. So, you must be careful while using them
in your code. We’ve just captured here a snapshot of the possible Python keywords.

It’s a long list to remember all at once. Our purpose of mentioning it here is only to
give you an initial idea of the available keywords. However, we’ll cover each of them
in the rest of the tutorials. You don’t need to jump onto memorizing them instead try
to learn to use them step by step.
One more point that you should note that the above list may change. The language
could get away with some of the old keywords and bring in new ones in future
releases.

Hence, to get hold of the up-to-date list, you can open Python shell and run the
following commands as shown in the below snippet.

help> keywords

Here is a list of the Python keywords. Enter any keyword to


get more help.

False def if
raise
None del import
return
True elif in
try
and else is
while
as except lambda
with
assert finally nonlocal
yield
break for not
class from or
continue global pass
help>
Alternatively, you can use Python’s keyword module, import it straight from the shell
and run the below commands to view the supported keywords.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
>>>
Back to list
Python Identifiers.
Python Identifiers are user-defined names to represent a variable, function, class,
module or any other object. If you assign some name to a programmable entity in
Python, then it is nothing but technically called an identifier.

Python language lays down a set of rules for programmers to create


meaningful identifiers.

Guidelines For Creating Identifiers In Python.


1. To form an identifier, use a sequence of letters either in lowercase (a to
z) or uppercase (A to Z). However, you can also mix up digits (0 to 9) or
an underscore (_) while writing an identifier.

For example – Names like shapeClass, shape_1, and upload_shape_to_db are all


valid identifiers.
2. You can’t use digits to begin an identifier name. It’ll lead to the syntax error.
For example – The name, 0Shape is incorrect, but shape1 is a valid identifier.
3. Also, the Keywords are reserved, so you should not use them as identifiers.
>>> for=1
SyntaxError: invalid syntax
>>> True=1
SyntaxError: can't assign to keyword
4. Python Identifiers can also not have special characters [‘.’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’] in
their formation. These symbols are forbidden.
>>> @index=0
SyntaxError: invalid syntax
>>> isPython?=True
SyntaxError: invalid syntax
5. Python doc says that you can have an identifier with unlimited length. But it is just
the half truth.
Using a large name (more than 79 chars) would lead to the violation of a rule set by
the PEP-8 standard. It says.
Limit all lines to a maximum of 79 characters.
Testing If An Identifier Is Valid.
You can test whether a Python identifier is valid or not by using
the keyword.iskeyword() function. It returns “True” if the keyword is correct
or “False” otherwise.
Please refer the below snippet.

>>> import keyword


>>> keyword.iskeyword("techbeamers")
False
>>> keyword.iskeyword("try")
True
>>>
Another useful method to check if an identifier is valid or not is by calling
the str.isidentifier() function. But it is only available in Python 3.0 and onwards.
>>> 'techbeamers'.isidentifier()
True
>>> '1techbeamers'.isidentifier()
False
>>> 'techbeamers.com'.isidentifier()
False
>>> 'techbemaers_com'.isidentifier()
True
Best Practices For Identifier Naming.
 Better have class names starting with a capital letter. All other identifiers
should begin with a lowercase letter.
 Declare private identifiers by using the (‘_’) underscore as their first letter.
 Don’t use ‘_’ as the leading and trailing character in an identifier. As Python
built-in types already use this notation.
 Avoid using names with only one character. Instead, make meaningful names.
 For example – While i = 1 is valid, but writing iter = 1 or index = 1 would
make more sense.
 You can use underscore to combine multiple words to form a sensible name.
 For example – count_no_of_letters.
Back to list
Python Variables.
A variable in Python represents an entity whose value can change as and when
required. Conceptually, it is a memory location which holds the actual value. And we
can retrieve the value from our code by querying the entity.

But it requires assigning a label to that memory location so that we can reference it.
And we call it as a variable in the programming terms.

Following are some of the key facts about Python variables. These will help
programmers to use them efficiently.

1. Variables don’t require declaration. However, you must initialize them before use.
For example –
test = 10
2. The above expression will lead to the following actions.
 Creation of an object to represent the value 10.
 If the variable (test) doesn’t exist, then it’ll get created.
 Association of the variable with the object, so that it can refer the value.
The variable ‘test’ is a reference to the value ’10’. Please refer to the illustration
shown below.
Example.
| ~~~~~ | ----- ~~~~~~~~~ ------- ****
( test ) ----- Reference ------- ** 10 **
| ~~~~~ | ----- ~~~~~~~~~ ------- ****
Variable ----- ~~~~~~~~~~ ------- Object
3. Whenever the expression changes, Python associates a new object (a chunk of
memory) to the variable for referencing that value. And the old one goes to the
garbage collector.
Example.
>>> test = 10
>>> id(test)
1716585200
>>> test = 11
>>> id(test)
1716585232
>>>
4. Also, for optimization, Python builds a cache and reuses some of the immutable
objects, such as small integers and strings.
5. An object is just a region of memory which can hold the following.
 The actual object values.
 A type designator to reflect the object type.
 The reference counter which determines when it’s OK to reclaim the object.
6. It’s the object which has a type, not the variable. However, a variable can hold
objects of different types as and when required.
Example.
>>> test = 10
>>> type(test)
<class 'int'>
>>> test = 'techbeamers'
>>> type(test)
<class 'str'>
>>> test = {'Python', 'C', 'C++'}
>>> type(test)
<class 'set'>
>>>

Python Statement, Expression &


Indentation

Python Statement

What Is A Statement?
A statement in Python is a logical instruction which Python interpreter can read and
execute. In Python, it could be an expression or an assignment statement.

The assignment statement is fundamental to Python. It defines the way an


expression creates objects and preserve them.

Let’s now find out more details on this topic.

What Is An Expression?
An expression is a type Python statement which contains a logical sequence of
numbers, strings, objects, and operators. The value in itself is a valid expression and
so is a variable.

Using expressions, we can perform operations like addition, subtraction,


concatenation and so on. It can also have a call to a function which evaluates
results.

Examples
# Using Arithmetic expressions
>>> ((10 + 2) * 100 / 5 - 200)
40.0
# Using functions in an expression
>>> pow(2, 10)
1024
# Using eval in an expression
>>> eval( "2.5+2.5" )
5.0
Back to top
Simple Assignment Statement
In a simple assignment, we create new variables, assign and change values. This
statement provides an expression and a variable name as a label to preserve the
value of the expression.

# Syntax
variable = expression
# LHS <=> RHS
Let’s now take a close look at three types of assignment statements in Python and
see what’s going on under the hood.

Case-1: Right-Hand Side (RHS) Is Just A Value-Based Expression.


Let’s consider the most basic form of assignment in Python.

>>> test = "Learn Python"


Python will create a string “Learn Python” in memory and assigns the name “test” to
it. You can confirm the memory address with the of a built-in function known as id().
>>> test = "Learn Python"
>>> id(test)
6589040
The number is the address of the location where the data lives in memory. Now,
here comes a few interesting points which you should know.

1. If you create another string with the same value, Python will create a new object
and assign it to a different location in memory. So this rule would apply to most of the
cases.
>>> test1 = "Learn Python"
>>> id(test1)
6589104
>>> test2 = "Learn Python"
>>> id(test2)
6589488
2. However, Python will also allocate the same memory address in the following two
scenarios.
 The strings don’t have whitespaces and contain less than 20 characters.
 In case of Integers ranging between -5 to +255.
This concept is known as Interning. Python does it to save memory.

Case-2: Right-Hand Side (RHS) Is A Current Python Variable.


Let’s take up the next type of assignment statement where the RHS is a current
Python variable.

>>> another_test = test


The above statement won’t trigger any new allocation in memory. Both the variables
would point to the same memory address. It’s like creating an alias to the existing
object. Let’s validate this by using the id() function.
>>> test = "Learn Python"
>>> id(test)
6589424
>>> another_test = test
>>> id(another_test)
6589424
Case-3: Right-Hand Side (RHS) Is An Operation.
In this type of statement, the result would depend on the outcome of the operation.
Let’s analyze it with the following examples.

>>> test = 2 * 5 / 10
>>> print(test)
1.0
>>> type(test)
<class 'float'>
In the above example, the assignment would lead to the creation of
a “float” variable.
>>> test = 2 * 5
>>> print(test)
10
>>> type(test)
<class 'int'>
In this example, the assignment would lead to the creation of an “int” variable.

Augmented Assignment Statement

You can combine arithmetic operators in assignments to form an augmented


assignment statement.
Check out the below examples for augmented assignment statement.

x += y
The above statement is a shorthand for the below simple statement.

x = x + y
Next one is a bit clearer example where we are appending new elements to the
tuple.

>>> my_tuple = (10, 20, 30)


>>> my_tuple += (40, 50,)
>>> print(my_tuple)
(10, 20, 30, 40, 50)
Next example is using a list of vowels. It is demonstrating the addition of missing
vowels to the list.

>>> list_vowels = ['a','e','i']


>>> list_vowels += ['o', 'u',]
>>> print(list_vowels)
['a', 'e', 'i', 'o', 'u']

Multi-Line Statement In Python


Usually, every Python statement ends with a newline character. However, we can
extend it over to multiple lines using the line continuation character (\).

And Python gives us two ways to enable multi-line statements in a program.

Explicit Line Continuation


When you right away use the line continuation character (\) to split a statement into
multiple lines.

Example
# Initializing a list using the multi-line statement
>>> my_list = [1, \
... 2, 3\
... ,4,5 \
... ]
>>> print(my_list)
[1, 2, 3, 4, 5]
# Evalulate an expression using a multi-line statement
>>> eval ( \
... " 2.5 \
... + \
... 3.5")
6.0
Back to top
Implicit Line Continuation
Implicit line continuation is when you split a statement using either of parentheses ( ),
brackets [ ] and braces { }. You need to enclose the target statement using the
mentioned construct.
Example
>>> result = (10 + 100
... * 5 - 5
... / 100 + 10
... )
>>> print(result)
519.95
Another Example
>>> subjects = [
... 'Maths',
... 'English',
... 'Science'
... ]
>>> print(subjects)
['Maths', 'English', 'Science']
>>> type(subjects)
<class 'list'>
Back to top
Python Indentation
Many of the high-level programming languages like C, C++, C# use braces { } to
mark a block of code. Python does it via indentation.

A code block which represents the body of a function or a loop begins with the
indentation and ends with the first unindented line.

How Many Spaces Is An Indent In Python?


Python style guidelines (PEP 8) states that you should keep indent size of four.
However, Google has its unique style guideline which limits indenting up to two
spaces. So you too can choose a different style, but we recommend to follow the
PEP8.

Why Is Indentation So Crucial In Python?


Most of the programming languages provide indentation for better code formatting
and don’t enforce to have it.

However, in Python, it is mandatory to obey the indentation rules. Typically, we


indent each line by four spaces (or by the same amount) in a block of code.

In the examples of the previous sections, you might have seen us writing simple
expression statements which didn’t have the indentation.

However, for creating compound statements, the indentation will be utmost


necessary.

Example
def demo_routine(num):
print('I am a demo function')
if num % 2 == 0:
return True
else:
return False

num = int(input('Enter a number:'))


if demo_routine(num) is True:
print(num, 'is an even number')
else:
print(num, 'is an odd number')
Now, also see a scenario when undesired indentation causes an error. So let’s try
indenting a simple expression statement.

>>> 6*5-10
File "<stdin>", line 1
6*5-10
^
IndentationError: unexpected indent

How to Write Comment and Multiline Comment in


Python

How To Use Comments In Python?


Commenting is an art of expressing what a program is going to do at a very high-
level. These are tagged lines of text to annotate a piece of code. In Python, we can
apply two styles of comment: single-line and multiline.
Single-Line Python Comment
You might prefer to use a single line Python comment when there is need of short,
quick comments for debugging. Single-line comments begin with a pound (#) symbol
and automatically ends with an EOL (end of the line).

# Good code is self-documenting.

print("Learn Python Step by Step!")


While putting a comment, make sure your comment is at the same indent level as
the code beneath it. For example, you might annotate a function definition which
doesn’t have any indentation. But the function could have blocks of code indented at
multiple levels. So take care of the alignment, when you comment inside the internal
code blocks.

# Define a list of months


months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul','Aug','Sep','Oct','Nov','Dec']

# Function to print the calender months


def showCalender(months):
# For loop that traverses the list and prints the name of
each month
for month in months:
print(month)

showCalender(months)

Multiline Python Comment


Python allows comments to span across multiple lines. Such comments are known
as multiline or block comments. You can use this style of commenting to describe
something more complicated.

This extended form of comments applies to some or all of the code that follows. Here
is an example to use the multiline Python comment.

Using The Hash (#) Mark


To add multiline comments, you should begin each line with the pound (#) symbol
followed by a single space. You can divide a comment into paragraphs. Just add an
empty line with a hash mark between each para.
Note: The symbol (#) is also known as the octothorpe. The term came from a group
of engineers at Bell Labs while working on a first of the touch-tone keypads project.
# To Learn any language you must follow the below rules.
# 1. Know the basic syntax, data types, control structures and
conditional statements.
# 2. Learn error handling and file I/O.
# 3. Read about advanced data structures.
# 4. Write functions and follow OOPs concepts.

def main():
print("Let's start to learn Python.")
...

Docstring In Python
Python has the documentation strings (or docstrings) feature. It gives programmers
an easy way of adding quick notes with every Python module, function, class, and
method.

You can define a docstring by adding it as a string constant. It must be the first
statement in the object’s (module, function, class, and method) definition.

The docstring has a much wider scope than a Python comment. Hence, it should
describe what the function does, not how. Also, it is a good practice for all functions
of a program to have a docstring.

How To Define Docstring In Python?


You can define a docstring with the help of triple-quotation mark. Add one in the
beginning and second at the end of the string. Just like multiline comments,
docstring can also overlap to multiple lines.

Note: The strings defined using triple-quotation mark are docstring in Python.


However, it might appear to you as a regular comment.
What Is The Difference Between A Comment And The Docstring?
The strings beginning with triple quotes are still regular strings except the fact that
they could spread to multiple lines. It means they are executable statements. And if
they are not labeled, then they will be garbage collected as soon as the code
executes.

The Python interpreter won’t ignore them as it does with the comments. However, if
such a string is placed immediately after a function or class definition or on top of a
module, then they turn into docstrings. You can access them using the following
special variable.
myobj.__doc__
Example
def theFunction():
'''
This function demonstrate the use of docstring in Python.
'''
print("Python docstrings are not comments.")

print("\nJust printing the docstring value...")


print(theFunction.__doc__)

Python Data Types – Learn from Basic to


Advanced

In general, a data type defines the format, sets the upper & lower bounds of the data
so that a program could use it appropriately. However, Python data types are just
more than that. In Python, we don’t need to declare a variable with explicitly
mentioning the data type. This feature is famously known as dynamic typing.

Python determines the type of a literal directly from the syntax at runtime. For
example – the quotes mark the declaration of a string value, square brackets
represent a list and curly brackets for a dictionary. Also, the non-decimal numbers
will get assigned to Integer type whereas the ones with a decimal point will be a float.

Everything including variables, functions, modules in Python is an object. Another


interesting fact is that variables don’t have types instead they are just labels in
Python. It is the value which gets associated with a type. Hence, the same variable,
the label can refer values of different Python data types.

Below is the list of important data types that are commonly used in Python. We’ll
discuss each of them with examples.

1. Booleans
2. Numbers
3. Strings
4. Bytes
5. Lists
6. Tuples
7. Sets
8. Dictionaries
Python Data Types From Basic To Advanced

1. Booleans
A boolean is such a data type that almost every programming language has, and so
is Python. Boolean in Python can have two values – True or False. These values are
constants and can be used to assign or compare boolean values. Follow a simple
example given below.
condition = False
if condition == True:
print("You can continue with the prpgram.")
else:
print("The program will end here.")
While making boolean conditions in Python, we can skip the explicit comparison in
our code. And we’ll still get the same behavior.

condition = False
if condition:
print("You can continue with the prpgram.")
else:
print("The program will end here.")
The above code will yield the same output as gave the previous one. It is because of
the statement

if condition:
is equivalent to,

if condition == True:
Next, an expression in Python can also produce a boolean result.

For example – The expression in a condition block will yield a boolean value. Python
creates boolean contexts to evaluate expressions.
Whatever be the expression is, Python will use the boolean context to determine its
truth value. Since Python has many data types, so they will operate with their own
rules to find the result in a boolean context.

>>> str = "Learn Python"

>>> len(str)
12
>>> len(str) == 12
True

>>> len(str) != 12
False
In some cases, the boolean constants “True” and “False” might also act as
numbers.
>>> A, B = True + 0, False + 0
>>> print(A, B)
1 0
>>> type(A), type(B)
(<class 'int'>, <class 'int'>)
It is evident from the above example that True is 1 and the value of False is 0. And
they will turn into numbers during arithmetic operations.
Back to top
2. Numbers
Numbers are one of the most prominent Python data types. Unlike many languages
which have only integers and floats, Python introduces complex as a new type of
numbers.

Here are a few points for you to ponder.

 The numbers in Python are classified using the following keywords.


 int, float, and complex.
 Python has a built-in function type() to determine the data type of a variable or
the value.
 Another built-in function isinstance() is there for testing the type of an object.
 In Python, we can add a “j” or “J” after a number to make it imaginary or
complex.
Example.
num = 2
print("The number (", num, ") is of type", type(num))

num = 3.0
print("The number (", num, ") is of type", type(num))

num = 3+5j
print("The number ", num, " is of type", type(num))
print("The number ", num, " is complex number?",
isinstance(3+5j, complex))
#Output
The number ( 2 ) is of type <class 'int'>
The number ( 3.0 ) is of type <class 'float'>
The number (3+5j) is of type <class 'complex'>
The number (3+5j) is complex number? True
 To form a complex number, we can even use the type as a constructor. See
the example below.
>>> complex(1.2,5)
(1.2+5j)
 Integers in Python don’t have any size limitation as long as the required
memory is available.
>>> num = 1234567890123456789
>>> num.bit_length()
61
>>> num
1234567890123456789
>>> num =
12345678901234567891234567890123456789123456789012345678912345
67890123456789
>>> num.bit_length()
250
>>> num
12345678901234567891234567890123456789123456789012345678912345
67890123456789
 A float type number can have precision up to 15 decimal places.
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024,
max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021,
min_10_exp=-307, dig=15, mant_dig=53,
epsilon=2.220446049250313e-16, radix=2, rounds=1)
>>> sys.float_info.dig
15
Note – The dig in above example is the maximum number of decimal digits in a float.
Back to top
3. Strings
A sequence of one or more characters enclosed within either single quotes ‘ or
double quotes ” is considered as String in Python. Any letter, a number or a symbol
could be a part of the sting.

Python also supports multi-line strings which require a triple quotation mark at the
start and one at the end.

>>> str = 'A string wrapped in single quotes'


>>> str
'A string wrapped in single quotes'
>>> str = "A string enclosed within double quotes"
>>> str
'A string enclosed within double quotes'
>>> str = """A multiline string
starts and ends with
a triple quotation mark."""
>>> str
'A multiline string\nstarts and ends with\na triple quotation
mark.'
Also, the strings in Python are immutable. It means the memory will be allocated
once and re-used thereafter.

>>> A = 'Python3'
>>> id(A)
56272968
>>> B = A
>>> id(B)
56272968
You can see the second string shares the same address as the first one does.

Python has two popular versions, namely 2.7 and 3.4. Most programmers around the
globe use either of them. The strings in Python 2 are by default non-Unicode (ASCII)
but also have support for Unicode.
On the other hand, Python 3 strings are all Unicode (UTF-8).

Strings in Python 2.
>>> print(type('Python String'))
<type 'str'>
>>> print(type(u'Python Unicode String'))
<type 'unicode'>
Strings in Python 3.
>>> print(type('Python String'))
<class 'str'>
>>> print(type(u'Python Unicode String'))
<class 'str'>
Python allows slicing strings using a special square-bracket syntax to extract a
substring. See the example below.

>>> str = "Learn Python"


>>> first_5_chars = str[0:5]
>>> print(first_5_chars)
Learn
>>> substr_from_2_to_5 = str[1:5]
>>> print(substr_from_2_to_5)
earn
>>> substr_from_6_to_end = str[6:]
>>> print(substr_from_6_to_end)
Python
>>> last_2_chars = str[-2:]
>>> print(last_2_chars)
on
>>> first_2_chars = str[:2]
>>> print(first_2_chars)
Le
>>> two_chars_before_last = str[-3:-1]
>>> print(two_chars_before_last)
ho
+ Must Read – Python String Fundamentals
Back to top
4. Bytes
The byte is an immutable type in Python. It can store a sequence of bytes (each 8-
bits) ranging from 0 to 255. Similar to an array, we can fetch the value of a single
byte by using the index. But we can not modify the value.

Here are a few differences between a byte and the string.

 Byte objects contain a sequence of bytes whereas the strings store sequence
of characters.
 The bytes are machine-readable objects whereas the strings are just in
human-readable form.
 Since the byte is machine-readable, so they can be directly stored to the disk.
Whereas, the strings first need to encoded before getting on to the disk.
>>> # Make an empty bytes object (8-bit bytes)
>>> empty_object = bytes(16)
>>> print(type(empty_object))
<class 'bytes'>
>>> print(empty_object)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00'
One scenario, where bytes matter is when carrying out I/O operations with buffering
enabled. For example, we have a program which is continuously receiving the data
over the network. It parses the date after waiting for the message headers and
terminators to appear in the stream. It keeps appending the incoming bytes to a
buffer.

With Python byte object, it is easy to program the above scenario using the below
pseudo code.

buf = b''
while message_not_complete(buf):
buf += read_from_socket()
In the later sections of this tutorial, we’ll see the byte to string conversion and vice-
versa.

Back to top
5. Lists
Python list is an array like construct which stores arbitrarily typed objects in an
ordered sequence. It is very flexible and does not have a fixed size. Index in a list
begins with zero in Python.

 It is a heterogeneous collection of items of varied data types. For example, a


list object can store the files in a folder, or the employee data in a company etc.
Python List Syntax
Lists in Python can be declared by placing elements inside square brackets separated
by commas.
>>> assorted_list = [True, False, 1, 1.1, 1+2j, 'Learn',
b'Python']
>>> first_element = assorted_list[0]
>>> print(first_element)
True
>>> print(assorted_list)
[True, False, 1, 1.1, (1+2j), 'Learn', b'Python']
>>> for item in assorted_list:
print(type(item))

<class 'bool'>
<class 'bool'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bytes'>
 List objects are mutable. Python allows modifying a list or its elements via
assignments as well as through the built-in list methods.
>>> simpleton = ['Learn', 'Python', '2']
>>> id(simpleton)
56321160
>>> simpleton
['Learn', 'Python', '2']
>>> simpleton[2] = '3'
>>> id(simpleton)
56321160
>>> simpleton
['Learn', 'Python', '3']
Nesting Inside A List
Interestingly, a list can contain another list. Such a list is called as the nested list.

>>> nested = [[1,1,1], [2,2,2], [3,3,3]]


>>> for items in nested:
for item in items:
print(item, end=' ')

1 1 1 2 2 2 3 3 3
Slicing A List
The list is also one of the Python data types which supports slicing like we
learned previously with Strings. With the slicing operator [ ], we can extract an
element or a bunch of them from a list.

>>> languages = ['C', 'C++', 'Python', 'Java', 'Go',


'Angular']
>>> print('languages[0:3] = ', languages[0:3])
languages[0:3] = ['C', 'C++', 'Python']
>>> print('languages[2:] = ', languages[2:])
languages[2:] = ['Python', 'Java', 'Go', 'Angular']
+ Attempt this Quiz – Python List, Tuple, & Dict
Back to top
6. Tuples
A tuple is a heterogeneous collection of Python objects separated by commas. It
means objects of different data types can co-exist in a tuple. The tuple and a list are
somewhat similar as they share the following traits.

 Both objects are an ordered sequence.


 They enable indexing and repetition.
 Nesting is allowed.
 They can store values of different types.
Python Tuple Syntax
Define a tuple using enclosing parentheses () having its elements separated by
commas inside.

Example – Define A Tuple


# Defining a tuple without any element
pure_tuple = ()
print (pure_tuple)
# Output- ()
Example – Nested Tuples
# Creating a tuple with nested tuples
first_tuple = (3, 5, 7, 9)
second_tuple = ('learn', 'python 3')
nested_tuple = (first_tuple, second_tuple)
print(nested_tuple)
# Output - ((3, 5, 7, 9), ('learn', 'python 3'))
Example – Repetition In Tuples
# How does repetition work with tuples
sample_tuple = ('Python 3',)*3
print(sample_tuple)
# Output - ('Python 3', 'Python 3', 'Python 3')
Example – Slicing In Tuples
# How does slicing work with tuples

sample_tuple = (0 ,1, 2, 3, 4)

tuple_without_first_item = sample_tuple[1:]
print(tuple_without_first_item)

tuple_reverse = sample_tuple[::-1]
print(tuple_reverse)

tuple_from_3_to_5 = sample_tuple[2:4]
print(tuple_from_3_to_5)
# Output - 
(1, 2, 3, 4)
(4, 3, 2, 1, 0)
(2, 3)
Important note – While slicing in the above example, The “2” means to start at
the third element in the tuple (the slicing index begins at 0). The “4” means to end at
the fifth element in the tuple but to exclude it.
How Does A Tuple Differ From The List?
Tuples do differ a bit from the list as they are immutable. Python does not allow to
modify a tuple after it is created. We can not add or remove any element later.
Instead, Python expects us to create a new one with the updated sequence of
elements.

What If A Tuple Has Mutable Objects As Elements?


Here, comes the surprise. Modifying a tuple is forbidden. But Python doesn’t enforce
it on the elements. It means we can update them if they are mutable objects.

Why Need A Tuple As One Of The Python Data Types?


Here are a couple of thoughts in support of tuples.

 Python uses tuples to return multiple values from a function.


 Tuples are more lightweight than lists.
 It works as a single container to stuff multiple things.
 We can use them as a key in a dictionary.
Back to top
7. Sets
Amongst all the Python data types, the set is one which supports mathematical
operations like union, intersection, symmetric difference etc.

A set is an unordered collection of unique and immutable objects. Its definition starts


with enclosing braces { } having its items separated by commas inside.

Since the set derives its implementation from the “Set” in mathematics, so it can’t
have multiple occurrences of the same element.

Why Need A Set?


The set type has a significant advantage over a list. It implements a highly optimized
method that checks whether the container hosts a specific element or not. The
mechanism used here is based on a data structure known as a hash table.

Creating A Set
To create a set, call the built-in set() function with a sequence or any iterable object.
>>> sample_set = set("Python data types")
>>> type(sample_set)
<class 'set'>
>>> sample_set
{'e', 'y', 't', 'o', ' ', 'd', 's', 'P', 'p', 'n', 'h', 'a'}
Another simpler way is to specify the elements enclosed in curly braces {}.

>>> another_set = {'red', 'green', 'black'}


>>> type(another_set)
<class 'set'>
>>> another_set
{'red', 'green', 'black'}
Frozen Set
A frozen set is a processed form of the traditional set. It is immutable and only
supports methods and operators that executes without altering the frozen set used in
the context.

# An empty frozenset
>>> frozenset()
frozenset()
>>> cities = {"New York City", "Saint Petersburg", "London",
"Munich", "Paris"}
>>> fset = frozenset(cities)
>>> type(fset)
<class 'frozenset'>
Now, see a full example to highlight the difference between a normal and the frozen
set.

# Python program to demonstrate frozen set

# A standard set
sample_set = {"red", "green"}

# Add an element to the standard set


sample_set.add("black")

print("Standard Set")
print(sample_set)

# A frozen set
frozen_set = frozenset(["red", "green", "black"])

print("Frozen Set")
print(frozen_set)
# Output -
Standard Set
{'green', 'red', 'black'}
Frozen Set
frozenset({'green', 'red', 'black'})

8. Dictionaries
A dictionary in Python is an unordered collection of key-value pairs. It’s a built-in
mapping type in Python where keys map to values. These key-value pairs provide an
intuitive way to store data.

Why Need A Dictionary?


The dictionary solves the problem of efficiently storing a large data set. Python has
made the dictionary object highly optimized for retrieving data.

Creating A Dictionary
Python syntax for creating dictionaries use braces {} where each item appears as
a pair of keys and values. The key and value can be of any Python data types.
>>> sample_dict = {'key':'value', 'jan':31, 'feb':28,
'mar':31}
>>> type(sample_dict)
<class 'dict'>
>>> sample_dict
{'mar': 31, 'key': 'value', 'jan': 31, 'feb': 28}
Accessing Dictionaries Elements With Keys
Dictionaries act like a database. Here, we don’t use a number to get a particular
index value as we do with a list. Instead, we replace it with a key and then use the
key to fetch its value.

>>> sample_dict['jan']
31
>>> sample_dict['feb']
28
Dictionaries Methods To Access Elements
Python exposes following built-in dictionary functions.

 keys() – It isolates the keys from a dictionary.


 values() – It isolates the values from a dictionary.
 items() – It returns the items in a list style of (key, value) pairs.
>>> sample_dict.keys()
dict_keys(['mar', 'key', 'jan', 'feb'])
>>> sample_dict.values()
dict_values([31, 'value', 31, 28])
>>> sample_dict.items()
dict_items([('mar', 31), ('key', 'value'), ('jan', 31),
('feb', 28)])
Modifying A Dictionary (Add/Update/Delete)
Since the dictionary object is mutable, so we can call add, update and delete
operations on a dictionary object.

>>> sample_dict['feb'] = 29
>>> sample_dict
{'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}
>>> sample_dict.update({'apr':30})
>>> sample_dict
{'apr': 30, 'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}
>>> del sample_dict['key']
>>> sample_dict
{'apr': 30, 'mar': 31, 'jan': 31, 'feb': 29}
Python Strings, Functions and Examples

Learn The Basics Of Python Strings


Contents [hide]
 1 How to Create Strings in Python?
 2 Index and Slice Strings in Python
o 2.1 Access Individual Characters of a String
o 2.2 Slice a String in Python
o 2.3 Python Strings – Common Error Codes
 3 Modify/Delete a String in Python
 4 String Operators in Python
o 4.1 Concatenation (+)
o 4.2 Repetition (*)
o 4.3 Slicing [ ]
o 4.4 Range Slicing [x:y]
o 4.5 Membership (in)
o 4.6 Membership (not in)
o 4.7 Iterating (for)
o 4.8 Raw String (r/R)
 5 String Formatting Operators in Python
o 5.1 Python Escape Characters
 5.1.1 List of Escape Characters
o 5.2 Python Format Characters
 5.2.1 List of Format Symbols
 6 Unicode String support in Python
 7 Built-in String Functions in Python
o 7.1 Conversion Functions
o 7.2 Comparison Functions – Part1
o 7.3 Comparison Functions – Part2
o 7.4 Padding Functions
o 7.5 Search Functions
o 7.6 String Substitution Functions
o 7.7 Misc String Functions
How To Create Strings In Python?
Creating strings is easy as you only need to enclose the characters either in single or
double-quotes.

In the following example, we are providing different ways to initialize strings.

To share an important note that you can also use triple quotes to create strings.
However, programmers use them to mark multi-line strings and docstrings.

# Python string examples - all assignments are identical.


String_var = 'Python'
String_var = "Python"
String_var = """Python"""

# with Triple quotes Strings can extend to multiple lines


String_var = """ This document will help you to
explore all the concepts
of Python Strings!!! """

# Replace "document" with "tutorial" and store in another


variable
substr_var = String_var.replace("document", "tutorial")
print (substr_var)
Index And Slice Strings In Python
Access Individual Characters Of A String
You need to know the index of a character to retrieve it from the String.

Like most programming languages, Python allows to index from the zeroth position
in Strings. But it also supports negative indexes. Index of ‘-1’ represents the last
character of the String. Similarly, using ‘-2’, we can access the penultimate element
of the string and so on.

sample_str = 'Python String'

print (sample_str[0]) # return 1st character


# output: P

print (sample_str[-1]) # return last character


# output: g

print (sample_str[-2]) # return last second character


# output: n
Slice A String In Python
To retrieve a range of characters in a String, we use ‘slicing operator,’ the colon ‘:’
sign. With the slicing operator, we define the range as [a:b]. It’ll let us print all the
characters of the String starting from index ‘a’ up to char at index ‘b-1’. So the char at
index ‘b’ is not a part of the output.
sample_str = 'Python String'
print (sample_str[3:5]) #return a range of character
# ho
print (sample_str[7:]) # return all characters from index
7
# String
print (sample_str[:6]) # return all characters before
index 6
# Python
print (sample_str[7:-4])
# St
Next, we have a no. of Python tutorials/quizzes/interview questions on this blog. If you
like to try them, then refer to any of the posts listed below.
Suggested Reading:
☛ 100+ Python Interview Questions
TOC
Python Strings – Common Error Codes
1- If we try to retrieve characters at out of range index, then ‘IndexError’ exception
will be raised.
sample_str = "Python Supports Machine Learning."
print (sample_str[1024]) #index must be in range

# IndexError: string index out of range


2- String index must be of the integer data type. You should not use a float or any
other data type for this purpose. Otherwise, the Python subsystem will flag a
TypeError exception as it detects a data type violation for the string index.
sample_str = "Welcome post"
print (sample_str[1.25]) #index must be an integer

# TypeError: string indices must be integers


Modify/Delete A String In Python
Python Strings are by design immutable. It suggests that once a String binds to a
variable, it can’t be modified.

If you want to update the String, then re-assign a new String value to the same
variable.

sample_str = 'Python String'


sample_str[2] = 'a'

# TypeError: 'str' object does not support item assignment

sample_str = 'Programming String'


print (sample_str)
# Output=> Programming String
Similarly, we cannot modify the Strings by deleting some characters from it. Instead,
we can remove the Strings altogether by using the ‘del’ command.

sample_str = "Python is the best scripting language."


del sample_str[1]
# TypeError: 'str' object doesn't support item deletion

del sample_str
print (sample_str)
# NameError: name 'sample_str' is not defined
Suggested Reading:
☛ Python Programming Interview Questions
TOC
String Operators In Python
Concatenation (+)
It combines two strings into one.

# example
var1 = 'Python'
var2 = 'String'
print (var1+var2)
# PythonString
Repetition (*)
This operator creates a new string by repeating it a given number of times.

# example
var1 = 'Python'
print (var1*3)
# PythonPythonPython
Slicing [ ]
The slice operator prints the character at a given index.

# example
var1 = 'Python'
print (var1[2])
# t
Range Slicing [X:y]
It prints the characters present in the given range.

# example
var1 = 'Python'
print (var1[2:5])
# tho
Membership (In)
This operator returns ‘True’ value if the character is present in the given String.

# example
var1 = 'Python'
print ('n' in var1)
# True
Membership (Not In)
It returns ‘True’ value if the character is not present in the given String.

# example
var1 = 'Python'
print ('N' not in var1)
# True
Iterating (For)
With this operator, we can iterate through all the characters of a string.

# example
for var in var1: print (var, end ="")
# Python
Raw String (R/R)
We can use it to ignore the actual meaning of Escape characters inside a string. For
this, we add ‘r’ or ‘R’ in front of the String.

# example
print (r'\n')
# \n
print (R'\n')
# \n
TOC
String Formatting Operators In Python
Python Escape Characters
An Escape sequence starts with a backslash (\), which signals the compiler to treat it
differently. Python subsystem automatically interprets an escape sequence
irrespective of it is in a single-quoted or double-quoted Strings.

Let’s discuss an example-One of an important Escape sequence is to escape a


single-quote or a double-quote.

Suppose we have a string like – Python is a “widely” used language.

The double-quote around the word “widely” disguise python that the String ends up
there.
We need a way to tell Python that the double-quotes inside the string are not the
string markup quotes. Instead, they are the part of the String and should appear in
the output.

To resolve this issue, we can escape the double-quotes and single-quotes as:

print ("Python is a "widely" used language")

# SyntaxError: invalid syntax

# After escaping with double-quotes

print ("Python is a \"widely\" used language")

# Output: Python is a "widely" used language


List Of Escape Characters
Here is the complete list of escape characters that are represented using backslash
notation.

Escape Char
Name
\\
Backslash (\)
\”
Double-quote (“)
\a
ASCII bell (BEL)
\b
ASCII backspace (BS)
\cx or \Cx
Control-x
\f
ASCII Form feed (FF)
\n
ASCII linefeed (LF)
\N{name}
Character named name in the Unicode database (Unicode only)
\r
Carriage Return (CR)
\t
Horizontal Tab (TAB)
\uxxxx
A character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx
A character with 32-bit hex value xxxxxxxx (Unicode only)
\v
ASCII vertical tab (VT)
\ooo
Characters with octal value ooo
\xnn
A character with hex value nn where n can be anything from the range 0-9, a-f, or A-F.
TOC
Python Format Characters
String ‘%’ operator issued for formatting Strings. We often use this operator with the
print() function.

Here’s a simple example.

print ("Employee Name: %s,\nEmployee Age:%d" % ('Ashish',25))

# Employee Name: Ashish,


# Employee Age: 25
List Of Format Symbols
Following is the table containing the complete list of symbols that you can use with
the ‘%’ operator.

Symbol
Conversion
%c
character
%s
string conversion via str() before formatting
%i
signed decimal integer
%d
signed decimal integer
%u
unsigned decimal integer
%o
octal integer
%x
hexadecimal integer (lowercase letters)
%X
hexadecimal integer (UPPER-case letters)
%e
exponential notation (with lowercase ‘e’)
%E
exponential notation (with UPPER-case ‘E’)
%f
floating-point real number
%g
the shorter of %f and %e
%G
the shorter of %f and %E

Unicode String Support In Python


Regular Strings stores as the 8-bit ASCII value, whereas Unicode String follows the
16-bit ASCII standard. This extension allows the strings to include characters from
the different languages of the world. In Python, the letter ‘u’ works as a prefix to
distinguish between Unicode and usual strings.

print (u' Hello Python!!')

#Hello Python
Suggested Reading:
☛ Python Online Practice Test
TOC
Built-In String Functions In Python
Conversion Functions
1. capitalize() – Returns the string with the first character capitalized and rest of the
characters in lower case.
var = 'PYTHON'
print (var.capitalize())
# Python
2. lower() – Converts all the characters of the String to lowercase
var = 'TechBeamers'
print (var.lower())
# techbeamers
3. upper() – Converts all the characters of the String to uppercase
var = 'TechBeamers'
print (var.upper())
# TECHBEAMERS
4. swapcase() – Swaps the case of every character in the String means that lowercase
characters got converted to uppercase and vice-versa.
var = 'TechBeamers'
print (var.swapcase())
# tECHbEAMERS
5. title() – Returns the ‘titlecased’ version of String, which means that all words start
with uppercase and the rest of the characters in words are in lowercase.
var = 'welcome to Python programming'
print (var.title())
# Welcome To Python Programming
6. count( str[, beg [, end]]) – Returns the number of times substring ‘str’ occurs in the
range [beg, end] if beg and end index are given else the search continues in full
String Search is case-sensitive.
var='TechBeamers'
str='e'
print (var.count(str))
# 3
var1='Eagle Eyes'
print (var1.count('e'))
# 2
var2='Eagle Eyes'
print (var2.count('E',0,5))
# 1
TOC
Comparison Functions – Part1
1. islower() – Returns ‘True’ if all the characters in the String are in lowercase. If any
of the char is in uppercase, it will return False.
var='Python'
print (var.islower())
# False

var='python'
print (var.islower())
# True
2. isupper() – Returns ‘True’ if all the characters in the String are in uppercase. If any
of the char is in lowercase, it will return False.
var='Python'
print (var.isupper())
# False

var='PYTHON'
print (var.isupper())
# True
3. isdecimal() – Returns ‘True’ if all the characters in String are decimal. If any
character in the String is of other data-type, it will return False.
Decimal characters are those from the Unicode category Nd.

num=u'2016'
print (num.isdecimal())
# True
4. isdigit() – Returns ‘True’ for any char for which isdecimal() would return ‘True and
some characters in the ‘No’ category. If there are any characters other than these, it
will return False’.
Precisely, digits are the characters for which Unicode property includes:
Numeric_Type=Digit or Numeric_Type=Decimal.

For example, superscripts are digits, but fractions not.

print ('2'.isdigit())
# True

print ('²'.isdigit())
# True
Comparison Functions – Part2
1. isnumeric() – Returns ‘True’ if all the characters of the Unicode String lie in any
one of the categories Nd, No, and NI.
If there are any characters other than these, it will return False.

Precisely, Numeric characters are those for which Unicode property includes:
Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

num=u'2016'
print (num.isnumeric())
# True

num=u'year2016'
print (num.isnumeric())
# False
2. isalpha() – Returns ‘True’ if String contains at least one character (non-empty
String), and all the characters are alphabetic, ‘False’ otherwise.
print ('python'.isalpha())
# True

print ('python3'.isalpha())
# False
3. isalnum() – Returns ‘True’ if String contains at least one character (non-empty
String), and all the characters are either alphabetic or decimal digits, ‘False’
otherwise.
print ('python'.isalnum())
# True
print ('python3'.isalnum())
# True
TOC
Padding Functions
1. rjust(width[,fillchar]) – Returns string filled with input char while pushing the
original content on the right side.
By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler
character.

var='Python'
print (var.rjust(10))
# Python

print (var.rjust(10,'-'))
# ----Python
2. ljust(width[,fillchar]) – Returns a padded version of String with the original String
left-justified to a total of width columns
By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler
character.

var='Python'
print (var.ljust(10))
# Python

print (var.ljust(10,'-'))
# Python----
3. center(width[,fillchar]) – Returns string filled with the input char while pushing the
original content into the center.
By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler
character.

var='Python'
print (var.center(20))
# Python
print (var.center(20,'*'))
# *******Python*******
4. zfill(width) – Returns string filled with the original content padded on the left with
zeros so that the total length of String becomes equal to the input size.
If there is a leading sign (+/-) present in the String, then with this function, padding
starts after the symbol, not before it.

var='Python'
print (var.zfill(10))
# 0000Python

var='+Python'
print (var.zfill(10))
# +000Python
TOC
Search Functions
1. find(str [,i [,j]]) – Searches for ‘str’ in complete String (if i and j not defined) or in a
sub-string of String (if i and j are defined).This function returns the index if ‘str’ is
found else returns ‘-1’.
Here, i=search starts from this index, j=search ends at this index.

See more details – Python String Find()


var="Tech Beamers"
str="Beam"
print (var.find(str))
# 5

var="Tech Beamers"
str="Beam"
print (var.find(str,4))
# 5

var="Tech Beamers"
str="Beam"
print (var.find(str,7))
# -1
2. index(str[,i [,j]]) – This is same as ‘find’ method. The only difference is that it raises
the ‘ValueError’ exception if ‘str’ doesn’t exist.
var='Tech Beamers'
str='Beam'
print (var.index(str))
# 5

var='Tech Beamers'
str='Beam'
print (var.index(str,4))
# 5

var='Tech Beamers'
str='Beam'
print (var.index(str,7))
# ValueError: substring not found
3. rfind(str[,i [,j]]) – This is same as find() just that this function returns the last index
where ‘str’ is found. If ‘str’ is not found, it returns ‘-1’.
var='This is a good example'
str='is'
print (var.rfind(str,0,10))
# 5

print (var.rfind(str,10))
# -1
4. count(str[,i [,j]]) – Returns the number of occurrences of substring ‘str’ in the
String. Searches for ‘str’ in the complete String (if i and j not defined) or in a sub-
string of String (if i and j are defined).
Where: i=search starts from this index, j=search ends at this index.

var='This is a good example'


str='is'
print (var.count(str))
# 2

print (var.count(str,4,10))
# 1
TOC
String Substitution Functions
1. replace(old,new[,count]) – Replaces all the occurrences of substring ‘old’ with ‘new’
in the String.
If the count is available, then only ‘count’ number of occurrences of ‘old’ will be
replaced with the ‘new’ var.

Where old =substring to replace, new =substring

var='This is a good example'


str='was'
print (var.replace('is',str))
# Thwas was a good exampleprint (var.replace('is',str,1))
# Thwas is a good example
2. split([sep[,maxsplit]]) – Returns a list of substring obtained after splitting the String
with ‘sep’ as a delimiter.
Where, sep= delimiter, the default is space, maxsplit= number of splits to be done

var = "This is a good example"


print (var.split())
# ['This', 'is', 'a', 'good', 'example']print (var.split(' ',
3))
# ['This', 'is', 'a', 'good example']
3. splitlines(num) – Splits the String at line breaks and returns the list after removing
the line breaks.
Where num = if this is a positive value. It indicates that line breaks will appear in the
returned list.

var='Print new line\nNextline\n\nMove again to new line'


print (var.splitlines())
# ['Print new line', 'Nextline', '', 'Move again to new
line']print (var.splitlines(1))
# ['Print new line\n', 'Nextline\n', '\n', 'Move again to new
line']
4. join(seq) – Returns a String obtained after concatenating the sequence ‘seq’ with a
delimiter string.
Where: the seq= sequence of elements to join

seq=('ab','bc','cd')
str='='
print (str.join(seq))
# ab=bc=cd
TOC
Misc String Functions
1. lstrip([chars]) – Returns a string after removing the characters from the beginning
of the String.
Where: Chars=this is the character to be trimmed from the String.

The default is whitespace character.

var=' This is a good example '


print (var.lstrip())
# This is a good example
var='*****This is a good example*****'
print (var.lstrip('*'))
# This is a good example**********
2. rstrip() – Returns a string after removing the characters from the End of the String.
Where: Chars=this is the character to be trimmed from the String. The default is
whitespace character.

var=' This is a good example '


print (var.rstrip())
# This is a good example
var='*****This is a good example*****'
print (var.lstrip('*'))
# *****This is a good example
3. rindex(str[,i [,j]]) – Searches for ‘str’ in the complete String (if i and j not defined) or
in a sub-string of String (if i and j are defined). This function returns the last index
where ‘str’ is available.
If ‘str’ is not there, then it raises a ValueError exception.

Where: i=search starts from this index, j=search ends at this index.

var='This is a good example'


str='is'
print (var.rindex(str,0,10))
# 5
print (var.rindex(str,10))
# ValueError: substring not found
4. len(string) – Returns the length of given String
var='This is a good example'
print (len(var))
# 22

Understand Python Numbers & Type Conversion


with Examples

Python numbers are a group of four data types: plain integer, long integer, floating-
point and complex numbers. They not only support simple arithmetic calculations but
can also be used in quantum computation as complex numbers. In this tutorial, we’ll
try to explain each of them with examples.

Let’s see what numbers in Python are? Like other types in Python, numbers are also
objects. They can store an integer, a real or a composite number. Python numbers
are immutable objects so any change in the value would lead to the creation of a
new object. Usually, assigning a numeric value to a variable will get the number
object created.
>>> num = 10 + 5j # The number object got created.
>>> print(num)
(10+5j)
>>> type(num) # The number is of complex type.
<class 'complex'>
>>> id(num) # The initial address of 'num' in memory.
10171888
>>> num = 11 + 6j # The 'num' gets a new value.
>>> print(num)
(11+6j)
>>> type(num) # The 'num' is still of complex type.
<class 'complex'>
>>> id(num) # Change in value caused 'num' to have a new
memory address.
10171952
 Table of Content.
 Types of Numbers in Python
 Key Points to Remember
 Type Conversion in Python
 External Number Classes in Python
 Python Mathematics

Python Numbers, Type Conversion, and Mathematics

Python Numbers – Types Of Numeric Data


Interestingly, Python 2.x had four built-in data types (int, long, float and complex) to
represent numbers. Later Python 3.x removed the long and extended the int type to
have unlimited length.
The Int Type
The int type represents the fundamental integer data type in Python. The plain
integer in Python 2.x had the maximum size up to the value of sys.maxint.
While in 3.x, the int type got promoted to have unlimited length and thus eliminated
the long.
>>> x = 9
>>> type(x)
<type 'int'>
The Long Type
An integer number with unlimited length. Until the end of Python 2.x, the integers
were allowed to overflow and turned into a long. This behavior changed since 3.0,
where the ints replaced the longs.

>>> x = 9999999999
>>> type(x) # In Python 2.x, the type will be long. While in
3.x, it is int irrespective of the size.
<type 'long'>
The Float Type
The float represents a binary floating point number. Using a float variable in an
expression automatically converts the adjoining longs and ints to floats.

>>> x = 9.999
>>> type(x)
<type 'float'>
The Complex Type
The number of this type has a real and an imaginary part. For example – The
expression (n1 + n2j) represents a complex type where both n1 and n2 are
the floating-point numbers denoting the real and imaginary parts respectively.
>>> x = 3 + 4j
>>> type(x)
<class 'complex'>
>>> x.real
3.0
>>> x.imag
4.0
Python Numbers – Key Points
1.
1. The number types are automatically upcast in the following order.
Int → Long → Float → Complex
2. While integers in Python 3.x can be of any length, a float type number
is only precise to fifteen decimal places.
3. Usually, we work with numbers based on the decimal (base 10)
number system. But sometimes, we may need to use other number systems
such as binary (base 2), hexadecimal (base 16) and octal (base 8).
In Python, we can deal such numbers using the proper prefixes. See below.
Number System
Base
Prefix to Use
Binary
Base-2
‘0b’ or ‘0B’
Octal
Base-8
‘0o’ or ‘0O’
Hex
Base-16
‘0x’ or ‘0X’
>>> x = 0b101
>>> print(x)
5
>>> type(x)
<type 'int'>
>>> print(0b101 + 5)
10
>>> print(0o123)
83
>>> type(0x10)
<type 'int'>
4. If you want to test the class type of a number in Python, then you
should use the isinstance() function.
isinstance(object, class)
Here is the example.

>>> isinstance(2.2, float)


True
5. If you use mixed data types in an expression, then all operands will
turn to behave as the most complex type used.
6. >>> 2 + 3.8
5.8
7. Be careful while dividing integers in Python.
In Python 2.x, the division (/) will return an integer quotient as the output.
8. >>> 7/2
3
In Python 3.x, the division (/) will return a float quotient as the output.

>>> 7/2
3.5
9. The floor operator (//) returns the integer quotient, and the mod (%)
operator gives the remainder. However, you can get both these by using the
divmod() function.
10.>>> divmod(7, 2)
11.(3, 1)
12.>>> 7 % 2
13.1
14.>>> 7 / 2
15.3.5
16.>>> 7 // 2
3
Type Conversion (Casting) In Python
In Python, it is pretty easy to convert any numeric data type into another. We call this
process as coercion in Pythonic term.

Basic operations such as addition, subtraction coerce integer to float implicitly (by
default) if one of the operands is a float.

>>> 2 + 4.5
6.5
In the above example, the first integer (2) turned into a float (2.0) for addition, and
the output is also a floating point number.

However, Python lays out a no. of built-in functions such as int(), float() and
complex() to convert between types explicitly. These functions can even convert
strings to numbers.

>>> int(3.7)
3
>>> int(-3.4)
-3
>>> float(3)
3.0
>>> complex(4 + 7j)
(4+7j)
Please note that if you are doing a conversion of a float to integer, then the number
will get truncated (i.e., the integer which is close to zero).

External Classes To Handle Python Numbers


As you’ve read above that Python’s built-in float class has a limit to control precision
up to the fifteen decimal places. However, there are other limitations as well because
it entirely depends on the computer implementation of the floating point numbers.
For example, see the below decimal point issue.

>>> 1.1 + 3.2


4.300000000000001
To overcome such type of issues, we can use the decimal module in Python.

Python Decimal
The decimal module provides the fixed and floating point arithmetic implementation
which is familiar to most people. Unlike the floating point numbers which have
precision up to 15 decimal places, the decimal module accepts a user-defined value.
It can even preserve significant digits in a no.

import decimal

print(0.28)

print(decimal.Decimal(0.28))

print(decimal.Decimal('5.30'))
Output-
0.28
0.2800000000000000266453525910037569701671600341796875
5.30
Python Fractions
Python packages a module named as ‘fractions,’ to handle fractional numbers.

A fraction combines a numerator and a denominator; both are of integer data type.
This module enables rational number arithmetic functionality.

Here is a simple example to create and use fraction type objects.

import fractions

print(fractions.Fraction(2.5))

print(fractions.Fraction(5.2))

print(fractions.Fraction(3,5))

print(fractions.Fraction(1.3))

print(fractions.Fraction('3.7'))
Output-
5/2
5854679515581645/1125899906842624
3/5
5854679515581645/4503599627370496
37/10
Python Mathematics
Python exposes a few built-in functions to carry out simple mathematical
calculations.
For example – abs(), cmp(), max(), min(), round().

print(round(55.26,1))

print(round(66.36,-1))
Output – 
55.3
70.0
Apart from the above methods, we can also use the math module in Python. It
provides following common functions to use.

Function
Description
abs(x)
The absolute value of x: the (positive) distance between x and zero.
ceil(x)
The ceiling of x: the smallest integer not less than x
cmp(a, b)
-1 if a < b, 0 if a == b, or 1 if a > b
exp(x)
The exponential of x: ex
floor(x)
The floor of x: the largest integer not greater than x
log(x)
The natural logarithm of x, for x> 0
log10(x)
The base-10 logarithm of x for x> 0.
max(x1, x2,…)
The largest of its arguments: the value closest to positive infinity
min(x1, x2,…)
The smallest of its arguments: the value closest to negative infinity
modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts share the same
sign as x. The integer part coerces into a float.
pow(x, y)
The value of x**y
round(x [,n])
x rounded to n digits from the decimal point.
sqrt(x)
The square root of x for x > 0
pi
The mathematical constant pi.
e
The mathematical constant e.
Here are some examples of using the ceil() function.

Example-1
import math
x = math.ceil(3.5)
print(x)
print(math.ceil(2 + 4.2))
Output –
4
7
Example-2
from math import ceil

x = 9 / 4
y = ceil(x)
print(y)
Output –
3

Python List – A Beginners Guide


Python Set – Learn Step By Step
Contents [hide]
 1 Sets in Python
o 1.1 What is a Set?
o 1.2 Properties of a Set
 2 Create or Update Python Set
o 2.1 Create a Set
o 2.2 Add Elements to a Set
 3 Remove Elements from a Set
 4 Python Set Operations
o 4.1 Union Operation
o 4.2 Intersection Operation
o 4.3 Difference Operation
o 4.4 Symmetric Difference
 5 Miscellaneous Set Operations
o 5.1 Access Set Elements
o 5.2 Set Membership Test
 6 Frozen Sets in Python
 7 Summary

Sets In Python
What Is A Set?
Set is a term that originates from Mathematics. But, in Python, it is a collection type
object which can store elements of different data types. It doesn’t index the values in
a particular order.
Properties Of A Set
A Python set has the following characteristics.

 The elements don’t have a specific order, and their positions can be
inconsistent.
 Each item is unique in a Set and, therefore, can’t have duplicates.
 The elements are immutable and hence, can’t accept changes once added.
 A set is itself mutable and allows the addition or deletion of items.
With Sets, we can execute several mathematical operations such as Union,
Intersection, Symmetric Difference, and Complement.

Create Or Update Python Set


Create A Set
You can invoke any of the following two methods to create a Python Set.

i. If you have a fixed set of elements, then group them using a comma as the
separator and enclose the group inside curly braces.
ii. Another way is to call the built-in “set()” method, which can also be used to
add elements at run-time.
Also, remember, the elements can be of any data types such as an integer, float,
tuple, or string, etc. The only exception with a set is that it can’t store a mutable item
such as List, Set, or Dictionary.
# create a set of numbers
py_set_num = {3, 7, 11, 15}
print(py_set_num)

# create a set of mixed data types


py_set_mix = {11, 1.1, "11", (1, 2)}
print(py_set_mix)
Executing the above code will return the following output.

# output
{3, 11, 7, 15}
{(1, 2), 1.1, 11, '11'}
Follow one more example of Python Set to gain more clarity.

# set can't store duplicate elements


py_set_num = {3, 7, 11, 15, 3, 7}
# it'll automatically filter the duplicates
print(py_set_num)

# create a set using the set() method


# creating set with a fixed set of elements
py_set_mix = set([11, 1.1, "11", (1, 2)])
print(py_set_mix)

# creating set with dynamic elements


py_list = [11, 1.1, "11", (1, 2)]
py_list.append(12)
print(py_list)
py_set_mix = set(py_list)
print(py_set_mix)
Check out the result of the above code after execution.

# output
{11, 3, 15, 7}
{(1, 2), 1.1, 11, '11'}
[11, 1.1, '11', (1, 2), 12]
{(1, 2), 1.1, 11, '11', 12}
Let’s now do one more test with sets. We’ll no try to create an empty Python Set.

# Let's try to create an empty Python set


py_set_num = {}
print("The value of py_set_num:", py_set_num)
print("The type of py_set_num:", type(py_set_num))

py_set_num = set()
print("The value of py_set_num:", py_set_num)
print("The type of py_set_num:", type(py_set_num))
Here is the explanation of the above code.

The first statement would result in the creation of a dictionary object instead of
creating a set. You can’t just use curly braces and expect a “Set” in return.

While in the next non-print statement, we used the set() function but didn’t pass any
argument to it. It will eventually return us an empty Set object.
Please refer to the below output of the last example.

# output
The value of py_set_num: {}
The type of py_set_num: <class 'dict'>
The value of py_set_num: set()
The type of py_set_num: <class 'set'>
Add Elements To A Set
Python Set is a mutable object. However, it doesn’t use any indexing, and hence, it
doesn’t have any order.
It also means that you can’t change its elements by accessing through an index or
via slicing.

However, there are Set methods like the add(), which adds a single element and
the update(), which can add more than one item.
The update() method can even accept tuples, lists, strings, or other sets as an
argument. However, duplicate elements will automatically get excluded.
# Let's try to change a Python set
py_set_num = {77, 88}

try:
print(py_set_num[0])
except Exception as ex:
print("Error in py_set_num[0]:", ex)

print("The value of py_set_num:", py_set_num)

# Let's add an element to the set


py_set_num.add(99)
print("The value of py_set_num:", py_set_num)

# Let's add multiple elements to the set


py_set_num.update([44, 55, 66])
print("The value of py_set_num:", py_set_num)

# Let's add a list and a set as elements


py_set_num.update([4.4, 5.5, 6.6], {2.2, 4.4, 6.6})
print("The value of py_set_num:", py_set_num)
In the above example, the first line is demonstrating that a set doesn’t allow indexing.
We’ve kept that code inside the try-except block so that we can catch the error, print
it, and continue with the rest of the execution.
In the next section of the example, you can see the Set’s add() and update() methods
in action.
Now, check out the output of the above Python Set example.

# output
Error in py_set_num[0]: 'set' object does not support indexing
The value of py_set_num: {88, 77}
The value of py_set_num: {88, 99, 77}
The value of py_set_num: {66, 99, 44, 77, 55, 88}
The value of py_set_num: {66, 99, 4.4, 5.5, 6.6, 2.2, 44, 77,
55, 88}
Remove Elements From A Set
You can use the following Set methods to delete elements from it.
i. Discard() method
ii. Remove() method
There is a small difference in the way these two methods operate.
The discard() method doesn’t throw any error if the target item is not the part of the
set.
On the contrary, the remove() method will throw the “KeyError” error in such a case.
Follow the below example to get more clarity.

# Let's try to use a Python set


py_set_num = {22, 33, 55, 77, 99}

# discard an element from the set


py_set_num.discard(99)
print("py_set_num.discard(99):", py_set_num)

# remove an element from the set


py_set_num.remove(77)
print("py_set_num.remove(77):", py_set_num)

# discard an element not present in the set


py_set_num.discard(44)
print("py_set_num.discard(44):", py_set_num)

# remove an element not present in the set


try:
py_set_num.remove(44)
except Exception as ex:
print("py_set_num.remove(44) => KeyError:", ex)
It’ll generate the following result.

# output
py_set_num.discard(99): {33, 77, 22, 55}
py_set_num.remove(77): {33, 22, 55}
py_set_num.discard(44): {33, 22, 55}
py_set_num.remove(44) => KeyError: 44
Apart from the methods you’ve so far seen, there is a pop() method to remove an
element.
Also, since the Set doesn’t use indexing, so you can’t be sure which of the item
would get popped. It’ll randomly pick one element and remove it.

There is also a method called clear(), which flushes everything from the set.

# Let's use the following Python set


py_set_num = {22, 33, 55, 77, 99}
print("py_set_num:", py_set_num)
# pop an element from the set
py_set_num.pop()
print("py_set_num.pop():", py_set_num)

# pop one more element from the set


py_set_num.pop()
print("py_set_num.pop():", py_set_num)

# clear all elements from the set


py_set_num.clear()
print("py_set_num.clear():", py_set_num)
The above example will produce the following result.

# output
py_set_num: {33, 99, 77, 22, 55}
py_set_num.pop(): {99, 77, 22, 55}
py_set_num.pop(): {77, 22, 55}
py_set_num.clear(): set()
Python Set Operations
Like in mathematics, the set supports operations like union, intersection, difference,
and complement so does it in Python.

There are methods as well as operators available to perform the set operations.

For the illustration purpose, we will use the following two sets in the next examples.

# We'll use the setA and setB for our illustration


setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}
Union Operation
Union of setA and setB is a new set combining all the elements from both the Sets.
Python Set – Union
The “|” operator is the one to perform the union operation on the sets.
# We'll use the setA and setB for our illustration
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

print("Initial setA:", setA, "size:", len(setA))


print("Initial setB:", setB, "size:", len(setB))

print("(setA | setB):", setA | setB, "size:", len(setA |


setB))
We’ve used the Len() method to calculate the length of the set. The output of the
above example is as follows:
# output
Initial setA: {'u', 'i', 'g', 'o', 'e', 'h', 'a'} size: 7
Initial setB: {'u', 'z', 'b', 'o', 'e', 'a', 't'} size: 7
(setA | setB): {'h', 'u', 'z', 'b', 't', 'g', 'o', 'e', 'i',
'a'} size: 10
You can also accomplish similar results using the union() method.
# Python set example using the union() method
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

print("setA.union(setB):", setA.union(setB), "size:",


len(setA.union(setB)))
print("setB.union(setA):", setB.union(setA), "size:",
len(setB.union(setA)))
You can apply the union() method on any of the set (i.e., set A or B); the output will
remain the same.
# output
setA.union(setB): {'a', 'o', 'e', 'b', 'u', 't', 'i', 'g',
'z', 'h'} size: 10
setB.union(setA): {'a', 'o', 'e', 'b', 'u', 't', 'i', 'g',
'z', 'h'} size: 10
Intersection Operation
The intersection of setA and setB will produce a set comprising common elements in
both the Sets.
Python Set – Intersection
You can use Python’s “&” operator to perform this operation.
# Python intersection example using the & operator
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

print("Initial setA:", setA, "size:", len(setA))


print("Initial setB:", setB, "size:", len(setB))

print("(setA & setB):", setA & setB, "size:", len(setA &


setB))
This example will produce the following result.

# output
Initial setA: {'e', 'o', 'h', 'a', 'g', 'u', 'i'} size: 7
Initial setB: {'b', 'e', 't', 'o', 'z', 'a', 'u'} size: 7
(setA & setB): {'o', 'a', 'u', 'e'} size: 4
Alternatively, you can call the intersection() method to perform this operation.
# Python set example using the intersection() method
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

intersectAB = setA.intersection(setB)
print("setA.intersection(setB):", intersectAB, "size:",
len(intersectAB))
intersectBA = setB.intersection(setA)
print("setB.intersection(setA):", intersectBA, "size:",
len(intersectBA))
This example will produce the following result.

# output
setA.intersection(setB): {'a', 'u', 'e', 'o'} size: 4
setB.intersection(setA): {'a', 'u', 'e', 'o'} size: 4
Difference Operation
When you perform the difference operation on two Sets, i.e., <setA – setB>,  the
resultant will be a set of elements that exist in the left but not in the right object.

Python Set – Difference


Likewise, the operation <setB – setA> will return those elements of setB which don’t
exist in the setA.

You can use the minus (-) operator to carry out this operation.


# Python set's difference operation
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

diffAB = setA - setB


print("diffAB:", diffAB, "size:", len(diffAB))
diffBA = setB - setA
print("diffBA:", diffBA, "size:", len(diffBA))
There are three unique elements in both of our input sets that don’t exist in another.
Check the output below.

# output
diffAB: {'i', 'g', 'h'} size: 3
diffBA: {'z', 'b', 't'} size: 3
The next example will demonstrate the same set of operations using
the difference() method.
# Python set's difference operation using the difference()
method
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

diffAB = setA.difference(setB)
print("diffAB:", diffAB, "size:", len(diffAB))
diffBA = setB.difference(setA)
print("diffBA:", diffBA, "size:", len(diffBA))
The execution of the above example would produce the below output.

# output
diffAB: {'i', 'g', 'h'} size: 3
diffBA: {'b', 't', 'z'} size: 3
Symmetric Difference
The symmetric difference of two sets will generate a set of elements that exist in
<setA> and <setB> but not in both.

Python Set – Symmetric Difference


You can execute this operation with the help of the caret operator (^) in Python.
# Python set example using the caret ^ operator
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

symdiffAB = setA^setB
print("symdiffAB:", symdiffAB, "size:", len(symdiffAB))
symdiffBA = setB^setA
print("symdiffBA:", symdiffBA, "size:", len(symdiffBA))
The output is as follows.

symdiffAB: {'z', 't', 'h', 'g', 'b', 'i'} size: 6


symdiffBA: {'z', 'h', 'g', 't', 'b', 'i'} size: 6
You can also get the operation done with the method symmetric_difference().
# Python set example using the symmetric_difference() method
setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'}
setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}

symdiffAB = setA.symmetric_difference(setB)
print("symdiffAB:", symdiffAB, "size:", len(symdiffAB))
symdiffBA = setB.symmetric_difference(setA)
print("symdiffBA:", symdiffBA, "size:", len(symdiffBA))
The result is as follows.

# result
symdiffAB: {'z', 'h', 'i', 'g', 't', 'b'} size: 6
symdiffBA: {'z', 'i', 'g', 'b', 't', 'h'} size: 6
Miscellaneous Set Operations
Access Set Elements
It’s not possible to access an element directly in a set. But you can fetch all of them
together. You need a loop to retrieve a list of particular items over the Set.

# Python set example to access elements from a set


basket = set(["apple", "mango", "banana", "grapes", "orange"])

for fruit in basket:


print(fruit)
After executing the above code, you’ll see the following output.

# output
apple
banana
mango
orange
grapes
Set Membership Test
You can surely check if a set contains a particular element or not. You can make use
of the “in” keyword for this purpose.
# Python set example to test elements in a set
basket = set(["apple", "mango", "banana", "grapes", "orange"])

# confirm if 'apple' is in the basket


print("Is 'apple' in the basket?", 'apple' in basket)

# confirm if 'grapes' is in the basket


print("Is 'watermelon' in the basket?", 'watermelon' in
basket)
After executing the above code, you’ll see the following output.

# output
Is 'apple' in the basket? True
Is 'watermelon' in the basket? False
Frozen Sets In Python
It is a unique type of set which is immutable and doesn’t allow changing its elements
after assignment.
It supports all methods and operators as a set does, but those that don’t alter its
content.

As you now know that the sets are mutable and thus become unhashable. So, we
can’t use them as keys for a Python dictionary. On the contrary, the Frozen Set is by
default hashable and can work as keys to a dictionary.

You can create a Frozen set with the help of the following function.

frozenset()
Also, the following Python methods can work with the Frozen set.

copy()
difference()
intersection()
isdisjoint()
issubset()
issuperset()
symmetric_difference()
union()
The methods which perform add or remove operations aren’t applicable for Frozen
sets as they are immutable.

The below sample exhibits the differences between a standard vs. the frozen set.

# Python Sample - Standard vs. Frozen Set

# A standard set
std_set = set(["apple", "mango","orange"])

# Adding an element to normal set is fine


std_set.add("banana")

print("Standard Set:", std_set)

# A frozen set
frozen_set = frozenset(["apple", "mango","orange"])

print("Frozen Set:", frozen_set)

# Below code will raise an error as we are modifying a frozen


set
try:
frozen_set.add("banana")
except Exception as ex:
print("Error:", ex)

Python Tuple – A Tutorial to Get Started Quickly

Python Tuple – Learn Step By Step


Contents [hide]
 1 What is a Tuple in Python?
 2 How to instantiate a Tuple in Python?
o 2.1 Simple examples to create a tuple with different inputs
o 2.2 Using the built-in function “tuple()” to create a tuple
o 2.3 Creating a tuple of size one
 3 How can you access a tuple in Python?
o 3.1 Via Indexing
o 3.2 Via Reverse Indexing
o 3.3 Via Slicing Operator
 4 How to modify/update a tuple in Python?
 5 How to remove/delete a tuple in Python?
 6 Miscellaneous Tuple Operations
o 6.1 Testing membership in Python tuple
o 6.2 Traversing in a Python tuple
 7 Usage of Python Tuples
o 7.1 Used for grouping data
o 7.2 Assign to a tuple
o 7.3 Using tuples in functions as return values
o 7.4 Mixed Data Structures in the form of tuples

What Is A Tuple In Python?


A Python tuple is a collection type data structure which is immutable by design and
holds a sequence of heterogeneous elements. It functions almost like a Python
list but with the following distinctions.
 Tuples store a fixed set of elements and don’t allow changes whereas the list
has the provision to update its content.
 The list uses square brackets for opening and closing whereas, and a tuple
has got parentheses for the enclosure.
A tuple can come quite handy for programmers in different situations. We’ll discuss
them later in this tutorial.
Python Tuple Data Structure
How To Instantiate A Tuple In Python?
You can create a tuple by placing a sequence of desired elements separated using
commas inside a pair of round brackets (), i.e., parentheses.

Please note that you can create a tuple even without using the parentheses. Also,
the elements of a tuple can be of any valid Python data types ranging
from numbers, strings, lists, etc.
Simple Examples To Create A Tuple With Different Inputs
# create an empty tuple
py_tuple = ()
print("A blank tuple:", py_tuple)

# create a tuple without using round brackets


py_tuple = 33, 55, 77
print("A tuple set without parenthesis:", py_tuple, "type:",
type(py_tuple))

# create a tuple of numbers


py_tuple = (33, 55, 77)
print("A tuple of numbers:", py_tuple)

# create a tuple of mixed numbers


# such as integer, float, imaginary
py_tuple = (33, 3.3, 3+3j)
print("A tuple of mixed numbers:", py_tuple)

# create a tuple of mixed data types


# such as numbers, strings, lists
py_tuple = (33, "33", [3, 3])
print("A tuple of mixed data types:", py_tuple)

# create a tuple of tuples


# i.e. a nested tuple
py_tuple = (('x', 'y', 'z'), ('X', 'Y', 'Z'))
print("A tuple of tuples:", py_tuple)
Executing the above coding snippet will produce the below result.

# output
A blank tuple: ()
A tuple set without parenthesis: (33, 55, 77) type: <class
'tuple'>
A tuple of numbers: (33, 55, 77)
A tuple of mixed numbers: (33, 3.3, (3+3j))
A tuple of mixed data types: (33, '33', [3, 3])
A tuple of tuples: (('x', 'y', 'z'), ('X', 'Y', 'Z'))
Using The Built-In Function “Tuple()” To Create A Tuple
We can invoke the tuple function and get the desired result. See the below example.

# creating a tuple from a set


>>> py_tuple = tuple({33, 55 , 77})
>>> type(py_tuple)
<class 'tuple'>
>>> py_tuple
(33, 77, 55)
# creating a tuple from a list
>>> py_tuple = tuple([33, 55 , 77])
>>> type(py_tuple)
<class 'tuple'>
>>> py_tuple
(33, 55, 77)
Creating A Tuple Of Size One
In the below example, we are trying to create a tuple with a single element. It’s not
as easy to achieve as it looks so.

# A single element surrounded by parenthesis will create a


string instead of a tuple
>>> py_tuple = ('single')
>>> type(py_tuple)
<class 'str'>
# You need to place a comma after the first element to create
a tuple of size "one"
>>> py_tuple = ('single',)
>>> type(py_tuple)
<class 'tuple'>
# You can use a list of one element and convert it to a tuple
>>> py_tuple = tuple(['single'])
>>> type(py_tuple)
<class 'tuple'>
# You can use a set of one element and convert it to a tuple
>>> py_tuple = tuple({'single'})
>>> type(py_tuple)
<class 'tuple'>
How Can You Access A Tuple In Python?
Python provides various intuitive mechanisms to access a single or a range of
elements from a tuple.

Via Indexing
The simplest is the direct access method where you use the index operator [] to pick
an item from the tuple. You can start indexing from the 0th position.

It means if a tuple holds ten elements, then the index will begin at 0th and will end at
9th position. Violating the boundaries of a tuple will result in an IndexError.

Please note that the index is always an integer. You must not try a float or any other
form of numbers for the indexing purpose. Doing so will produce TypeError.

Next, if the tuple contains other tuples as its elements, then you would need to index
the elements tuple-by-tuple.

vowel_tuple = ('a','e','i','o','u')
print("The tuple:", vowel_tuple, "Length:", len(vowel_tuple))

# Indexing the first element


print("OP(vowel_tuple[0]):", vowel_tuple[0])

# Indexing the last element


print("OP(vowel_tuple[length-1]):",
vowel_tuple[len(vowel_tuple) - 1])

# Indexing a non-existent member


# will raise the IndexError
try:
print(vowel_tuple[len(vowel_tuple)+1])
except Exception as ex:
print("OP(vowel_tuple[length+1]) Error:", ex)

# Indexing with a non-integer index


# will raise the TypeError
try:
print(vowel_tuple[0.0])
except Exception as ex:
print("OP(vowel_tuple[0.0]) Error:", ex)

# Indexing in a tuple of tuples


t_o_t = (('jan', 'feb', 'mar'), ('sun', 'mon', 'wed'))

# Accessing elements from the first sub tuple


print("OP(t_o_t[0][2]):", t_o_t[0][2])

# Accessing elements from the second sub tuple


print("OP(t_o_t[1][2]):", t_o_t[1][2])
After running the above sample code, the following output will get displayed:

# output
The tuple: ('a', 'e', 'i', 'o', 'u') Length: 5
OP(vowel_tuple[0]): a
OP(vowel_tuple[length-1]): u
OP(vowel_tuple[length+1]) Error: tuple index out of range
OP(vowel_tuple[0.0]) Error: tuple indices must be integers or
slices, not float
OP(t_o_t[0][2]): mar
OP(t_o_t[1][2]): wed
Via Reverse Indexing
Python tuple supports reverse indexing, i.e., accessing elements using the (-ve)
index values.

The reverse indexing works in the following manner.

 The index -1 represents the last item.


 An index with value -2 will refer to the second item from the rear end.
Please go through the below example for more clarity.

>>> vowels = ('a','e','i','o','u')


>>> vowels
('a', 'e', 'i', 'o', 'u')
>>> vowels[-1]
'u'
>>> vowels[-2]
'o'
>>> vowels[-5]
'a'
>>> vowels[-6]
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
vowels[-6]
IndexError: tuple index out of range
Via Slicing Operator
If you need to access not one but more than one element from a tuple, then Python’s
slicing operator can come to use.

The single colon, i.e., a “:” represents the slicing operator in Python.

Let’s see how can the “:” operator can come into play with the below example.

>>> weekdays = ('mon', 'tue', 'wed' ,'thu', 'fri', 'sat',


'sun')
>>> weekdays
('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
# accessing elements leaving the first one
>>> weekdays[1:]
('tue', 'wed', 'thu', 'fri', 'sat', 'sun')
# accessing elements between the first and fifth positions
# excluding the ones at the first and fifth position
>>> weekdays[1:5]
('tue', 'wed', 'thu', 'fri')
# accessing elements after the fifth position
>>> weekdays[5:]
('sat', 'sun')
# accessing the first five elements
>>> weekdays[:5]
('mon', 'tue', 'wed', 'thu', 'fri')
# accessing elements that appears after
# counting five from the rear end
>>> weekdays[:-5]
('mon', 'tue')
# accessing five elements from the rear
>>> weekdays[-5:]
('wed', 'thu', 'fri', 'sat', 'sun')
# accessing elements from the start to end
>>> weekdays[:]
('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
How To Modify/Update A Tuple In Python?
Since tuples are immutable, so it seems no way to modify them.

Once you assign a set of elements to a tuple, Python won’t allow it to change. But,
there is a catch, what if the items you set are modifiable.

If there is such a case, then you can change the elements instead of directly
modifying the tuple.

Moreover, you can even set a tuple to have different values. Check out the below
example.

py_tuple = (22, 33, 55, 66, [88, 99])


print("Tuple before modificaton:", py_tuple)

# Let's try to modify py_tuple


# It'll return a TypeError
try:
py_tuple[0] = 11
except Exception as ex:
print("OP(py_tuple[0]) Error:", ex)

# We can change the values of mutable


# elements inside the py_tuple i.e. list
py_tuple[4][0] = 77
py_tuple[4][1] = 88
print("Tuple after modificaton:", py_tuple)

# We can assign a tuple with new data


py_tuple = ('mon', 'tue', 'wed')
print("Tuple after reassignment:", py_tuple)
After execution, the example will yield the following result.

# output
Tuple before modificaton: (22, 33, 55, 66, [88, 99])
OP(py_tuple[0]) Error: 'tuple' object does not support item
assignment
Tuple after modificaton: (22, 33, 55, 66, [77, 88])
Tuple after reassignment: ('mon', 'tue', 'wed')
Moreover, you can extend the behavior of a tuple by using the +
(concatenation) and * (repeat) operators.
The plus operator helps you join the two distinct tuples.
>>> first_tuple = ('p', 'y', 't')
>>> second_tuple = ('h', 'o', 'n')
>>> full_tuple = first_tuple + second_tuple
>>> full_tuple
('p', 'y', 't', 'h', 'o', 'n')
>>>
And the star operator helps you repeat the elements in a tuple for a specified number
of times.

>>> init_tuple = ("fork", )


>>> fork_tuple = init_tuple * 5
>>> fork_tuple
('fork', 'fork', 'fork', 'fork', 'fork')
>>>
How To Remove/Delete A Tuple In Python?
Immutability of a tuple would again prevent you from deleting it in a Python program.
While you can’t delete a tuple directly, but here is something which can help.

The Python’s del keyword can make you delete a tuple. Check out the below
example.
py_tuple = ('p', 'y', 't', 'h', 'o', 'n')

# you can't delete a particular item from a tuple


try:
del py_tuple[0]
except Exception as ex:
print("OP(del py_tuple[0]) Error:", ex)

# but you can delete a whole tuple


del py_tuple
try:
print(py_tuple)
except Exception as ex:
print("print(py_tuple) => Error:", ex)
The execution of the above code would give you the following result.

# output
del py_tuple[0] => Error: 'tuple' object doesn't support item
deletion
print(py_tuple) => Error: name 'py_tuple' is not defined
The first line of the output conveys that we can’t delete a specific item from the tuple.
But the second line says that we’ve already removed it and trying to print an
undefined object.
Miscellaneous Tuple Operations
Testing Membership In Python Tuple
Just like we did in Python set, here also, the “in” keyword will help us exercise the
membership test on a tuple.
>>> py_tuple = ('p', 'y', 't', 'h', 'o', 'n')
>>> print("First Test: Does 'p' exist?", 'p' in py_tuple)
First Test: Does 'p' exist? True
>>> print("Second Test: Does 'z' exist?", 'z' in py_tuple)
Second Test: Does 'z' exist? False
>>> print("Third Test: Does 'n' exist?", 'n' in py_tuple)
Third Test: Does 'n' exist? True
>>> print("Last Test: Does 't' not exist?", 't' not in
py_tuple)
Last Test: Does 't' not exist? False
>>>
Traversing In A Python Tuple
You can form a for loop and one by one access all the elements in a tuple.

>>> py_tuple = ('p', 'y', 't', 'h', 'o', 'n')


>>> for item in py_tuple:
print("Item:", item)

Item: p
Item: y
Item: t
Item: h
Item: o
Item: n
Usage Of Python Tuples
Used For Grouping Data
The tuple provides a quick way of grouping and arranging data. It can help you
combine any number of elements into a single unit.

They can help us representing information in the form of records such as the
employee record. A tuple allows us to group related information and use it as a
single entity.

>>> emp_records = ('john', 'hr', 2010, 'robert', 'account',


2015, 'bill', 'mis', 2018)
>>> emp_records[3]
'robert'
Assign To A Tuple
Python tuple supports a very intuitive feature know as “tuple assignment.” It lets us
assign a tuple of variables on the left of a statement to initialize from the tuple on the
right side.

>>> emp_records = ('john', 'hr', 2010, 'robert', 'account',


2015, 'bill', 'mis', 2018)
>>> (emp_name, emp_dept, emp_join_date) = emp_records[0:3]
>>> emp_name
'john'
>>> emp_dept
'hr'
>>> emp_join_date
2010
Using Tuples In Functions As Return Values
Usually, a Function only returns one value. However, we can introduce a tuple and
set it as the Return Value for the Function.

It means, we can combine multiple values and store them in a tuple and finally return
it. It could come quite handy in situations when we want to know the hours, minutes,
seconds consumed by a job, or to get the counts of different types of accessories or
the prices of multiple books written by a particular author.

def square(n1, n2):


return (n1*n1, n2*n2)

print(type(square(2, 3)))
# output
<class 'tuple'>
Mixed Data Structures In The Form Of Tuples
Tuples are a type of container which can embed another tuple as an element. We
call such an object as a nested tuple.

It could help in visualizing information at a broader level. For example, if we have to


maintain employee counts in each department along with their names, position, and
salaries, the nested tuples can let us do this efficiently.

employes = [
   ("HR", 2, [('david', 'manager', 100000), ('bruno', 'asst.
manager', 50000)])
   ("IT", 2, [('kirk', 'team lead', 150000), ('matt',
'engineer', 45000)])
   ("Sales", 2, [('billy', 'sales lead', 250000), ('tom',
'executive', 95000)])
]
Python Dictionary – Create, Append, Update,
Remove

In this class, you’ll discover what Python Dictionary is and how to create it. You will
also learn to append, update, remove and search elements in a dictionary object.

A dictionary in Python is a scrambled collection of objects. Unlike other data types


such as a list or a set which has a single value field, the dictionary type stores a key
along with its value.

The keys pair with values using a colon (:) while the commas work as a separator for
the elements. Also, the entire dictionary object uses curly braces to enclose itself.

Below is an example of a barren dictionary object which doesn’t have any elements.

#The empty Python dictionary object


{}
Please remember that only keys inside a dictionary can’t have duplicates, but
their values can repeat themselves.

Next, the value in a dictionary can be of any valid Python data type. But the keys
have a constraint to be of any immutable data types such as a string, a number, or a
tuple.

Dictionary In Python
Contents [hide]
 1 Create Dictionaries
 2 Dictionary Operations
 3 Access Elements
 4 Append in a Dictionary
o 4.1 Assignment to Append Elements
o 4.2 Update Method to Append Elements
 5 Update a Dictionary
o 5.1 Use Assignment
o 5.2 Use the Update Method
 6 Remove Elements
 7 Dictionary Attributes
 8 Iterate Dictionary
 9 Dictionary Comprehension
 10 Membership Test

Create Dictionaries
If you wish to create a Python dictionary with fixed keys and values, then it’s quite
easy to do so. Just combine all the “key1:value1, key2:value2,…” pairs and enclose
with curly braces.
The combination of a key and its value, i.e. “key: value” represents a single element
of a dictionary in Python.

While defining static dictionary objects, you must be careful to use unique values for
keys. However, they can derive from any valid Python data type.

Also, remember to use only immutable data types for the values while they can have
duplicates.

# Define a blank dictionary with no elements


blank_dict = {}

# Define a dictionary with numeric keys


num_dict = {1: 'soccer', 2: 'baseball'}

# Define a dictionary with keys having different types


misc_dict = {'class': 'senior secondary', 1: [1, 2, 3,4,5]}

# Create a dictionary with dict() method


get_dict_from_func = dict({1:'veg', 2:'non-veg'})

# Create a dictionary from a sequence of tuples


make_dict_from_seq = dict([(1,'jake'), (2,'john')])
Learn about – Python Strings
Dictionary Operations
Access Elements
Python dictionary has the key as an additional parameter. We can access the
elements of a dictionary with the help of keys by using them as Index to the array
operator ([]) or passing as Argument to the get() method.

Both methods will work the same, but the former will return a KeyError while the
latter returns None if the element is not available.

dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':


'English'}
print("dict['Student Name']: ", dict['Student Name'])
print("dict['Roll No.']: ", dict['Roll No.'])
print("dict['Subject']: ", dict['Subject'])
Running the above coding snippet will result in the following output.

dict['Student Name']: Berry


dict['Roll No.']: 12
dict['Subject']: English
Accessing an element with a non-existent key will return an error. Check out the
below code.

dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':


'English'}
print("dict['Name']: ", dict['Name'])
The above example uses the “Name” key which doesn’t exist. Running the same
would produce a “KeyError.”

Traceback (most recent call last):


File "C:/Python/Python35/test_dict.py", line 2, in <module>
print("dict['Name']: ", dict['Name'])
KeyError: 'Name'
In the next example, we’ll access the elements in a Python dictionary using the get()
function.

dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':


'English'}
print(dict.get('Student Name'))
print(dict.get('Roll No.'))
print(dict.get('Subject'))
This code will yield the following result.

Berry
12
English
Append In A Dictionary
You can append a new item to an existing dict object with elements in the following
two ways.

Assignment To Append Elements


>>> dict_append = {"1" : "Python", "2" : "Java"}
>>> print(dict_append)
{'1': 'Python', '2': 'Java'}
>>> dict_append["3"] = "CSharp"
>>> print(dict_append)
{'1': 'Python', '3': 'CSharp', '2': 'Java'}
>>>
Update Method To Append Elements
You can call the dictionary’s update method to append a new element to it. We are
extending the above example, see below:

>>> dict_append.update({"4" : "JavaScript"})


>>> print(dict_append)
{'1': 'Python', '3': 'CSharp', '2': 'Java', '4': 'JavaScript'}
>>>
Update A Dictionary
Python allowed the dictionary object to be mutable. Hence, the add or update
operations are permissible. You can push a new item or modify any existing with the
help of the assignment operator.

Whenever you add an element whose key already exists, it’s value will get changed
to the new value. On adding a fresh “key: value” pair, a new element will get added
to the dictionary.

Use Assignment
In the below example, we are demonstrating both the update and the addition
operations on the existing dictionary object.

dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':


'English'}
print("The student who left:", dict.get('Student Name'))
dict['Student Name'] = 'Larry'
print("The student who replaced: [Update]", dict.get('Student
Name'))
dict['Student Name'] = 'Jarry'
print("The student who joined: [Addition]", dict.get('Student
Name'))
The execution of the above code will produce the following output.

The student who left: Berry


The student who replaced: [Update] Larry
The student who joined: [Addition] Jarry
Use The Update Method
You can alternatively call the update method to modify the value of any existing
element. See the example below.

Let’s resume the previous example. It has a dict object which contains a key as
‘Student Name’. We’ll update its value.

>>> sample_dict = {"python" : 1, "csharp" : 2, "javascript" :


3}
>>> sample_dict.update( javascript = 2 )
>>> print(sample_dict)
{'python': 1, 'javascript': 2, 'csharp': 2}
>>> sample_dict.update( csharp = 3 )
>>> print(sample_dict)
{'python': 1, 'javascript': 2, 'csharp': 3}
Remove Elements
Python lends us a no. of methods to remove elements from the dictionary.

The most common of them is the “pop()” method. It takes the key as the input
and deletes the corresponding element from the Python dictionary. It returns the
value associated with the input key.
Another method is “popitem()”. It removes and returns a random element (key,
value) from the dictionary.
If you like to drop all the elements from the dictionary, then use the “clear()” method
to flush everything.
Nonetheless, one more way to remove an element from a dictionary is to use the del
keyword. It can help you delete individual items and consequently the whole
dictionary object.

# Create a Python dictionary


sixMonths = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30}

# Delete a specific element


print(sixMonths.pop(6))
print(sixMonths)

# Delete an random element


print(sixMonths.popitem())
print(sixMonths)

# Remove a specific element


del sixMonths[5]
print(sixMonths)

# Delete all elements from the dictionary


sixMonths.clear()
print(sixMonths)

# Finally, eliminate the dictionary object


del sixMonths
print(sixMonths)
Here is the result of running the above coding snippet.

30
{1: 31, 2: 28, 3: 31, 4: 30, 5: 31}
(1, 31)
{2: 28, 3: 31, 4: 30, 5: 31}
{2: 28, 3: 31, 4: 30}
{}
Traceback (most recent call last):
File "C:/Python/Python35/test_dict.py", line 22, in <module>
print(sixMonths)
NameError: name 'sixMonths' is not defined
In the above example, the second last statement removes all the elements from the
Python dictionary, leaving it empty.

And the subsequent call to the “del” operator on the dictionary object removes it
altogether. Hence, the last print statement fails with the “NameError.”

Learn about – Tuples in Python


Dictionary Attributes
Python doesn’t impose any constraints on the “Values” of a dictionary object. You
can form them using the standard Python or any custom data types. But, as we said
earlier, the “Keys” aren’t the same as “Values” and have altogether different
handling.

Hence, it is vital for you to memorize the following two facts about the dictionary
“Keys.”

 The same key can’t have another value in the dictionary. It confirms that a
duplicate key can’t exist. However, even if you try to supply a duplicate key, it’ll
only modify the existing key with the value provided in the last assignment.
dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':
'English','Student Name': 'Kerry'}
print("dict['Student Name']: ", dict['Student Name'])
Executing the above code will show that the key “Student Name” will keep the last
assigned value, i.e., “Kerry.”

dict['Student Name']: Kerry


 Python says that the dictionary Keys should derive from the immutable data
types. You can infer that only allowed types are strings, numbers or tuples.
Check out a standard example below.
dict = {['Student Name']: 'Berry', 'Roll No.': 12, 'Subject':
'English'}
print("dict['Student Name']: ", dict['Student Name'])
In the above example, the key is using a list type. Since Python doesn’t support this,
hence the statement will generate a “TypeError.”

Here is the outcome of the above example.

Traceback (most recent call last):


File "C:/Python/Python35/test_dict.py", line 1, in <module>
dict = {['Student Name']: 'Berry', 'Roll No.': 12, 'Subject':
'English'}
TypeError: unhashable type: 'list'
Iterate Dictionary
Similar to the lists, you can use a “for in” loop to traverse through a dictionary. In
general, it’s the keys which enable iteration.

Let’s understand the concept with a simple example. It prints all the keys of a
dictionary in a loop.

dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':


'English'}
print("Keys are:")
for key in dict:
print(key)
The output of the above Python code is as follows.

Keys are:
Student Name
Roll No.
Subject
Follow one more example below which prints keys along with values.

dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject':


'English'}
print("{Keys}:{Values}")
for key, value in dict.items():
print({key},":",{value})
The result of the above Python code is as follows.

{Keys}:{Values}
{'Student Name'} : {'Berry'}
{'Roll No.'} : {12}
{'Subject'} : {'English'}
Dictionary Comprehension
Just like a Python list, the dictionary also allows comprehension to create new
objects from an iterable in a loop.
You can specify a dictionary comprehension by using an expression including a “key:
value” pair followed by for loop and enclosed with curly braces {}.

Follow the below examples to create a dictionary using the comprehension syntax.

Let’s make a dictionary object with the string type for keys and the number format for
values.

>>> {str(iter):iter for iter in [11,22,33,44,55]}


{'44': 44, '33': 33, '55': 55, '11': 11, '22': 22}
Another example of creating a dictionary from the list of weekdays as keys and the
length of each week as the values.

>>> weekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri',


'sat']
>>> {w:len(w) for w in weekdays}
{'fri': 3, 'tue': 3, 'wed': 3, 'sat': 3, 'thu': 3, 'mon': 3,
'sun': 3}
We can use the “enumerate()” function in a dictionary comprehension. It helps
us save the index of a specific element that we could use later. Also, in a for loop,
the position of a list element isn’t visible without “enumerate().”

Such Python dictionaries which have element index can be useful in many situations.

>>> {w : i for i, w in enumerate(weekdays)}


{'fri': 5, 'tue': 2, 'wed': 3, 'sat': 6, 'thu': 4, 'mon': 1,
'sun': 0}
Membership Test
We can quickly confirm whether a Key is present in a dictionary or not using the
keyword “in.” Also, please note that the membership test is only applicable to Keys,
not for Values.

weekdays = {'fri': 5, 'tue': 2, 'wed': 3, 'sat': 6, 'thu': 4,


'mon': 1, 'sun': 0}
# Output: True
print('fri' in weekdays)
# Output: False
print('thu' not in weekdays)
# Output: True
print('mon' in weekdays)
The output of the above snippet is as follows.

True
False
True
A Quick Guide to Format String in Python

Python Format – String And Other Types


Contents [hide]
 1 Python format function
o 1.1 Single argument formatting
o 1.2 Multiple arguments formatting
 2 Format a Python string
o 2.1 Basic string formatting
o 2.2 Padding and align strings
o 2.3 Justify a variable string expansion
 3 Format integers
o 3.1 Using separator number formatting
o 3.2 Specify field width for numbers
o 3.3 Padding for numbers
o 3.4 Format a number as binary
o 3.5 Format a number as octal
o 3.6 Format a number as hex
 4 Representing a float number
o 4.1 Simple example
o 4.2 Fixed point
o 4.3 General
o 4.4 Scientific
 5 Format lists and dictionaries
o 5.1 Formatting a list in Python
o 5.2 Formatting a dict in Python
Here are a few of the simple examples of the Python string formatting.
Python Format Function
You can invoke format function in one of the following ways:

Single Argument Formatting


The simplest case while calling the Python format function is to have a single
formatter. Below is the syntax to use it.

Format syntax : '{}'.format(param)

* Description:
** '{}': It is the format target, i.e., the placeholder.
** param: It can be a string, integer, float, or any of the
collection types.
** Return: It returns a formatted output with the input
argument substituting the placeholder.
See a quick illustration:

>>> '{}'.format('Formatting a String in Python')


'Formatting a String in Python'
Multiple Arguments Formatting
A slightly complicated way to call the Python format function is to supply more than
one formatter at a time. Below is the syntax to use it.

Format syntax : '{} {}'.format(arg1, arg2)

* Description:
** '{} {}': We can have multiple placeholders.
** arg1, arg2: They can be a string, integer, float, or any of
the collection types.
** Return: It returns a formatted output with the input
argument substituting the placeholder.
See a quick illustration:

>>> '{} {}'.format('Python', 'Format')


'Python Format'
Format A Python String
Basic String Formatting
Print a single string using the format function.

>>> test = "Hello"


>>> print('{}'.format(test))
Hello
Combine two string literals and print them using the format function.

>>> first = "Hello"


>>> second = "World"
>>> print('{} {}'.format(first, second))
Hello World
Padding And Align Strings
We can also use the Python format function to allow padding.

Its purpose is to align a string either using a space or some value. You need to
provide the length for the alignment which should be higher than the size of the
target string.

It is because the alignment can only occur in a box of fixed length.

Let’s align a string to the right with spaces.

>>> print(format("Hello", ">10s"))


Hello
Now, let’s do the same operation using the ‘#’ character.

>>> print(format("Hello", "#>10s"))


#####Hello
Here is a brief description of the above steps.

 You can see that the box length for printing the string is 10.
 It means the max we can accommodate the ten characters.
 The word “Hello” itself has five letters and the ‘#’ gets filled at the remaining
five places.
 You might have observed the “>” symbol in the format syntax. It makes our
target string to move to the right side.
If you like to align the target string from the left, then use the ‘<‘ symbol.

>>> print(format("Hello", "#<10s"))


Hello#####
You can even make a string center-aligned inside a fixed-length box.

>>> print(format("Hello", "#^15s"))


#####Hello#####
The carat ‘^’ sign makes the string format to the center.

Justify A Variable String Expansion


In the below example, we demonstrate the variable string expansion and justifies it.

>>> print('<-- {0:30} -->'.format('Python Programming'))


<-- Python Programming -->
>>> print('<-- {0:>30} -->'.format('Python Programming'))
<-- Python Programming -->
>>> print('<-- {0:<30} -->'.format('Python Programming'))
<-- Python Programming -->
>>> print('<-- {0:^30} -->'.format('Python Programming'))
<-- Python Programming -->
Format Integers
There are many ways to format an Integer, let’s see the basic usage first.

>>> print("I've <{}> years of experience and my salary is <{}>


USD per annum.".format(10, 75000))
I've <10> years of experience and my salary is <75000> USD per
annum.
Using Separator Number Formatting
It is a standard convention to display the salary with commas. Python format function
supports this representation and requires a pair of ‘:’ and ‘,’ inside the parenthesis.

>>> print("I've <{}> years of experience and my salary is


<{:,}> USD per annum.".format(10, 75000))
I've <10> years of experience and my salary is <75,000> USD
per annum.
Specify Field Width For Numbers
Same as we did for strings is applicable for the integers. For integers, we can’t use
precision.
>>> print("I've <{:5}> years of experience and my salary is
<{:15,}> USD per annum.".format(10, 75000))
I've < 10> years of experience and my salary is <
75,000> USD per annum.
Padding For Numbers
While specifying the width for integers, you can use a character for padding the
space left vacant after printing the subject.

>>> print("I've <{:#>8}> years of experience and my salary is


<{:z>20,}> USD per annum.".format(10, 75000))
I've <######10> years of experience and my salary is
<zzzzzzzzzzzzzz75,000> USD per annum.
Format A Number As Binary
Python format function allows printing a number in binary style. The symbol ‘b’ after
the colon inside the parenthesis notifies to display a number in binary format.

>>> print('{0:b}'.format(10))
1010
Format A Number As Octal
Python format function allows printing an integer in the octal style. The symbol ‘o’
after the colon inside the parenthesis notifies to display a number in octal format.

>>> print('{0:o}'.format(10))
12
Format A Number As Hex
Python format function allows printing an integer in the hex style. The symbol ‘x’ or
‘X’ after the colon inside the parenthesis notifies to display a number in hex format.

>>> print('{0:x}'.format(10))
a
>>>
>>>
>>> print('{0:X}'.format(10))
A
Representing A Float Number
A float data type also has a couple of variations which you can style using the
Python format function.

Simple Example
Let’s print a full floating point number.

>>> print("{0:f}".format(1.123456))
1.123456
Now, let’s print a floating point number truncating after three decimal points.
>>> print("{0:.3f}".format(1.123456))
1.123
Finally, let’s print a floating point number which truncates after three decimal places
but does round the final value.

>>> print("{0:.3f}".format(1.123556))
1.124
Fixed Point
>>> print('Fixed-point example: <{0:f}>'.format(2.2183))
Fixed-point example: <2.218300>
>>> print('Fixed-point with right alignment example:
<{0:25f}>'.format(2.2183))
Fixed-point with right alignment example: <
2.218300>
>>> print('Fixed-point with precision and right alignment
example: <{0:<25.10f}>'.format(2.2183))
Fixed-point with precision and right alignment example:
<2.2183000000 >
General
>>> print('General format example: <{0:g}>'.format(2.2183))
General format example: <2.2183>
>>> print('General format with right alignment example:
<{0:25g}>'.format(2.2183))
General format with right alignment example: <
2.2183>
>>> print('General format with precision and center alignment
example: <{0:^25.10g}>'.format(2.2183))
General format with precision and center alignment example: <
2.2183 >
Scientific
>>> print('Scientific format example: <{0:e}>'.format(2.2183))
Scientific format example: <2.218300e+00>
>>> print('Scientific format with left alignment example:
<{0:<25e}>'.format(2.2183))
Scientific format with left alignment example: <2.218300e+00
>
>>> print('General format with precision and right alignment
example: <{0:>25.5e}>'.format(2.2183))
General format with precision and right alignment example: <
2.21830e+00>
Format Lists And Dictionaries
Formatting A List In Python
The Python format method accepts a sequence of positional parameters. If we pass
an array or a List, then let’s find out the result.
>>> langs = ['C', 'C++', 'CSharp']
>>> print('Skillset: {}'.format(langs))
Skillset: ['C', 'C++', 'CSharp']
The whole list gets displayed. You can also decide to print one item from the
sequence by providing its index.

>>> print('Skillset: {0[1]}'.format(langs))


Skillset: C++
You can even send the list item as the positional parameters. To achieve this,
unpack them using the * operator.

>>> print('Skillset: {}'.format(*langs))


Skillset: C
Formatting A Dict In Python
Format function allows using a dictionary as a parameter. See the below example.

>>> print(" Jake's salary is {0[jake]} \n Anand's salary is


{0[anand]}".format({'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K
Anand's salary is $120K
You can format dictionary data using the keyworded arguments.

>>> print(" Jake's salary is {sal[jake]} \n Anand's salary is


{sal[anand]}".format(sal={'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K
Anand's salary is $120K

Python Operators Tutorial for Beginners to Learn

 What is an Operator in Python?


 Arithmetic operators
 Comparison operators
 Logical operators
 Bitwise operators
 Assignment operators
 Identity operators
 Membership operators
Python Operators Tutorial To Learn Step By Step

What Is An Operator In Python?


Like many programming languages, Python reserves some special characters for
acting as operators. Every operator carries out some operation such as addition,
multiplication to manipulate data and variables. The variables passed as input to an
operator are known as operands. We also recommend you to read about keywords
in Python.
Example-
>>> 7%4
3
In this case, ‘%’ is the modulus operator that calculates the remainder of the division.
The numbers ‘7’ and ‘4’ passed as input are the operands, whereas the numbers ‘3’
is the result of the action performed.

Arithmetic Operators
With arithmetic operators, we can do various arithmetic operations like addition,
subtraction, multiplication, division, modulus, exponent, etc. Python provides multiple
ways for arithmetic calculations like eval function, declare variable & calculate, or call
functions.

The table below outlines the built-in arithmetic operators in Python.

Operator
Purpose
Usage
+
Addition – Sum of two operands
a+b

Subtraction – Difference between the two operands
a-b
*
Multiplication – Product of the two operands
a*b
/
Float Division – Quotient of the two operands
a/b
//
Floor Division – Quotient of the two operands (Without fractional part)
a//b
%
Modulus – Integer remainder after division of ‘a’ by ‘b.’
a%b
**
Exponent – Product of ‘a’ by itself ‘b’ times (a to the power of b)
a**b
Example-
a=7
b=4
print('Sum : ', a+b)
print('Subtraction : ', a-b)
print('Multiplication : ', a*b)
print('Division (float) : ', a/b)
print('Division (floor) : ', a//b)
print('Modulus : ', a%b)
print('Exponent : ', a**b)
Output-
Sum : 11
Subtraction : 3
Multiplication : 28
Division (float) : 1.75
Division (floor) : 1
Modulus : 3
Exponent : 2401
Back to top
Comparison Operators
In Python programming, comparison operators allow us to determine whether two
values are equal or if one is higher than the other and then make a decision based
on the result.

The table below outlines the built-in comparison operators in Python.

Operator
Purpose
Usage
>
Greater than – if the left operand is greater than the right, then it returns true.
a>b
<
Less than – if the left operand is less than the right, then it returns true.
a<b
==
Equal to – if two operands are equal, then it returns true.
a==b
!=
Not equal to – if two operands are not equal, then it returns true.
a!=b
>=
Greater than or equal – if the left operand is greater than or equal to the right, then it
returns true.
a>=b
<=
Less than or equal – if the left operand is less than or equal to the right, then it
returns true.
a<=b
Example-
a=7
b=4

print('a > b is',a>b)

print('a < b is',a<b)

print('a == b is',a==b)

print('a != b is',a!=b)

print('a >= b is',a>=b)

print('a <= b is',a<=b)


Output-
a > b is True
a < b is False
a == b is False
a != b is True
a >= b is True
a <= b is False
Back to top
Logical Operators
Logical Python operators enable us to make decisions based on multiple conditions.
The operands act as conditions that can result in a true or false value. The outcome
of such an operation is either true or false (i.e., a Boolean value).

However, not all of these operators return a boolean result. The ‘and’ and ‘or’
operators do return one of their operands instead of pure boolean value. Whereas
the ‘not’ operator always gives a real boolean outcome.

Refer to the below table and the example to know how these operators work in
Python.

Operator
Purpose
Usage
and
if ‘a’ is false, then ‘a’, else ‘b’
a and b
or
if ‘a’ is false, then ‘b’, else ‘a’
a or b
not
if ‘a’ is false, then True, else False
not a
Example-
a=7
b=4

# Result: a and b is 4
print('a and b is',a and b)

# Result: a or b is 7
print('a or b is',a or b)

# Result: not a is False


print('not a is',not a)
Output-
a and b is 4
a or b is 7
not a is False
Back to top
Bitwise Operators
Bitwise Python operators process the individual bits of integer values. They treat
them as sequences of binary bits.

We can use bitwise operators to check whether a particular bit is set. For example,
IoT applications read data from the sensors based on a specific bit is set or not. In
such a situation, these operators can help.

Operator
Purpose
Usage
&
Bitwise AND – compares two operands on a bit level and returns 1 if both the
corresponding bits are 1
a&b
|
Bitwise OR – compares two operands on a bit level and returns 1 if any of the
corresponding bits is 1
a|b
~
Bitwise NOT – inverts all of the bits in a single operand
~a
^
Bitwise XOR – compares two operands on a bit level and returns 1 if any of the
corresponding bits is 1, but not both
a^b
>>
Right shift – shifts the bits of ‘a’ to the right by ‘b’ no. of times
a >> b
<<
Left shift – shifts the bits of ‘a’ to the left by ‘b’ no. of times
a << b
Example-
Let’s consider the numbers 4 and 6 whose binary representations are ‘00000100’
and ‘00000110’. Now, we’ll perform the AND operation on these numbers.

a=4
b=6

#Bitwise AND: The result of 'a & b' is 4


print('a & b is',a & b)
Output-
a & b is 4
The above result is the outcome of following AND (‘&’) operation.

0 0 0 0 0 1 0 0 &
0 0 0 0 0 1 1 0
------------------
0 0 0 0 0 1 0 0 (the binary representation of the number 4)
Back to top
Assignment Operators
In Python, we can use assignment operators to set values into variables.

The instruction a = 4 uses a primitive assignment operator that assigns the value 4 to
the left operand.

Below is the list of available compound operators in Python. For example, the
statement a += 4 adds to the variable and then assigns the same. It will evaluate to a
= a + 4.

Operator
Example
Similar to
=
a=4
a=4
+=
a+=4
a=a+4
-=
a-=4
a=a-4
*=
a*=4
a=a*4
/=
a/=4
a=a/4
%=
a%=4
a=a%4
**=
a**=4
a=a**4
&=
a&=4
a=a&4
|=
a|=4
a=a|4
^=
a^=4
a=a^4
>>=
a>>=4
a=a>>4
<<=
a<<=4
a=<<4
Back to top
Advanced Python Operators
Python also bundles a few operators for special purposes. These are known as
advanced Python operators like the identity operator or the membership operator.

Identity Operators
These operators enable us to compare the memory locations of two Python
objects/variables. They can let us find if the objects share the same memory
address. The variables holding equal values are not necessarily identical.

Alternatively, we can use these operators to determine whether a value is of a


specific class or type.

Refer to the below table to understand more about them.

Operator
Purpose
Usage
is
True – if both the operands refer to the same object, else False
a is b (True if id(a) and id(b) are the same)
is not
True – if the operands refer to different objects, else False
a is not b  (True if id(a) and id(b) are different)
Example-
# Using 'is' identity operator
a = 7
if (type(a) is int):
print("true")
else:
print("false")

# Using 'is not' identity operator


b = 7.5
if (type(b) is not int):
print("true")
else:
print("false")
Output-
true
true
Back to top
Membership Operators
Membership operators enable us to test whether a value is a member of other
Python objects such as strings, lists, or tuples.

In C, a membership test requires iterating through a sequence and checking each


value. But Python makes it very easy to establish membership as compared to C.

Also, note that this operator can also test against a dictionary but only for the key,
not the value.

Operator
Purpose
Usage
in
True – if the value exists in the sequence
7 in [3, 7, 9]
not in
True – if the value doesn’t found in the sequence
7 not in [3, 5, 9]
Example-
# Using Membership operator
str = 'Python operators'
dict = {6:'June',12:'Dec'}
print('P' in str)
print('Python' in str)
print('python' not in str)
print(6 in dict)
print('Dec' in dict)
Output-
True
True
True
True
False

Guide to Python Operator Precedence and


Associativity

Understand Python Namespace and Scope with


Examples
Python Operator Precedence And Associativity

 1 Python operator precedence
o 1.1 How does the operator precedence work in Python?
o 1.2 Give examples of operator precedence in Python
 2 Python operator associativity
o 2.1 What does the associativity mean in Python?
o 2.2 Give examples of associativity in Python
 3 Nonassociative operators
o 3.1 What are nonassociative operators in Python?
o 3.2 Give examples of nonassociative operators

Python Operator Precedence
How Does The Operator Precedence Work In Python?
When we group a set of values, variables, operators or function calls that turn out as
an expression. And once you execute that expression, Python interpreter evaluates it
as a valid expression.

See a simple example given below.

>>> 3 + 4
7
Here, the ‘3 +4’ is a Python expression. It contains one operator and two operands.
However, a more complex statement can include multiple operators.
To evaluate complex expressions, Python lays out the rule of precedence. It governs
the order in which the operations take place.

Give Examples Of Operator Precedence In Python


See the below example which combines multiple operators to form a compound
expression.

# Multiplication get evaluated before


# the addition operation
# Result: 17
5 + 4 * 3
However, it is possible to alter the evaluation order with the help of parentheses (). It
can override the precedence of the arithmetic operators.

# Parentheses () overriding the precedence of the arithmetic


operators
# Output: 27
(5 + 4) * 3
Operator precedence table in Python

Refer to the below table which lists the operators with the highest precedence at
the top and lowest at the bottom.

Operators
Usage
{}
Parentheses (grouping)
f(args…)
Function call
x[index:index]
Slicing
x[index]
Subscription
x.attribute
Attribute reference
**
Exponent
~x
Bitwise not
+x, -x
Positive, negative
*, /, %
Product, division, remainder
+, –
Addition, subtraction
<<, >>
Shifts left/right
&
Bitwise AND
^
Bitwise XOR
|
Bitwise OR
in, not in, is, is not, <, <=, >, >=,
<>, !=, ==
Comparisons, membership, identity
not x
Boolean NOT
and
Boolean AND
or
Boolean OR
lambda
Lambda expression
Python Operator Associativity
In the above table, you can confirm that some of the groups have many operators. It
means that all operators in a group are at the same precedence level.

And whenever two or more operators have the same precedence, then associativity
defines the order of operations.

What Does The Associativity Mean In Python?


The associativity is the order in which Python evaluates an expression containing
multiple operators of the same precedence. Almost all operators except the
exponent (**) support the left-to-right associativity.

Give Examples Of Associativity In Python


For example, the product (*) and the modulus (%) have the same precedence. So, if
both appear in an expression, then the left one will get evaluated first.

# Testing Left-right associativity


# Result: 1
print(4 * 7 % 3)

# Testing left-right associativity


# Result: 0
print(2 * (10 % 5))
As said earlier, the only operator which has right-to-left associativity in Python is the
exponent (**) operator.

See the examples below.

# Checking right-left associativity of ** exponent operator


# Output: 256
print(4 ** 2 ** 2)

# Checking the right-left associativity


# of **
# Output: 256
print((4 ** 2) ** 2)
You might have observed that the ‘print(4 ** 2 ** 2)’ is similar to ‘(4 ** 2 ** 2).

Nonassociative Operators
What Are Nonassociative Operators In Python?
Python does have some operators such as assignment operators and comparison
operators which don’t support associativity. Instead, there are special rules for the
ordering of this type of operator which can’t be managed via associativity.

Give Examples Of Nonassociative Operators


For example, the expression 5 < 7 < 9 does not mean (5 < 7) < 9 or 5 < (7 < 9). Also,
the statement 5 < 7 < 9 is same as 5 < 7 and 7 < 9, and gets evaluated from left-to-
right.
Moreover, chaining of assignments operators like a = b = c is perfectly alright
whereas the ‘a = b += c’ will result in an error.
# Set the values of a, b, c
x = 11, y = 12, z = 13

# Expression is incorrect
# Non-associative operators
# Error -> SyntaxError: invalid syntax

x = y += 12
Understand Python Namespace and Scope with
Examples

Python Namespace And Scope


What Are Names In Python?
Before getting on to namespaces, first, let’s understand what Python means by a
name.

A name in Python is just a way to access a variable like in any other languages.
However, Python is more flexible when it comes to the variable declaration. You can
declare a variable by just assigning a name to it.

You can use names to reference values.

num = 5
str = 'Z'
seq = [0, 1, 1, 2, 3, 5]
You can even assign a name to a function.

def function():
print('It is a function.')

foo = function
foo()
You can also assign a name and then reuse it. Check the below example; it is alright
for a name to point to different values.

test = -1
print("type <test> :=", type(test))
test = "Pointing to a string now"
print("type <test> :=", type(test))
test = [0, 1, 1, 2, 3, 5, 8]
print("type <test> :=", type(test))
And here is the output follows.

type <test> := <class 'int'>


type <test> := <class 'str'>
type <test> := <class 'list'>
So, you can see that one name is working perfectly fine to hold data of different
types.
You can learn more about types in Python from here – Python data types.
The naming mechanism works inline with Python’s object system, i.e., everything in
Python is an object. All the data types such as numbers, strings, functions, classes
are all objects. And a name acts as a reference to get to the objects.

What Are Namespaces In Python?


A namespace is a simple system to control the names in a program. It ensures that
names are unique and won’t lead to any conflict.

Also, add to your knowledge that Python implements namespaces in the form of
dictionaries. It maintains a name-to-object mapping where names act as keys and
the objects as values. Multiple namespaces may have the same name but pointing
to a different variable. Check out a few examples of namespaces for more clarity.

Local Namespace
This namespace covers the local names inside a function. Python creates this
namespace for every function called in a program. It remains active until the function
returns.

Global Namespace
This namespace covers the names from various imported modules used in a project.
Python creates this namespace for every module included in your program. It’ll last
until the program ends.

Built-in Namespace
This namespace covers the built-in functions and built-in exception names. Python
creates it as the interpreter starts and keeps it until you exit.

What Is Scope In Python?


Namespaces make our programs immune from name conflicts. However, it doesn’t
give us a free ride to use a variable name anywhere we want. Python restricts
names to be bound by specific rules known as a scope. The scope determines the
parts of the program where you could use that name without any prefix.

 Python outlines different scopes for locals, function, modules, and built-ins.
Check out from the below list.
 A local scope, also known as the innermost scope, holds the list of all local
names available in the current function.
 A scope for all the enclosing functions, it finds a name from the nearest
enclosing scope and goes outwards.
 A module level scope, it takes care of all the global names from the current
module.
 The outermost scope which manages the list of all the built-in names. It is the
last place to search for a name that you cited in the program.
Scope Resolution In Python – Examples
Scope resolution for a given name begins from the inner-most function and then
goes higher and higher until the program finds the related object. If the search ends
without any outcome, then the program throws a NameError exception.

Let’s now see some examples which you can run inside any Python IDE or with
IDLE.
a_var = 10
print("begin()-> ", dir())

def foo():
b_var = 11
print("inside foo()-> ", dir())

foo()

print("end()-> ", dir())


The output is as follows.

begin()-> ['__builtins__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__', 'a_var']
inside foo()-> ['b_var']
end()-> ['__builtins__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'a_var', 'foo']
In this example, we used the dir() function. It lists all the names that are available in
a Python program then.

In the first print() statement, the dir() only displays the list of names inside the current
scope. While in the second print(), it finds only one name, “b_var,” a local function
variable.

Calling dir() after defining the foo() pushes it to the list of names available in the
global namespace.

In the next example, we’ll see the list of names inside some nested functions. The
code in this block continues from the previous block.

def outer_foo():
outer_var = 3
def inner_foo():
inner_var = 5
print(dir(), ' - names in inner_foo')
outer_var = 7
inner_foo()
print(dir(), ' - names in outer_foo')
outer_foo()
The output is as follows.

['inner_var'] - names in inner_foo


['inner_foo', 'outer_var'] - names in outer_foo
The above example defines two variables and a function inside the scope of
outer_foo(). Inside the inner_foo(), the dir() function only displays one name i.e.
“inner_var”. It is alright as the “inner_var” is the only variable defined in there.

If you reuse a global name inside a local namespace, then Python creates a new
local variable with the same name.

a_var = 5
b_var = 7

def outer_foo():
global a_var
a_var = 3
b_var = 9
def inner_foo():
global a_var
a_var = 4
b_var = 8
print('a_var inside inner_foo :', a_var)
print('b_var inside inner_foo :', b_var)
inner_foo()
print('a_var inside outer_foo :', a_var)
print('b_var inside outer_foo :', b_var)

outer_foo()
print('a_var outside all functions :', a_var)
print('b_var outside all functions :', b_var)
Here goes the output of the above code after execution.

a_var inside inner_foo : 4


b_var inside inner_foo : 8
a_var inside outer_foo : 4
b_var inside outer_foo : 9
a_var outside all functions : 4
b_var outside all functions : 7
We’ve declared a global variable as “a_var” inside both the outer_foo() and
inner_foo() functions. However, we’ve assigned different values in the same global
variable. And that’s the reason the value of “a_var” is same (i.e., 4) on all occasions.
Whereas, each function is creating its own “b_var” variable inside the local scope.
And the print() function is showing the values of this variable as per its local context.

How To Correctly Import Modules In Python?


It is very likely that you would import some of the external modules in your program.
So, we’ll discuss here some of the import strategies, and you can choose the best
one.

Import All Names From A Module


from <module name> import *
It’ll import all the names from a module directly into your working namespace. Since
it is an effortless way, so you might tempt to use this method. However, you may not
be able to tell which module imported a particular function.

Here is an example of using this method.

print("namespace_1: ", dir())

from math import *


print("namespace_2: ", dir())
print(sqrt(144.2))

from cmath import *


print("namespace_3: ", dir())
print(sqrt(144.2))
The output of the above code is as follows.

namespace_1: ['__builtins__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__']
namespace_2: ['__builtins__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc',
'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp',
'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite',
'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh', 'trunc']
12.00833044182246
namespace_3: ['__builtins__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc',
'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp',
'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite',
'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'log2', 'modf', 'nan', 'phase', 'pi', 'polar', 'pow',
'radians', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh',
'trunc']
(12.00833044182246+0j)
In this example, we’ve imported two distinct math modules, one after the other.
There are some common names which both of these modules have. So, the second
module will override the definitions of functions in the first.

The first call to sqrt() returns a real number and the second one gives a complex
number. And now, there is no way we can call the sqrt() function from the first math
module.

Even if we call the function using the module name, then Python will raise
the NameError exception. So, the lesson learned here is that there are no shortcuts
for quality code.

Import Specific Names From A Module


from <module name> import <foo_1>, <foo_2>
If you are sure of the names to be used from a module, then import them directly into
your program. This method is slightly better but will not prevent you from polluting
the namespace completely. It is because you can’t use any other name from the
module. Here also, any function having the same name in your program will also
override the same definition present in the module. The affected method will become
dormant in such a case.

Check out an example of using this method.

print("namespace_1: ", dir())

from math import sqrt, pow


print("namespace_2: ", dir())
print(sqrt(144.2))
The output of the above code is as follows.

namespace_1: ['__builtins__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__']
namespace_2: ['__builtins__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'pow',
'sqrt']
12.00833044182246
Import Just The Module Using Its Name
import <module name>
It is the most reliable and suggested way of importing a module. However, it comes
with a catch that you need to prefix the name of the module before using any name
from it. But you can prevent the program from polluting the namespace and freely
define functions with matching names in the module.

print("namespace_1: ", dir())

import math
print("namespace_2: ", dir())
print(math.sqrt(144.2))
The output of the above example goes like this.

namespace_1: ['__builtins__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__']
namespace_2: ['__builtins__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'math']
12.00833044182246

Python For Loop – A Complete Guide for


Beginners

A “for” loop is the most preferred control flow statement to be used in a Python
program. It is best to use when you know the total no. of iterations required for
execution.

It has a clearer and simple syntax and can help you iterate through different types of
sequences. Python supports seven sequence data types: standard/Unicode strings, a
list, tuples, a bytearray, and xrange objects. There are sets and dictionaries as well,
but they are just containers for the sequence types.
Table of Content

 What is a For Loop?
 For Loop Syntax
 For Loop Workflow
 Examples of For Loop
 Range() function with For Loop
 What is Range() Function
 Range() Function Example
 Else Clause with For loop
 Syntax
 For-Else Flowchart
 For-Else Example
1. What Is A Python For Loop?
A for loop in Python requires at least two variables to work. The first is the iterable
object such as a list, tuple or a string. And second is the variable to store the
successive values from the sequence in the loop.

1.1. Python For Loop Syntax


In Python, you can use the “for” loop in the following manner.

for iter in sequence:


statements(iter)
The “iter” represents the iterating variable. It gets assigned with the successive
values from the input sequence.
The “sequence” may refer to any of the following Python objects such as a list, a
tuple or a string.
1.2. For Loop WorkFlow In Python
The for loop can include a single line or a block of code with multiple statements.
Before executing the code inside the loop, the value from the sequence gets
assigned to the iterating variable (“iter”).
Below is the flowchart representation of a Python For Loop.

Regular Python For Loop Flowchart


1.3.1. Python For Loop Example – Print Characters Of A String
vowels="AEIOU"
for iter in vowels:
print("char:", iter)
The above code is traversing the characters in the input string named as the vowels.
Its output is as follows.

char: A
char: E
char: I
char: O
char: U
1.3.2. Python For Loop Example – Find The Average Of N
Numbers
We’ll use the following steps to calculate the sum of N numbers.

1. Create a list of integers and populate with N (=6) values.


2. Initialize a variable (sum) for storing the summation.
3. Loop N (=6) number of times to get the value of each integer from the list.
4. In the loop, add each value with the previous and assign to a variable named
as the sum.
5. Divide the “sum” with N (=6). We used the len() function to determine the size
of our list.
6. The output of the previous step is the average we wanted.
7. Finally, print both the “sum” and the average.
Below is the Python code for the above program.

int_list = [1, 2, 3, 4, 5, 6]
sum = 0
for iter in int_list:
sum += iter
print("Sum =", sum)
print("Avg =", sum/len(int_list))
Here is the output after executing the above code.

Sum = 21
Avg = 3.5
2. Range() Function With For Loop
2.1. What Is Range() Function?
The range() function can produce an integer sequence at runtime. For example, a
statement like range(0, 10) will generate a series of ten integers starting from 0 to 9.
Below snippet is interpreting more about the functional aspect of the range() function.
>>> type(range(0, 10))
<class 'range'>
>>> range(0, 10)[0]
0
>>> range(0, 10)[1]
1
>>> range(0, 10)[9]
9
>>> len(range(0, 10))
10
>>>
2.2. Range() Function Example
Let’s now use the range() with a “for” loop.

for iter in range(0, 3):


print("iter: %d" % (iter))
It will yield the following result.

iter: 0
iter: 1
iter: 2
By default, the “for” loop fetches elements from the sequence and assigns to the
iterating variable. But you can also make the “for” loop returning the index
by replacing the sequence with a range(len(seq)) expression.
books = ['C', 'C++', 'Java', 'Python']
for index in range(len(books)):
print('Book (%d):' % index, books[index])
The following lines will get printed.

Book (0): C
Book (1): C++
Book (2): Java
Book (3): Python
Read details here – Python range function
3. Else Clause With Python For Loop
Interestingly, Python allows using an optional else statement along with
the “for” loop.
The code under the else clause executes after the completion of the “for” loop.
However, if the loop stops due to a “break” call, then it’ll skip the “else” clause.
3.1. Syntax
# Foe-Else Syntax

for item in seq:


statement 1
statement 2
if <cond>:
break
else:
statements
Look at the below For Loop with Else flowchart.

3.2. For-Else Flowchart

3.3. For-Else Example


birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']
ignoreElse = False

for theBird in birds:


print(theBird )
if ignoreElse and theBird is 'Snow':
break
else:
print("No birds left.")
The above code will print the names of all birds plus the message in the “else” part.
Belle
Coco
Juniper
Lilly
Snow
No birds left.

Python While Loop – A Complete Guide for


Beginners

Table of Content
 What is a While Loop?
 While Loop Syntax
 While Loop Workflow
 Example – While Loop Demo
 Else Clause with While Loop
 Example – While with Else
1. What Is A Python While Loop?
A while loop is a control flow structure which repeatedly executes a block of code
indefinite no. of times until the given condition becomes false. For example, say, you
want to count the occurrence of odd numbers in a range. Some technical references
call it a pre-test loop as it checks the condition before every iteration.

1.1. Python While Loop – Syntax


while some condition (or expression) :
a block of code
The syntax is clearly stating that Python first evaluates the condition.

If the check fails, then the control won’t enter into the loop instead will get transferred
to the next statement. Whereas if the condition passes, then the statements inside
the loop shall execute.

This cycle would repeat itself until the while condition fails or returns false. When
such a situation would occur, the loop would break and pass control to the next
executable statement.

1.2. Python While Loop Workflow


1.3. While Loop In Python – Example
This example exhibits how to count the occurrences of odd numbers in a range
entered by the user excluding the endpoints.

#custom debug print function


def dbgprint(x):
if debug == True:
print(x)

#ask user to enter the range values


debug = False
r1 = int(input("Enter the starting range value?"))
r2 = int(input("Enter the ending range value?"))

dbgprint("Range: %d - %d" % (r1, r2))

num = r1 + 1
count = 0

while num < r2:


dbgprint("num: %d" % (num))
res = num % 2
dbgprint("res: %d" % (res))
if (num % 2) > 0:
count += 1
num += 1
print("Odd count: %d" % (count))
Once you finish up the execution of the above code, you should see the following
output.

Enter the starting range value? 1


Enter the ending range value? 100
Odd count: 49
In this program, we are using the following four variables.

1. r1 – starting range value


2. r2 – ending range value
3. num – the variable we are testing for an odd number
4. count – the counter variable, incremented upon every positive test
We’ve initialized the “num” variable with the starting offset plus one and the counter
variable with a zero. The loop is testing if “num” remains less than the ending offset
value else it’ll break.
In each iteration, the code block inside the loop is calculating the remainder of
the “num” variable. A non-zero result would mean the number is odd and
the “count” var would get incremented by one.
The last statement in the while loop is stepping up the value of “num” by one, and it
goes through for re-execution. The loop shall stop only after the value of
the “num” is equal to or more than the ending range offset, i.e., “r2”.
2. Else Clause With Python While Loop
In Python, we can add an optional else clause after the end of “while” loop.
The code inside the else clause would always run but after the while loop finishes
execution. The one situation when it won’t run is if the loop exits after
a “break” statement.
Using the else clause would make sense when you wish to execute a set of
instructions after the while loop ends, i.e., without using a break statement.

Let’s now see an example to demonstrate the use of “else” in the Python while loop.
2.1. While Loop With Else In Python – Example
def while_else_demo():

count = 0
while count < 5 :
num = int(input("Enter number between 0-100?"))
if (num < 0) or (num > 100):
print("Aborted while: You've entered an invalid
number.")
break
count += 1
else:
print("While loop ended gracefully.")
while_else_demo()
The above program runs the while loop until the count is less than 5.

It takes a number between 0-100 as input. If you enter a valid number 5 times, then
the while loop runs successfully, and the message from the else clause would get
displayed.

If you enter an invalid number, then the loop would get aborted without execting the
code in the else.

Iteration#1 While loop finishes with success and “else” clause executes.
Enter number between 0-100?1
Enter number between 0-100?2
Enter number between 0-100?3
Enter number between 0-100?4
Enter number between 0-100?5
While loop ended gracefully.
Iteration#2 While loop aborts and “else” clause won’t execute.
Enter number between 0-100?1
Enter number between 0-100?101
Aborted while: You've entered an invalid number.

Python If Else, If Elif Else, Nested If for Decision


Making

Python Conditions/Decision-Making Statements


Table of Content
 if Statement
 Syntax
 Flowchart
 Example
 if Else in One Line
 if Else Statement
 Syntax
 Flowchart
 Example
 if-Elif-Else Statement
 Syntax
 Flowchart
 Example
 Nested If-Else Statement
 Syntax
 Flowchart
 Example
 Using Not Operator with If Else
 Examples
 Using And Operator with If Else
 Flowchart
 Example
 Using In Operator with If Else
 Examples
Go back to ☛ Python Tutorial
Python If Statement
A bare Python if statement evaluates whether an expression is True or False. It
executes the underlying code only if the result is True.

Given below is the syntax of Python if statement.

Syntax
if Logical_Expression :
Indented Code Block
Flowchart

Basic Python if Statement Flowchart


Example
days = int(input("How many days in a leap year? "))
if days == 366:
print("You have cleared the test.")
print("Congrats!")
The output of the above code is –

How many days in a leap year? 366


You have cleared the test.
Congrats!
Python If Else Statement
A Python if else statement takes action irrespective of what the value of the
expression is.

If the result is True, then the code block following the expression would run.
Otherwise, the code indented under the else clause would execute.

Given below is the syntax of Python if Else statement.

Syntax
if Logical_Expression :
Indented Code Block 1
else :
Indented Code Block 2
Flowchart

If-Else Statement Flowchart


Example
answer = input("Is Python an interpreted language? Yes or No
>> ").lower()

if answer == "yes" :
print("You have cleared the test.")
else :
print("You have failed the test.")

print("Thanks!")
When you run the above code, it asks for your input. It converts the entered value it
into lower case and runs the if-else condition.

If you enter a ‘yes,’ then the output of the above code would be –

Is Python an interpreted language? Yes or No >> yes


You have cleared the test.
Thanks!
If you enter a ‘no,’ then the result of the above code would be –

Is Python an interpreted language? Yes or No >> no


You have failed the test.
Thanks!
Python If Else In One Line
Python provides a way to shorten an if/else statement to one line. Let’s see how can
you do this.

The one-liner If-else has the following syntax:

# If Else in one line - Syntax


value_on_true if condition else value_on_false
See the below example of If-Else in one line.

>>> num = 2
>>> 'Even' if num%2 == 0 else 'Odd'
'Even'
>>> num = 3
>>> 'Even' if num%2 == 0 else 'Odd'
'Odd'
>>> num = 33
>>> 'Even' if num%2 == 0 else 'Odd'
'Odd'
>>> num = 34
>>> 'Even' if num%2 == 0 else 'Odd'
'Even'
>>>
Python If-Elif-Else Statement
The first three if-else constructs can only address two outcomes, i.e., True or False.
However, the expression next to “if” can also evaluate to a value different from the
boolean. It means to have more conditions, not just a single “else” block.

Python supports to specify multiple conditions by using an “elif” clause with each of
the expression.

Given below is the syntax of Python if-elif-else statement.

Syntax
if Logical_Expression_1 :
Indented Code Block 1
elif Logical_Expression_2 :
Indented Code Block 2
elif Logical_Expression_3 :
Indented Code Block 3
...
else :
Indented Code Block N
Flowchart

If Elif Else Statement Flowchart


Example
while True:
response = input("Which Python data type is an ordered
sequence? ").lower()
print("You entered:", response)

if response == "list" :
print("You have cleared the test.")
break
elif response == "tuple" :
print("You have cleared the test.")
break
else :
print("Your input is wrong. Please try again.")
This program has a while loop where it is querying about Python data types. It wants
you to enter the name of an ordered sequence. If you provide a wrong value, then it
would again prompt you for the correct input.

Only by entering the correct value, the loop could break. However, you can also
press the CTRL+C to exit the program.

Had you entered a wrong answer, then the output would be :

Which Python data type is an ordered sequence? dictionary


You entered: dictionary
Your input is wrong. Please try again.
Which Python data type is an ordered sequence?
Once you provide the correct answer, the program would end with the following
output.

Which Python data type is an ordered sequence? tuple


You entered: tuple
You have cleared the test.
Nested If-Else In Python
Some programs may have a code block under an “if” clause. And it could have
subsequent conditional blocks.

In such a case, Python allows nesting of an if-else or if-elif-else inside another


conditional clause.

Python doesn’t limit the level of nested conditions in a program. Given below is the
syntax of a multi-level nested if-elif-else statement.

Syntax
if Logical_Expression_1 :
if Logical_Expression_1.1 :
if Logical_Expression_1.1.1 :
Indented Code Block 1.1.1
else
Indented Code Block
elif Logical_Expression_1.2 :
Indented Code Block 1.2
else :
Indented Code Block
elif Logical_Expression_2 :
Indented Code Block 2
elif Logical_Expression_3 :
Indented Code Block 3
...
else :
Indented Code Block
Flowchart
Nested Condition Statement Flowchart
The above diagram represents the following code flow.

x = 10
y = 20
z = 30

print("Start")
if x == 10:
print(" Nested If")
if y == 20:
print(" End of Nested If Block ")
else:
print(" End of Nested If-Else Block ")
elif y == 20:
print(" Elif block ")
else:
print(" Nested If")
if z == 30:
print(" End of Nested If Block ")
else:
print(" End of Nested If-Else Block ")
print("Stop")
Example
while True:
response = int(input("How many days are there in a leap
year? "))
print("You entered:", response)

if response == 366 :
print("You have cleared the first level.")
response = input("What month has an extra day in leap
year?? ").lower()
if response == "february" :
print("You have cleared the test.")
break
else :
print("You have failed the test.")
break
else :
print("Your input is wrong, please try again.")
The above code demonstrates the use of nested if in Python. It first asks a question
from the user. After that, there is an if statement to check whether the answer is
correct or not. In case the user provides the right input, then he faces another
question. Now, the nested IF comes into the picture checking the latest response
from the user.

Using Not Operator With Python If Else


The ‘not’ is a negation logical operator in Python. It reverses the result of its operand
and converts to a boolean outcome, i.e., True or False. The operand could be a
variable or an expression evaluating to a numeric type.

Example-1
a = 10
b = 20
if not a > b :
print("The number %d is less than %d" %(a, b))/
The output of the above code is -
The number 10 is less than 20
Example-2
X = 0
if not X :
print("X is not %d" %(X))
else :
print("X is %d" %(X))
The output of the above code is –

X is not 0
Using And Operator With If Else
By using the ‘and’ operator, you can join multiple expression in a Python if condition.
It is also a logical operator which evaluates as True if both/all the operands (x and y
and z) are True.

Flowchart
You can find the code of this flowchart in the underlying example.
Using And Operator in Python Conditions
Example
Check out the following example to see the ‘and’ operator in action.

a = 10
b = 20
c = 30

avg = (a + b + c) / 3
print("avg =", avg)

if avg > a and avg > b and avg > c:


print("%d is higher than %d, %d, %d" %(avg, a, b, c))
elif avg > a and avg > b:
print("%d is higher than %d, %d" %(avg, a, b))
elif avg > a and avg > c:
print("%d is higher than %d, %d" %(avg, a, c))
elif avg > b and avg > c:
print("%d is higher than %d, %d" %(avg, b, c))
elif avg > a:
print("%d is just higher than %d" %(avg, a))
elif avg > b:
print("%d is just higher than %d" %(avg, b))
elif avg > c:
print("%d is just higher than %d" %(avg, c))
The output of the above code is –

avg = 20.0
20 is just higher than 10
Using In Operator With If Else
Python “in” operator allows comparing a variable against multiple values in a single
line. It makes decision making more comfortable by reducing the use of many if-elif
statements.

In Python, we often refer to it as the membership operator. It can let you check value
from objects of different types. They could be a list, tuple, string, dictionary types.

Examples
This example first creates a list of six numbers. After that, there is a for loop which is
traversing it and prints values.

The loop has an if statement which prints specific numbers from the list which are
not in the tuple used in the condition.

Hence, we’ve also used the “not” along with the “in” operator.

#Example of "in" operator with Python If statement

num_list = [1, 10, 2, 20, 3, 30]


for num in num_list:
if not num in (2, 3):
print ("Allowed Item:", num)
The output of the above code is as follows.

Allowed Item: 1
Allowed Item: 10
Allowed Item: 20
Allowed Item: 30
Let’s check out one more example. It has two teams of players (team1 and team2)
for two games. In here, we’ve to find who from the “team1” also plays for the
“team2”.

# Find players who play both games

team1 =["Jake", "Allan", "Nick", "Alex", "Dave"]


team2 =["David", "John", "Chris", "Alex", "Nick"]

for aplayer in team1:


if aplayer in team2:
print("%s also plays for team2." %(aplayer))
The output of the above code is as follows.

Nick also plays for team2.


Alex also plays for team2.

How to Implement Switch Case Statement in


Python

Python Switch Case Statement


Unlike other programming languages, Python doesn’t provide a switch case
instrument over the self.

However, it has many other constructs like a dictionary, lambda function,


and classes to write a custom implementation of the Python switch case statement.
If you are keen to know why Python doesn’t have a switch case, then do refer the
explanation at PEP 3103.
Before diving into further, let’s have a quick view of the most common example of a
switch case statement in the C programming language.

A Typical Switch Case In C Programming


 In C, you can only pass an integer or enum value to the switch-case
statement.
 Unlike the if…else block which requires evaluating expressions in each
condition, the switch has a single point of interaction which leads to different
paths of execution.
 A switch is a control instruction which decides the control to flow based on the
value of a variable or an expression.
In the below example, the variable ‘dayOfWeek’ is a constant integer variable which
represents days in a week. And the switch-case block prints the name of the day
based on its value.

switch (dayOfWeek) {
case 1:
printf("%s", Monday);
break;
case 2:
printf("%s", Tuesday);
break;
case 3:
printf("%s", Wednesday);
break;
case 4:
printf("%s", Thursday);
break;
case 5:
printf("%s", Friday);
break;
case 6:
printf("%s", Saturday);
break;
case 7:
printf("%s", Sunday);
break;
default:
printf("Incorrect day");
break;
}
There are a couple of facts to consider for the switch-case statement.

 The expression under the switch gets evaluated once.


 It should result in a constant integer value. [Note: In Python, we can alter this
behavior.]
 A case with a duplicate value should not appear.
 If no case matches, then the default case gets executed.
Implement Python Switch Case Statement
Switch Case Using A Dictionary
It is simple to use a dictionary for implementing the Python switch case statement.
Follow the below steps.

 First, define individual functions for every case.


 Make sure there is a function/method to handle the default case.
 Next, make a dictionary object and store each of the function beginning with
the 0th index.
 After that, write a switch() function accepting the day of the week as an
argument.
 The switch() calls the get() method on the dictionary object which returns the
function matching the argument and invokes it simultaneously.
# Implement Python Switch Case Statement using Dictionary

def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"

switcher = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}

def switch(dayOfWeek):
return switcher.get(dayOfWeek, default)()

print(switch(1))
print(switch(0))
The output is as follows:

Monday
Incorrect day
Switch Case Using A Class
It is quite easy to use a class for implementing the Python switch case statement.
Let’s do it with an example.

 In the below example, there is a PythonSwitch class which defines the


switch() method.
 It takes the day of the week as an argument, converts it to string and appends
to the ‘case_’ literal. After that, the resultant string gets passed to the getattr()
method.
 The getattr() method returns a matching function available in the class.
 If the string doesn’t find a match, then the getattr() returns the lambda function
as default.
 The class also have the definition for functions specific to different cases.
# Implement Python Switch Case Statement using Class

class PythonSwitch:

def switch(self, dayOfWeek):


default = "Incorrect day"
return getattr(self, 'case_' + str(dayOfWeek), lambda:
default)()

def case_1(self):
return "Monday"

def case_2(self):
return "Tuesday"

def case_3(self):
return "Wednesday"

s = PythonSwitch()

print(s.switch(1))
print(s.switch(0))

Python Function – A Step by Step Guide for


Beginners

Table Of Content
 What is a Function in Python?
 How to Create a Function – Syntax
 Def Statement
 How to Call a Function in Python?
 Example of a Function Call
 Polymorphism in Python
 How to Pass Parameters to a Function?
 Immutable Vs. Mutable Arguments
 Standard Arguments
 Arguments with Default Values
 Keyword-based Arguments
 Variable Arguments
 Local Variables inside a Function
 Global Variables in a Function
 Name Resolution
 Scope Lookup
 Return Statement
 Functions Examples
 General Function
 Recursive Function
 Functions as Objects
 Function Attributes
Go back to ☛ Python Tutorial
What Is A Python Function?
A function in Python is a logical unit of code containing a sequence of statements
indented under a name given using the “def” keyword.

Functions allow you to create a logical division of a big project into smaller modules.
They make your code more manageable and extensible.

While programming, it prevents you from adding duplicate code and promotes
reusability.

How To Create A Function – Syntax


The syntax of a Python function is as follows.

Single line function:


def single_line(): statement
Python function with docstring:
def fn(arg1, arg2,...):
"""docstring"""
statement1
statement2
Nested Python function:
def fn(arg1, arg2,...):
"""docstring"""
statement1
statement2
def fn_new(arg1, arg2,...):
statement1
statement2
...
...
TOC
Def Statement
Please read the below notes before creating your first Python function.

 The “def” keyword is a statement for defining a function in Python.


 You start a function with the def keyword, specify a name followed by a colon
(:) sign.
 The “def” call creates the function object and assigns it to the name given.
 You can further re-assign the same function object to other names.
 Give a unique name to your function and follow the same rules as naming
the identifiers.
 Add a meaningful docstring to explain what the function does. However, it is
an optional step.
 Now, start the function body by adding valid Python statements each indented
with four spaces.
 You can also add a statement to return a value at the end of a function.
However, this step is optional.
 Just press enter and remove the indentation to end a function.
 Since def is a statement, so you can use it anywhere a statement can appear
– such as nested in an if clause or within another function.
Example :
if test:
def test(): # First definition
...
else:
def test(): # Alternate definition
...
...
TOC
How To Call A Function In Python?
By using the def keyword, you learned to create the blueprint of a function which has
a name, parameters to pass and a body with valid Python statements.
The next step is to execute it. You can do so by calling it from the Python script or
inside a function or directly from the Python shell.

To call a function, you need to specify the function name with relevant parameters,
and that’s it.
Follow the below example to learn how to call a function in Python.

Example Of A Function Call


It’s a simple example where a function “typeOfNum()” has nested functions to decide
on a number is either odd or even.

def typeOfNum(num): # Function header


# Function body
if num % 2 == 0:
def message():
print("You entered an even number.")
else:
def message():
print("You entered an odd number.")
message()
# End of function

typeOfNum(2) # call the function


typeOfNum(3) # call the function again
TOC
Polymorphism In Python
In Python, functions polymorphism is possible as we don’t specify the argument
types while creating functions.
 The behavior of a function may vary depending upon the arguments passed
to it.
 The same function can accept arguments of different object types.
 If the objects find a matching interface, the function can process them.
Example :
def product(x, y) : return x * y
print(product(4, 9)) # function returns 36
print(product('Python!', 2)) # function returns
# Python!Python!
print(product('Python 2 or 3?', '3')) # TypeError occurs
The above example clarifies that we can pass any two objects to the product()
function which supports the ‘*’ operator.

The concept above we’ve explained is known as polymorphism. Some points which
you should remember are as follows.

 Python is a dynamically typed language which means the types correlate with
values, not with variables. Hence, the polymorphism runs unrestricted.
 That’s one of the primary differences between Python and other statically
typed languages such as C++ or Java.
 In Python, you don’t have to mention the specific data types while coding.
 However, if you do, then the code limits to the types anticipated at the time of
coding.
 Such code won’t allow other compatible types that may require in the future.
 Python doesn’t support any form of function overloading.
TOC
Parameters In A Function
We often use the terms parameters and arguments interchangeably. However, there
is a slight difference between them.
Parameters are the variables used in the function definition whereas arguments are
the values we pass to the function parameters.
Python supports different variations of passing parameters to a function. Before we
discuss each of them, you should read the following notes.

 The argument gets assigned to the local variable name once passed to the
function.
 Changing the value of an argument inside a function doesn’t affect the caller.
 If the argument holds a mutable object, then changing it in a function impacts
the caller.
 We call the passing of immutable arguments as Pass by Value because
Python doesn’t allow them to change in place.
 The passing of mutable arguments happens to be Pass by Pointer in Python
because they are likely to be affected by the changes inside a function.
Example: Immutable Vs. Mutable
def test1(a, b) :
a = 'Garbage' # 'a' receives an immutable object
b[0] = 'Python' # 'b' receives a list object
# list is mutable
# it can undergo an in place change
def test2(a, b) :
a = 'Garbage 2'
b = 'Python 3' # 'b' now is made to refer to new
# object and therefore argument 'y'
# is not changed

arg1 = 10
arg2 = [1, 2, 3, 4]
test1(arg1, arg2)
print("After executing test 1 =>", arg1, arg2)
test2(arg1, arg2)
print("After executing test 2 =>", arg1, arg2)
After execution, the above code prints the following.

After executing test 1 => 10 ['Python', 2, 3, 4]


After executing test 2 => 10 ['Python', 2, 3, 4]
Example: How To Avoid Changing The Mutable Argument
def test1(a, b) :
a = 'Garbage'
b[0] = 'Python'

arg1 = 10
arg2 = [1, 2, 3, 4]

print("Before test 1 =>", arg1, arg2)


test1(arg1, arg2[:]) # Create an explicit copy of mutable
object
# 'y' in the function.
# Now 'b' in test1() refers to a
# different object which was initially a
# copy of 'arg2'

print("After test 1 =>", arg1, arg2)


After execution, the above code prints the following.

Before test 1 => 10 [1, 2, 3, 4]


After test 1 => 10 [1, 2, 3, 4]
TOC
Standard Arguments
The standard arguments are those which you pass as specified in a Python function
definition. It means without changing their order and without skipping any of them.

def fn(value):
print(value)
return

fn()
Executing the above code throws the below error as we’ve not passed the single
argument required.

TypeError: fn() missing 1 required positional argument:


'value'
Keyword-Based Arguments
When you assign a value to the parameter (such as param=value) and pass to the
function (like fn(param=value)), then it turns into a keyword argument.

If you pass the keyword arguments to a function, then Python determines it through
the parameter name used in the assignment.

See the below example.

def fn(value):
print(value)
return

fn(value=123) # output => 123


fn(value="Python!") # output => Python!
While using keyword arguments, you should make sure that the name in the
assignment should match with the one in the function definition. Otherwise, Python
throws the TypeError as shown below.

fn(value1="Python!") # wrong name used in the keyword argument


The above function call causes the following error.

TypeError: fn() got an unexpected keyword argument 'value1'


Arguments With Default Values
Python functions allow setting the default values for parameters in the function
definition. We refer them as the default arguments.

The callee uses these default values when the caller doesn’t pass them in the
function call.
The below example will help you clearly understand the concept of default
arguments.

def daysInYear(is_leap_year=False):
if not is_leap_year:
print("365 days")
else:
print("366 days")
return

daysInYear()
daysInYear(True)
Here, the parameter “is_leap_year” is working as a default argument. If you don’t
pass any value, then it assumes the default which is False.

The output of the above code is:

365 days
366 days
Variable Arguments
You may encounter situations when you have to pass additional arguments to a
Python function. We refer them as variable-length arguments.

The Python’s print() is itself an example of such a function which supports variable
arguments.

To define a function with variable arguments, you need to prefix the parameter with
an asterisk (*) sign. Follow the below syntax.

def fn([std_args,] *var_args_tuple ):


"""docstring"""
function_body
return_statement
Check out the below example for better clarity.

def inventory(category, *items):


print("%s [items=%d]:" % (category, len(items)), items)
for item in items:
print("-", item)
return

inventory('Electronics', 'tv', 'lcd', 'ac', 'refrigerator',


'heater')
inventory('Books', 'python', 'java', 'c', 'c++')
The output of the above code goes like this.

Electronics [items=5]: ('tv', 'lcd', 'ac', 'refrigerator',


'heater')
- tv
- lcd
- ac
- refrigerator
- heater
Books [items=4]: ('python', 'java', 'c', 'c++')
- python
- java
- c
- c++
Please note that you can choose to have a formal argument or not in the function
definition along with the variable arguments.

You may choose to skip the variable arguments while calling the function. In such a
case, the tuple would remain empty.

TOC
Local Variables Inside A Function
A local variable has visibility only inside a code block such as the function def.

They are available only while the function is executing.

Check out the below example of using local variables.

def fn(a, b) :
temp = 1
for iter in range(b) :
temp = temp*a
return temp

print(fn(2, 4))

print(temp) # error : can not access 'temp' out of scope of


function 'fn'
print(iter) # error : can not access 'iter' out of scope of
function 'fn'
In this example, we try to access local variables outside the function body which
results in the NameError.
Function’s local variables don’t retain values between calls. The names used inside
a def do not conflict with variables outside the def, even if you’ve used the same
names elsewhere.

In Python, the variables assignment can occur at three different places.

 Inside a def – it is local to that function


 In an enclosing def – it is nonlocal to the nested functions
 Outside all def(s) – it is global to the entire file
TOC
Global Variables In A Function
The global keyword is a statement in Python. It enables variable (names) to retain
changes that live outside a def, at the top level of a module file.

In a single global statement, you can specify one or more names separated by
commas.

All the listed names attach to the enclosing module’s scope when assigned or
referenced within the function body.

Check the below example.

x = 5
y = 55
def fn() :
global x
x = [3, 7]
y = [1, 33, 55]
# a local 'y' is assigned and created here
# whereas, 'x' refers to the global name
fn()
print(x, y)
In the above code, ‘x’ is a global variable which will retain any change in its value
made in the function. Another variable ‘y’ has local scope and won’t carry forward the
change.

Let’s now see how a globally declared name behaves in two different Python
functions.

foo = 99

def fn1() :
foo = 'new' # new local foo created
def fn2() :
global foo
foo = 'update' # value of global foo changes
In the next example, let’s see how global behaves with the import statement.

Here, we have got the following three scripts:

 mod_global.py: It contains the global definition and a function changing and


displaying values.
 test1.py: It imports the first file and accesses the global variable.
 test2.py: It is using the “from” clause to import the first file and accessing the
global variable.
# mod_global.py
def fn1() :
global x
x = [1,2] ; y = [20, 200]
# a local 'y' is created – availableonly within 'f1'
# 'x' can be accessed anywhere after a call to 'f1'
fn1()
try :
print(x, y) # name 'y' is not defined – error
except Exception as ex:
print('y ->', ex)
print('x ->', x)
# test1.py
import mod_global
print('test1 ->', mod_global.x)
# test2.py
from mod_global import *
print('test2 ->', x)
TOC
Name Resolution In A Python Function
It is essential to understand how name resolution works in case of a def statement.

Here are a few points you should keep in mind.

 The name assignments create or change local names.


 The LEGB rule comes in the picture for searching the name reference.
 local – L
 then enclosing functions (if any) – E
 next comes the global – G
 and the last one is the built-in – B
To gain more understanding, run through the below example.
#var = 5
def fn1() :
#var = [3, 5, 7, 9]
def fn2() :
#var = (21, 31, 41)
print(var)
fn2()
fn1() # uncomment var assignments one-by-one and check the
output
print(var)
After uncommenting the first “var” assignment, the output is:

5
5
Next, after uncommenting the second “var” assignment as well, the output is:

[3, 5, 7, 9]
5
Finally, if we uncomment the last “var” assignment, then the result is as follows.

(21, 31, 41)


5
TOC
Scope Lookup In Functions
Python functions can access names in all available enclosing def statements.

Check the below example.

X = 101 # global scope name - unused


def fn1():
X = 102 # Enclosing def local
def fn2():
print(X) # Reference made in nested def
fn2() # Prints 102: enclosing def local
fn1()
The scope lookup remains in action even if the enclosing function has already
returned.

def fn1():
print('In fn1')
X = 100
def fn2():
print('In fn2')
print(X) # Remembers X in enclosing def scope
return fn2 # Return fn2 but don't call it
action = fn1() # Make, return function
action() # Call fn2() now: prints 100
The output is as follows.

In fn1
In fn2
100
TOC
Return Values From A Python Function
In Python functions, you can add the “return” statement to return a value.

Usually, the functions return a single value. But if required, Python allows returning
multiple values by using the collection types such as using a tuple or list.

This feature works like the call-by-reference by returning tuples and assigning the
results back to the original argument names in the caller.

def returnDemo(val1, val2) :


val1 = 'Windows'
val2 = 'OS X'
return val1, val2 # return multiple values in a tuple

var1 = 4
var2 = [2, 4, 6, 8]

print("before return =>", var1, var2)


var1, var2 = returnDemo(var1, var2)
print("after return =>", var1, var2)
The above code gives the following output.

before return => 4 [2, 4, 6, 8]


after return => Windows OS X
TOC
Function Examples
General Function
Check out a general function call example.

def getMin(*varArgs) :
min = varArgs[0]
for i in varArgs[1:] :
if i < min :
min = i
return min

min = getMin(21, -11, 17, -23, 6, 5, -89, 4, 9)


print(min)
The output is as follows.

-89
Recursive Function
Next is an example of the recursive function.

def calcFact(num) :
if(num != 1) :
return num * calcFact(num-1)
else :
return 1

print(calcFact(4))
The output is as follows.

24
TOC
Python Functions As Objects
Yes, Python treats everything as an object and functions are no different.

You can assign a function object to any other names.


def testFunc(a, b) : print('testFunc called')
fn = testFunc
fn(22, 'bb')
The output is:

testFunc called
You can even pass the function object to other functions.
def fn1(a, b) : print('fn1 called')
def fn2(fun, x, y) : fun(x, y)
fn2(fn1, 22, 'bb')
The output is:

fn1 called
You can also embed a function object in data structures.
def fn1(a) : print('fn1', a)
def fn2(a) : print('fn2', a)

listOfFuncs = [(fn1, "First function"), (fn2, "Second


function")]
for (f, arg) in listOfFuncs : f(arg)
The output is:

fn1 First function


fn2 Second function
You can return a function object from another function.
def FuncLair(produce) :
def fn1() : print('fn1 called')
def fn2() : print('fn2 called')
def fn3() : print('fn3 called')
if produce == 1 : return fn1
elif produce == 2 : return fn2
else : return fn3

f = FuncLair(2) ; f()
The output is:

fn2 called
TOC
Function Attributes
Python functions also have attributes.

 You can list them via the dir() built-in function.


 The attributes can be system-defined.
 Some of them can be user-defined as well.
 The dir() function also lists the user-defined attributes.
def testFunc():
print("I'm just a test function.")

testFunc.attr1 = "Hello"
testFunc.attr2 = 5
testFunc()
print(dir(testFunc))
The output is:

I'm just a test function.


['__annotations__', '__call__', '__class__', '__closure__',
'__code__', '__defaults__',
Python Class and OOPs Fundamentals with
Examples

Python Class And Objects – Introduction


Contents [hide]
 1 Can I use OOP with Python?
 2 What is a Python class?
 3 How to create a class in Python?
o 3.1 The “class” keyword
o 3.2 What is self?
o 3.3 What is __init__ (constructor) in Python?
o 3.4 The instance attributes
o 3.5 The class attributes
 4 Python class demo
o 4.1 Create a BookStore class in Python
o 4.2 UML diagram of BookStore class

☛ Go back to Python Tutorials


Can I Use OOP With Python?
Yes, Python supports object-oriented programming (OOP). OOP is a development
model which lets a programmer focus on producing reusable code. It is different from
the procedural model which follows a sequential approach.

OOP is useful when you have a large and complicated project to work. There will be
multiple programmers creating reusable code, sharing and integrating their source
code. Reusability results in better readability and reduces maintenance in the longer
term.

What Is A Python Class?


A class is an arrangement of variables and functions into a single logical entity. It
works as a template for creating objects. Every object can use class variables and
functions as its members.

Python has a reserved keyword known as “class” which you can use to define a new
class.

The object is a working instance of a class created at runtime.

How To Create A Class In Python?


There are some terms which you need to know while working with classes in Python.

1. The “class” keyword


2. The instance attributes
3. The class attributes
4. The “self” keyword
5. The “__init_” method

Let’s now have a clear understanding of each of the above points one by one.

The “Class” Keyword


With the class keyword, we can create a Python class as shown in the example
below.

class BookStore:
pass
What Is Self?
Python provides the “self” keyword to represent the instance of a class. It works as a
handle for accessing the class members such as attributes from the class methods.

Also, please note that it is implicitly the first argument to the __init__ method in every
Python class. You can read about it below.

What Is __init__ (Constructor) In Python?


The “__init__()” is a unique method associated with every Python class.

Python calls it automatically for every object created from the class. Its purpose is to
initialize the class attributes with user-supplied values.

It is commonly known as Constructor in object-oriented programming. See the below


example.

class BookStore:
def __init__(self):
print("__init__() constructor gets called...")

B1 = BookStore()
Output
__init__() constructor gets called...
The Instance Attributes
These are object-specific attributes defined as parameters to the __init__ method.
Each object can have different values for themselves.

In the below example, the “attrib1” and “attrib2” are the instance attributes.

class BookStore:
def __init__(self, attrib1, attrib2):
self.attrib1 = attrib1
self.attrib2 = attrib2
The Class Attributes
Unlike the instance attributes which are visible at object-level, the class attributes
remain the same for all objects.

Check out the below example to demonstrate the usage of class-level attributes.

class BookStore:
instances = 0
def __init__(self, attrib1, attrib2):
self.attrib1 = attrib1
self.attrib2 = attrib2
BookStore.instances += 1

b1 = BookStore("", "")
b2 = BookStore("", "")

print("BookStore.instances:", BookStore.instances)
In this example, the “instances” is a class-level attribute. You can access it using the
class name. It holds the total no. of instances created.

We’ve created two instances of the class <Bookstore>. Hence, executing the
example should print “2” as the output.

# output
BookStore.instances: 2
Python Class Demo
Given here is an example where we are building a BookStore class and instantiating
its object with different values.

Create A BookStore Class In Python


class BookStore:
noOfBooks = 0

def __init__(self, title, author):


self.title = title
self.author = author
BookStore.noOfBooks += 1

def bookInfo(self):
print("Book title:", self.title)
print("Book author:", self.author,"\n")

# Create a virtual book store


b1 = BookStore("Great Expectations", "Charles Dickens")
b2 = BookStore("War and Peace", "Leo Tolstoy")
b3 = BookStore("Middlemarch", "George Eliot")

# call member functions for each object


b1.bookInfo()
b2.bookInfo()
b3.bookInfo()

print("BookStore.noOfBooks:", BookStore.noOfBooks)
You can open IDLE or any other Python IDE, save the above code in some file, and
execute the program.
In this example, we have created three objects of the BookStore class, i.e., b1, b2,
and b3. Each of the objects is an instance of the BookStore class.

UML Diagram Of BookStore Class


The UML diagram of the above code is as follows.

Python Class and Objects (UML diagram)


After executing the code in the example, you should see the following result.

# output
Book title: Great Expectations
Book author: Charles Dickens

Book title: War and Peace


Book author: Leo Tolstoy

Book title: Middlemarch


Book author: George Eliot

BookStore.noOfBooks: 3
Python Inheritance and OOPs Fundamentals with
Examples

Python Inheritance – Introduction


Contents [hide]
 1 What does inheritance mean in OOP?
 2 What is the purpose of inheritance?
 3 How to implement inheritance in Python?
 4 Give an example of Python Inheritance
o 4.1 Create a base class Taxi and a subclass Vehicle
o 4.2 Python inheritance’s UML diagram
 5 The super() method
o 5.1 What does the super() do in Python?
o 5.2 How does the super() method work?

☛ Go back to Python Tutorials


What Does Inheritance Mean In OOP?
Inheritance is the core feature of object-oriented programming which extends the
functionality of an existing class by adding new features. You may compare it with
real-life situations when a child inherits the property of his parents in addition to
adding his own. He may even derive the surname (the second name) from his
parents.

What Is The Purpose Of Inheritance?


By using the inheritance feature, we can have a new blueprint with old attributes but
without making any changes to the original one. We refer to the new class as the
derived or child class whereas the old one becomes the base or parent class.
Python Inheritance & OOP Concepts
How To Implement Inheritance In Python?
You can introduce inheritance by using the following syntax.

class ParentClass:
Parent class attributes
Parent class methods
class ChildClass(ParentClass):
Child class attributes
Child class methods
Inheritance automatically brings reusability to your code as the derived class has got
everything from the base class.

Give An Example Of Python Inheritance


To understand the application of inheritance, let’s consider the following example.

Create A Base Class Taxi And A Subclass Vehicle


We have a base class Taxi, and it has a subclass (child) Vehicle.
class Taxi:

def __init__(self, model, capacity, variant):


self.__model = model # __model is private to Taxi
class
self.__capacity = capacity
self.__variant = variant

def getModel(self): # getmodel() is accessible


outside the class
return self.__model

def getCapacity(self): # getCapacity() function is


accessible to class Vehicle
return self.__capacity

def setCapacity(self, capacity): # setCapacity() is


accessible outside the class
self.__capacity = capacity

def getVariant(self): # getVariant() function is


accessible to class Vehicle
return self.__variant

def setVariant(self, variant): # setVariant() is


accessible outside the class
self.__variant = variant

class Vehicle(Taxi):

def __init__(self, model, capacity, variant, color):


# call parent constructor to set model and color
super().__init__(model, capacity, variant)
self.__color = color

def vehicleInfo(self):
return self.getModel() + " " + self.getVariant() + "
in " + self.__color + " with " + self.getCapacity() + " seats"

# In method getInfo we can call getmodel(), getCapacity() as


they are
# accessible in the child class through inheritance

v1 = Vehicle("i20 Active", "4", "SX", "Bronze")


print(v1.vehicleInfo())
print(v1.getModel()) # Vehicle has no method getModel() but it
is accessible via Vehicle class

v2 = Vehicle("Fortuner", "7", "MT2755", "White")


print(v2.vehicleInfo())
print(v2.getModel()) # Vehicle has no method getModel() but it
is accessible via Vehicle class
Please note that we have not specified the getName() method in the Vehicle class,
but we can access it. It is because the Vehicle class inherits it from the Taxi class.

The output of the above example is as follows.

# output
i20 Active SX in Bronze with 4 seats
i20 Active
Fortuner MT2755 in White with 7 seats
Fortuner
Python Inheritance’s UML Diagram
To bring more clarity, you can refer the below Python inheritance’s UML diagram of
the example mentioned above.

The Super() Method


What Does The Super() Do In Python?
The super() method allows us to access the inherited methods that cascade to a
class object.
In the earlier example, we’ve used the super() method in the constructor of the child
class <Vehicle>. It is invoking the function of the base class <Taxi>.
How Does The Super() Method Work?
Just assume, if you have to invoke a method in the base class,
i.e., vehicleInfo() defined in the child class, then you can use the following code.
super().vehicleInfo()
Likewise, you can invoke the base class constructor from the sub (child)
class __init__ using the below code.
super().__init__()

Python File Handling A-Z Guide for Beginners

Python File Handling Tutorial For Beginners


First of all, let’s look at the summary of the Python file handling topics covered in this
tutorial.

Contents [hide]
 1 What does file handling mean?
 2 Open a file in Python
o 2.1 Python open() file method
o 2.2 File open modes in Python
o 2.3 The Python file object attributes
 2.3.1 Example: Python file attribute in action
o 2.4 Python file encoding
 3 Close a file in Python
o 3.1 The close() file method
 3.1.1 Close operation in Python
 3.1.2 Close with try-catch
 3.1.3 Auto close using ‘with’
 4 Perform Write operation
o 4.1 The write() file method
 4.1.1 Example: Read/Write to a File in Python
 5 Perform Read operation
o 5.1 Example: Read from a File in Python
 6 Set File offset in Python
o 6.1 Tell() Method
o 6.2 Seek() Method
o 6.3 Example: Setting offsets in Python
 7 Renaming and deleting files in Python
o 7.1 The rename() file method
o 7.2 The remove() file method
 8 Python File object methods
What Does File Handling Mean?
Here is a basic definition of file handling in Python.

File is a named location on the system storage which records


data for later access. It enables persistent storage in a non-
volatile memory i.e. Hard disk.
In Python, file processing takes place in the following order.

 Open a file that returns a filehandle.


 Use the handle to perform read or write action.
 Close the filehandle.
Before you do a read or write operation to a file in Python, you need to open it first.
And as the read/write transaction completes, you should close it to free the
resources tied with the file.

In the next sections, we’ll touch upon all the Python file handling topics one by one.
Since it’s an example-driven Python tutorial, so better you open a Python console to
test-run the code.

Open A File In Python


To read or write to a file, you need to open it first. To open a file in Python, use its
built open() function. This function returns a file object, i.e., a handle. You can use it
to read or modify the file.
Python Open() File Method
file object = open(file_name [, access_mode][, buffering])
Below are the parameter details.

<access_mode>- It’s an integer representing the file opening mode, e.g., read, write,
append, etc. It’s an optional parameter. By default, it is set to read-only <r>. In this
mode, we get data in text form after reading from the file.
On the other hand, the binary mode returns bytes. It’s preferable for accessing the
non-text files like an image or the Exe files. See the table in the next section. It lists
down the available access modes.

<buffering>- The default value is 0, which means buffering won’t happen. If the value
is 1, then line buffering will take place while accessing the file. If it’s higher than 1,
then the buffering action will run as per the buffer size. In the case of a negative
value, the default behavior is considered.
<file_name>- It’s a string representing the name of the file you want to access.
RECOMMENDED – Copy a File in Python
File Open Modes In Python
Modes Description

It opens a file in
read-only mode
<r>
while the file offset
stays at the root.

It opens a file in
(binary + read-only)
<rb> modes. And the
offset remains at the
root level.

It opens the file in


both (read + write)
<r+> modes while the file
offset is again at the
root level.

It opens the file in


(read + write +
<rb+> binary) modes. The
file offset is again at
the root level.

<w> It allows write-level


access to a file. If
the file already
exists, then it’ll get
overwritten. It’ll
create a new file if
the same doesn’t
exist.

Use it to open a file


for writing in binary
<wb> format. Same
behavior as
for write-only mode.

It opens a file in
both (read + write)
<w+> modes. Same
behavior as
for write-only mode.

It opens a file in
(read + write +
<wb+> binary) modes.
Same behavior as
for write-only mode.

It opens the file in


append mode. The
offset goes to the
<a>
end of the file. If the
file doesn’t exist,
then it gets created.

It opens a file in
(append + binary)
<ab> modes. Same
behavior as for
append mode.

It opens a file in
(append + read)
<a+> modes. Same
behavior as for
append mode.

It opens a file in
(append + read +
<ab+> binary) modes.
Same behavior as
for append mode.
The Python File Object Attributes
When you call the Python open() function, it returns an object, which is the
filehandle. Also, you should know that Python files have several linked attributes.
And we can make use of the filehandle to list the attributes of a file.

For more information on file attributes, please run down through the below table.

Attribute Description

For a
closed file,
it returns
<file.closed> true
whereas
false
otherwise.

It returns
the access
<file.mode> mode used
to open a
file.

Returns the
<file.name> name of a
file

It returns a
boolean to
suggest if a
space char
will get
added
<file.softspace> before
printing
another
value in the
output of
a <print>
command.

Example: Python File Attribute In Action


#Open a file in write and binary mode.
fob = open("app.log", "wb")

#Display file name.


print "File name: ", fob.name
#Display state of the file.
print "File state: ", fob.closed
#Print the opening mode.
print "Opening mode: ", fob.mode
#Output the softspace value.
print "Softspace flag: ", fob.softspace
Python 2.7.10
[GCC 4.8.2] on Linux

File name: app.log


File state: False
Opening mode: wb
Softspace flag: 0
Python File Encoding
In Python 3.x, there is a clear difference between strings (text) and a byte (8-bits). It
states that the char ‘a’ doesn’t represent the ASCII value 97 until you specify it like
that. So, while you want to use a file in text mode, then better you mention the
correct encoding type.

Also, Python stores a file in the form of bytes on the disk, so you need to decode
them in strings before reading. And, similarly, encode them while writing texts to the
file.

For a note, Python enables platform-dependent encoding by default. Hence, if you


don’t change it, then it’s set to <cp1252> for Windows and <utf-8> for Linux.

Thus, the documentation says to quote the desired encoding while opening a file in
Python. See the Python code snippet.

f = open('app.log', mode = 'r', encoding = 'utf-8')


For note, you should import the <io> module in Python 2.x to enable the encoding
feature. Python 3.x does it implicitly.

Back to top
Close A File In Python
It’s always the best practice to close a file when your work gets finished. However,
Python runs a garbage collector to clean up the unused objects. But you must do it
on your own instead leave it for the GC.

The Close() File Method


Python provides the <close()> method to close a file.

While closing a file, the system frees up all resources allocated to it. And it’s rather
easy to achieve.
Please see the below code snippets.

Close Operation In Python


The most basic way is to call the Python close() method.

f = open("app.log",encoding = 'utf-8')
# do file operations.
f.close()
Close With Try-Catch
Say, if an exception occurs while performing some operations on the file. In such a
case, the code exits without closing the file. So it’s better to put the code inside a
<try-finally> block.

try:
f = open('app.log', encoding = 'utf-8')
# do file operations.
finally:
f.close()
So, even if there comes an exception, the above code will make sure your file gets
appropriately closed.

Auto Close Using ‘With’


Another way to close a file is by using the WITH clause. It ensures that the file gets
closed when the block inside the WITH clause executes. The beauty of this method
is that it doesn’t require to call the close() method explicitly.
with open('app.log', encoding = 'utf-8') as f:
#do any file operation.
Back to top
Perform Write Operation
While you get ready for writing data to a file, first of all, open it using a mode
(read/write/append). View the list of all available file modes here.
You can even do the same using the append mode. Also, if you’ve used
the <w> mode, then it’ll erase the existing data from the file. So you must note this
fact while you choose it.
The Write() File Method
Python provides the write() method to write a string or sequence of bytes to a file.
This function returns a number, which is the size of data written in a single Write call.
Example: Read/Write To A File In Python
with open('app.log', 'w', encoding = 'utf-8') as f:
#first line
f.write('my first file\n')
#second line
f.write('This file\n')
#third line
f.write('contains three lines\n')
with open('app.log', 'r', encoding = 'utf-8') as f:
content = f.readlines()

for line in content:


print(line)
Python 3.5.1
[GCC 4.8.2] on Linux

my first file

This file

contains three lines


Back to top
Perform Read Operation
To read data from a file, first of all, you need to open it in reading mode. Then, you
can call any of the methods that Python provides for reading from a file.

Usually, we use Python <read(size)> function to read the content of a file up to the


size. If you don’t pass the size, then it’ll read the whole file.
Example: Read From A File In Python
with open('app.log', 'w', encoding = 'utf-8') as f:
#first line
f.write('my first file\n')
#second line
f.write('This file\n')
#third line
f.write('contains three lines\n')

f = open('app.log', 'r', encoding = 'utf-8')


print(f.read(10)) # read the first 10 data
#'my first f'

print(f.read(4)) # read the next 4 data


#'ile\n'

print(f.read()) # read in the rest till end of file


#'This file\ncontains three lines\n'

print(f.read()) # further reading returns empty sting


#''
CHECK OUT – Read file line by line in Python
Back to top
Set File Offset In Python
Tell() Method
This method gives you the current offset of the file pointer in a file.

Syntax:
file.tell()
The tell() method doesn’t require any argument.

Seek() Method
This method can help you change the position of a file pointer in a file.

Syntax:
file.seek(offset[, from])
The <offset> argument represents the size of the displacement.
The <from> argument indicates the start point.

If from is 0, then the shift will start from the root level.
If from is 1, then the reference position will become the
current position.
It from is 2, then the end of the file would serve as
the reference position.
Example: Setting Offsets In Python
with open('app.log', 'w', encoding = 'utf-8') as f:
#first line
f.write('It is my first file\n')
#second line
f.write('This file\n')
#third line
f.write('contains three lines\n')

#Open a file
f = open('app.log', 'r+')
data = f.read(19);
print('Read String is : ', data)

#Check current position


position = f.tell();
print('Current file position : ', position)

#Reposition pointer at the beginning once again


position = f.seek(0, 0);
data = f.read(19);
print('Again read String is : ', data)
#Close the opened file
f.close()
Python 3.5.1
[GCC 4.8.2] on Linux

Read String is : It is my first file


Current file position : 19
Again read String is : It is my first file
Back to top
Renaming And Deleting Files In Python
While you were using the <read/write> functions, you may also need to
<rename/delete> a file in Python. So, there comes a <os> module in Python, which
brings the support of file <rename/delete> operations.

So, to continue, first of all, you should import the <os> module in your Python script.

The Rename() File Method


os.rename(cur_file, new_file)
The <rename()> method takes two arguments, the current filename and the new
filename.

Following is the example to rename an existing file <app.log> to <app1.log>.

Example:
import os

#Rename a file from <app.log> to <app1.log>


os.rename( "app.log", "app1.log" )
The Remove() File Method
os.remove(file_name)
The <remove()> method deletes a file which it receives in the argument.

Following is the example to delete an existing file, the <app1.log>.

Example:
import os

#Delete a file <app1.log>


os.remove( "app1.log" )
Back to top
Python File Object Methods
So far, we’ve only shared with you a few of the functions that you can use for file
handling in Python. But there is more to the story of Python file handling.
Python’s open() method returns an object which we call as the filehandle. Python
adds a no. of functions that we can call using this object.

Function Description

Close the
file. You
need to
<file.close()>
reopen it for
further
access.

Flush the
internal
buffer. It’s
same as
<file.flush()>
the
<stdio>’s
<fflush()>
function.

Returns an
<file.fileno()> integer file
descriptor.

It returns
true if file
<file.isatty()> has a <tty>
attached to
it.

Returns the
next line
<file.next()>
from the
last offset.

Reads the
given no. of
bytes. It
<file.read(size)>
may read
less if EOF
is hit.

<file.readline(size)> It’ll read an


entire line
(trailing with
a new line
char) from
the file.

It calls the
<readline()
> to read
until EOF. It
returns a
list of lines
read from
the file. If
<file.readlines(size_hint)>
you pass
<size_hint>
, then it
reads lines
equalling
the
<size_hint>
bytes.

Sets the
file’s
<file.seek(offset[, from])>
current
position.

Returns the
file’s
<file.tell()>
current
position.

Truncates
the file’s
size. If the
optional
size
<file.truncate(size)> argument is
present, the
file is
truncated to
(at most)
that size.

It writes a
string to the
file. And it
<file.write(string)>
doesn’t
return any
value.
Writes a
sequence
of strings to
the file. The
sequence is
possibly an
<file.writelines(sequence)> iterable
object
producing
strings,
typically a
list of
strings.

How to Copy a File in Python – 9 Different Ways


to do It!

How To Do Python Copy File – 9 Ways To Learn.


Here are the nine methods to demonstrate “How to copy a file in Python?”.
1. shutil copyfile() method
2. shutil copy() method
3. shutil copyfileobj() method
4. shutil copy2() method
5. os popen method
6. os system() method
7. threading Thread() method
8. subprocess call() method
9. subprocess check_output() method
Python Copy File – How To for Beginners

1. Shutil Copyfile() Method


This method copies the content of the source to the destination only if the target is
writable. If you don’t have the right permissions, then it will raise an IOError.
It works by opening the input file for reading while ignoring its file type.

Next, it doesn’t treat special files any differently and won’t create their clones.

The copyfile() method makes use of lower-level function copyfileobj() underneath. It


takes file names as arguments, opens them and passes file handles to copyfileobj().
There is one optional third argument in this method which you can use to specify the
buffer length. It’ll then open the file for reading in chunks of the specified buffer size.
However, the default behavior is to read the entire file in one go.
copyfile(source_file, destination_file)
Following are the points to know about the copyfile() method.
 It copies the contents of the source to a file named as the destination.
 If the destination isn’t writable, then the copy operation would result in
an IOError exception.
 It will return the SameFileError if both the source and destination files are the
same.
 However, if the destination pre-exists with a different name, then the copy will
overwrite its content.
 Error 13 will occur if the destination is a directory which means this method
won’t copy to a folder.
 It doesn’t support copying files such as character or block devices and the
pipes.
# Python Copy File - Sample Code

from shutil import copyfile


from sys import exit

source = input("Enter source file with full path: ")


target = input("Enter target file with full path: ")

# adding exception handling


try:
copyfile(source, target)
except IOError as e:
print("Unable to copy file. %s" % e)
exit(1)
except:
print("Unexpected error:", sys.exc_info())
exit(1)

print("\nFile copy done!\n")

while True:
print("Do you like to print the file ? (y/n): ")
check = input()
if check == 'n':
break
elif check == 'y':
file = open(target, "r")
print("\nHere follows the file content:\n")
print(file.read())
file.close()
print()
break
else:
continue
Back to top
2. Shutil Copy() Method
copyfile(source_file, [destination_file or dest_dir])
The copy() method functions like the “cp” command in Unix. It means if the target is
a folder, then it’ll create a new file inside it with the same name (basename) as the
source file. Also, this method will sync the permissions of the target file with the
source after copying its content. It too throws the SameFileError if you are copying
the same file.
import os
import shutil

source = 'current/test/test.py'
target = '/prod/new'

assert not os.path.isabs(source)


target = os.path.join(target, os.path.dirname(source))

# create the folders if not already exists


os.makedirs(target)

# adding exception handling


try:
shutil.copy(source, target)
except IOError as e:
print("Unable to copy file. %s" % e)
except:
print("Unexpected error:", sys.exc_info())
Copy() Vs Copyfile() –
1. The copy() also sets the permission bits while copying the contents whereas
the copyfile() only copies the data.
2. The copy() will copy a file if the destination is a directory whereas the
copyfile() will fail with error 13.
3. Interestingly, the copyfile() method utilizes the copyfileobj() method in its
implementation whereas the copy() method makes use of the copyfile() and
copymode() functions in turn.
4. Point-3 makes it apparent that copyfile() would be a bit faster than the copy()
as the latter has an additional task (preserving the permissions) at hand.
Back to top
3. Shutil Copyfileobj() Method
This method copies the file to a target path or file object. If the target is a file object,
then you need to close it explicitly after the calling the copyfileobj(). It assumes an
optional argument (the buffer size) which you can use to supply the buffer length. It
is the number of bytes kept in memory during the copy process. The default size that
system use is 16KB.
from shutil import copyfileobj
status = False
if isinstance(target, string_types):
target = open(target, 'wb')
status = True
try:
copyfileobj(self.stream, target, buffer_size)
finally:
if status:
target.close()
Back to top
4. Shutil Copy2() Method
However, the copy2() method functions like the copy(). But it also gets the access
and modification times added in the meta-data while copying the data. Copying the
same file would result in SameFileError.
from shutil import *
import os
import time
from os.path import basename

def displayFileStats(filename):
file_stats = os.stat(basename(filename))
print('\tMode :', file_stats.st_mode)
print('\tCreated :', time.ctime(file_stats.st_ctime))
print('\tAccessed:', time.ctime(file_stats.st_atime))
print('\tModified:', time.ctime(file_stats.st_mtime))

os.mkdir('test')

print('SOURCE:')
displayFileStats(__file__)

copy2(__file__, 'testfile')

print('TARGET:')
displayFileStats(os.path.realpath(os.getcwd() +
'./test/testfile'))
Copy() Vs Copy2()
1. The copy() only sets permission bits whereas copy2() also updates the file
metadata with timestamps.
2. The copy() method calls copyfile() and copymode() internally whereas copy2()
replaces the call to copymode() with copystat().
Copymode() Vs Copystat()
shutil.copymode()
copymode(source, target, *, follow_symlinks=True)
 It intends to copy the permission bits from source to the target files.
 The file contents, owner, and group remain unchanged. The arguments
passed are strings.
 If the follow_symlinks arg is false and the first two args are symlinks,
then copymode() will try to update the target link, not the actual file it is pointing.
shutil.copystat()
copystat(source, target, *, follow_symlinks=True)
 It attempts to preserve the permission bits, last used time/update time, and
flags of the target file.
 The copystat() includes the extended attributes while copying on Linux. The
file contents/owner/group remain unchanged.
 If the follow_symlinks arg is false and the first two args are symlinks, then
copystat() will update them, not the files they point.
Back to top
5. Os Popen() Method
This method creates a pipe to or from the command. It returns an open file object
which connects to a pipe. You can use it for reading or writing according to the file
mode, i.e., ‘r’ (default) or ‘w.’

os.popen(command[, mode[, bufsize]])


 mode – It can be ‘r’ (default) or ‘w’.
 bufsize – If its value is 0, then no buffering will occur. If the bufsize is 1, then
line buffering will take place while accessing the file. If you provide a value
greater than 1, then buffering will occur with the specified buffer size. However,
for a negative value, the system will assume the default buffer size.
For Windows OS.
import os

os.popen('copy 1.txt.py 2.txt.py')


For Linux OS.
import os

os.popen('cp 1.txt.py 2.txt.py')


Back to top
6. Os System() Method
The system() method allows you to instantly execute any OS command or a script in
the subshell.
You need to pass the command or the script as an argument to the system() call.
Internally, this method calls the standard C library function.
Its return value is the exit status of the command.

For Windows OS.


import os

os.system('copy 1.txt.py 2.txt.py')


For Linux OS.
import os

os.system('cp 1.txt.py 2.txt.py')


Back to top
7. Python File Copy Using Threading Library In Async Manner
If you want to copy a file asynchronously, then use the below method. In this, we’ve
used Python’s threading module to run the copy operation in the background.

While using this method, please make sure to employ locking to avoid deadlocks.
You may face it if your application is using multiple threads reading/writing a file.

import shutil
from threading import Thread

src="1.txt.py"
dst="3.txt.py"

Thread(target=shutil.copy, args=[src, dst]).start()


Back to top
8. Use Subprocess’s Call() Method To Copy A File In Python
The subprocess module gives a simple interface to work with child processes. It
enables us to launch subprocesses, attach to their input/output/error pipes, and
retrieve the return values.
The subprocess module aims to replace the legacy modules and functions like
– os.system, os.spawn*, os.popen*, popen2.*.
It exposes a call() method to invoke system commands to execute user tasks.
import subprocess

src="1.txt.py"
dst="2.txt.py"
cmd='copy "%s" "%s"' % (src, dst)

status = subprocess.call(cmd, shell=True)

if status != 0:
if status < 0:
print("Killed by signal", status)
else:
print("Command failed with return code - ", status)
else:
print('Execution of %s passed!\n' % cmd)
Back to top
9. Use Subprocess’s Check_output() Method To Copy A File In
Python
With subprocess’s check_output() method, you can run an external command or a
program and capture its output. It also supports pipes.
import os, subprocess

src=os.path.realpath(os.getcwd() + "./1.txt.py")
dst=os.path.realpath(os.getcwd() + "./2.txt.py")
cmd='copy "%s" "%s"' % (src, dst)

status = subprocess.check_output(['copy', src, dst],


shell=True)

print("status: ", status.decode('utf-8'))

Python Exception Handling: A Quick Guide for


Learning

Table of Content
 Error vs. Exception in Python
 What is Error?
 What is an Exception in Python?
 Handle Exceptions with Try-Except
 What is Try-Except?
 Exception Syntax
 Examples
 Handle All Types of Exception with Except
 Example
 Handle Multiple Exceptions with Except
 Example
 Handle Exceptions with Try-Finally
 What is Try-Finally?
 Examples
 Raise Exception with Arguments
 What is Raise in Python?
 Raise Syntax
 Example
 Create Custom Exceptions in Python
 What is a Custom exception in Python?
 Create Exception Class in Python
 Examples
 Python Built-in Exceptions
First of all, we have to understand the difference between an error and the
exception. Consequently, we’ll teach you the essentials of Python exception
handling.
Python Exception Handling: Error Vs. Exception
What Is Error?
The error is something that goes wrong in the program, e.g., like a syntactical error.

It occurs at compile time. Let’s see an example.

if a<5
File "<interactive input>", line 1
if a < 5
^
SyntaxError: invalid syntax
What Is Exception?
The errors also occur at runtime, and we know them as exceptions. An exception is
an event which occurs during the execution of a program and disrupts the normal
flow of the program’s instructions.

In general, when a Python script encounters an error situation that it can’t cope with,
it raises an exception.

When a Python script raises an exception, it creates an exception object.

Usually, the script handles the exception immediately. If it doesn’t do so, then the
program will terminate and print a traceback to the error along with its whereabouts.

>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in run code
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
How To Handle Exceptions With Try-Except?
What Is Try-Except Statement?
We use the try-except statement to enable exception handling in Python programs.

Inside the try block, you write the code which can raise an exception.

And the code that handles or catches the exception, we place in the except clause.

Python Exception Handling Syntax


Following is the syntax of a Python try-except-else block.
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
➡ Have a look – 30 Python Interview Questions for Beginners.
Here is a checklist for using the Python try statement effectively.

 A single try statement can have multiple except statements depending on the
requirement. In this case, a try block contains statements that can throw different
types of exceptions.
 We can also add a generic except clause which can handle all possible types
of exceptions.
 We can even include an else clause after the except clause. The instructions
in the else block will execute if the code in the try block doesn’t raise an
exception.
Python Exception Handling Examples
Let’s take a sample code to understand the use of Python try-except.
try:
fob = open("test", "w")
fob.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find the file or read data"
else:
print "Write operation is performed successfully on the
file"
fob.close()
The above code produces the following output.

>>Write operation is performed successfully on the file.


Let’s take another example in which we are trying to open a file in the READ mode.
We’ll perform a WRITE operation on it. Upon execution, it’ll throw an exception.

try:
fob = open("test", "r")
fob.write("It's my test file to verify exception handling
in Python!!")
except IOError:
print "Error: can\'t find the file or read data"
else:
print "Write operation is performed successfully on the
file"
The above code produces the following output.

>>Error: can't find file or read data


Handling All Types Of Exceptions With Except
If we use a bare “except” clause, then it would catch all types of exceptions.
However, neither it’s a good programming practice nor does anyone recommend it.

It is because that such a Python try-except block can handle all types of exceptions.
But it’ll not help the programmer to find what exception caused the issue.

You can go through the below code to see how to catch all exceptions.

Example
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
Handling Multiple Exceptions With Except
We can define multiple exceptions with the same except clause. It means that if the
Python interpreter finds a matching exception, then it’ll execute the code written
under the except clause.

In short, when we define except clause in this way, we expect the same piece of
code to throw different exceptions. Also, we want to take the same action in each
case.

Please refer to the below example.

Example
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block
How To Handle Exceptions With Try-Finally?
What Is Try-Finally Statement?
We can also enable Python exception handling with the help of try-finally statement.

With try block, we also have the option to define the “finally” block. This clause
allows defining statements that we want to execute, no matters whether the try block
has raised an exception or not.
This feature usually comes in the picture while releasing external resources.

Here is the coding snippet for help.

try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Examples
One critical point is that we can either define an “except” or a “finally” clause with
every try block. You can’t club these together. Also, you shouldn’t use the “else”
clause along with a “finally” clause.
Let’s take an example to get more clarity.

try:
fob = open('test', 'w')
fob.write("It's my test file to verify try-finally in
exception handling!!"
)
print 'try block executed'
finally:
fob.close()
print 'finally block executed'
If the exception doesn’t occur, then you’ll see the following output.
>>try block executed
>>finally block executed
Suppose we open the file in the READ mode and then try to perform a write
operation on it. In such a situation, below code will help to handle the exception.
try:
fob = open('test', 'r')
try:
fob.write("It's my test file to verify try-finally in
exception handling!!"
)
print 'try block executed'
finally:
fob.close()
print 'finally block executed to close the file'
except IOError:
print "Error: can\'t find file or read data"
In this case, the interpreter will raise an exception, and the following output will get
displayed.
>>finally block executed to close the file
>>Error: can\'t find file or read data
When some code causes an exception in a try block, the execution immediately
passes to the “finally” block. After all the statements in the “finally” block gets
executed, the exception resumes to the “except” block for execution. But there must
present a next higher layer of the “try-except” statement.
Raise Exception With Arguments
What Is Raise?
We can forcefully raise an exception using the raise keyword.

We can also optionally pass values to the exception and specify why it has occurred.

Raise Syntax
Here is the syntax for calling the “raise” method.
raise [Exception [, args [, traceback]]]
Where,

 Under the “Exception” – specify its name.


 The “args” is optional and represents the value of the exception argument.
 The final argument, “traceback,” is also optional and if present, is the
traceback object used for the exception.
Let’s take an example to clarify this.

Raise Example
>>> raise MemoryError
Traceback (most recent call last):
...
MemoryError

>>> raise MemoryError("This is an argument")


Traceback (most recent call last):
...
MemoryError: This is an argument

>>> try:
a = int(input("Enter a positive integer value: "))
if a <= 0:
raise ValueError("This is not a positive
number!!")
except ValueError as ve:
print(ve)

Following Output is displayed if we enter a negative number:

Enter a positive integer: –5

This is not a positive number!!


Create Custom Exceptions In Python
What Is A Custom Exception?
A custom exception is one which the programmer creates himself.

He does it by adding a new class. The trick here is to derive the custom exception
class from the base exception class.

Most of the built-in exceptions do also have a corresponding class.

Create Exception Class In Python


>>> class UserDefinedError(Exception):
... pass

>>> raise UserDefinedError


Traceback (most recent call last):
...
__main__.UserDefinedError
>>> raise UserDefinedError("An error occurred")
Traceback (most recent call last):
...
__main__.UserDefinedError: An error occurred
In the above code snippet, you can see that we have created a user-defined
exception class, the “UserDefinedError.” It is using the base Exception class as the
parent. Hence, the new user-defined exception class will raise exceptions as any
other exception class does, i.e., by calling the “raise” statement with an optional error
message.
Let’s take an example.

Examples
In this example, we will show how to raise an user-defined exception and catch
errors in a program.

This program prompts the user to enter an alphabet again and again until he inputs
the stored alphabet only.

For help, the program provides a hint to the user so that he can figure out the correct
alphabet. Also, he can check whether his guess is higher or less than the stored
alphabet.

#define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
pass

class InputTooSmallError(Error):
"""Raised when the entered alpahbet is smaller than the
actual one"""
pass

class InputTooLargeError(Error):
"""Raised when the entered alpahbet is larger than the
actual one"""
pass

#our main program


#user guesses an alphabet until he/she gets it right

#you need to guess this alphabet


alphabet = 'm'

while True:
try:
apb = raw_input("Enter an alphabet: ")
if apb < alphabet:
raise InputTooSmallError
elif apb > alphabet:
raise InputTooLargeError
break
except InputTooSmallError:
print("The entered alphabet is too small, try again!")
print('')
except InputTooLargeError:
print("The entered alphabet is too large, try again!")
print('')

print("Congratulations! You guessed it correctly.")


Let’s test this program by supplying different inputs.

Enter an alphabet: s
This value is too large, try again!

Enter an alphabet: a
This value is too small, try again!

Enter an alphabet: l
This value is too small, try again!

Enter an alphabet: p
This value is too large, try again!

Enter a number: m
Congratulations! You guessed it correctly.
Thus you can see that we have defined a base class called Error here in this
program. It raises two exceptions (“InputTooSmallError” and “InputTooLargeError“)
derived from the base class. It’s the standard way to define user-defined exceptions
in Python programming.
Python Built-In Exceptions
Exception Cause of Error

AirthmeticError For errors in numeric calculation.

AssertionError If the assert statement fails.

AttributeError When an attribute assignment or the reference fails.

EOFError If there is no input or the file pointer is at EOF.


Exception It is the base class for all exceptions.

EnvironmentError For errors that occur outside the Python environment.

FloatingPointError It occurs when the floating point operation fails.

GeneratorExit If a generator’s <close()> method gets called.

ImportError It occurs when the imported module is not available.

IOError If an input/output operation fails.

IndexError When the index of a sequence is out of range.

KeyError If the specified key is not available in the dictionary.

KeyboardInterrupt When the user hits an interrupt key (Ctrl+c or delete).

MemoryError If an operation runs out of memory.

NameError When a variable is not available in local or global scope.

NotImplementedError If an abstract method isn’t available.

OSError When a system operation fails.

OverflowError It occurs if the result of an arithmetic operation exceeds the range.

ReferenceError When a weak reference proxy accesses a garbage collected referenc

RuntimeError If the generated error doesn’t fall under any category.

It is a base class for all built-in exceptions except <StopIteration> and


StandardError <SystemExit>.

StopIteration The <next()> function has no further item to be returned.

SyntaxError For errors in Python syntax.

IndentationError It occurs if the indentation is not proper.

TabError For inconsistent tabs and spaces.

SystemError When interpreter detects an internal error.

SystemExit The <sys.exit()> function raises it.

TypeError When a function is using an object of the incorrect type.

UnboundLocalError If the code using an unassigned reference gets executed.

UnicodeError For a Unicode encoding or decoding error.

ValueError When a function receives invalid values.


ZeroDivisionError If the second operand of division or modulo operation is zero.

How to Best Use Try Except in Python –


Especially for Beginners
 How to handle an arbitrary exception
 Catch multiple exceptions in one except block
 Handling multiple exceptions with one except block
 Re-raising exceptions in Python
 When to use the else clause
 Make use of [finally clause]
 Use the As keyword to catch specific exception types
 Best practice for manually raising exceptions
 How to skip through errors and continue execution
 Most common exception errors in Python
 Examples of most common exceptions in Python
1. How To Handle An Arbitrary Exception
Sometimes, you may need a way to allow any arbitrary exception and also want to
be able to display the error or exception message.

It is easily achievable using the Python exceptions. Check the below code. While
testing, you can place the code inside the try block in the below example.

try:
#your code
except Exception as ex:
print(ex)
Back to top
2. Catch Multiple Exceptions In One Except Block
You can catch multiple exceptions in a single except block. See the below example.

except (Exception1, Exception2) as e:


pass
Please note that you can separate the exceptions from the variable with a comma
which is applicable in Python 2.6/2.7. But you can’t do it in Python 3. So, you should
prefer to use the [as] keyword.

Back to top
3. Handling Multiple Exceptions With One Except Block
There are many ways to handle multiple exceptions. The first of them requires
placing all the exceptions which are likely to occur in the form of a tuple. Please see
from below.
try:
file = open('input-file', 'open mode')
except (IOError, EOFError) as e:
print("Testing multiple exceptions. {}".format(e.args[-
1]))
The next method is to handle each exception in a dedicated except block. You can
add as many except blocks as needed. See the below example.

try:
file = open('input-file', 'open mode')
except EOFError as ex:
print("Caught the EOF error.")
raise ex
except IOError as e:
print("Caught the I/O error.")
raise ex
The last but not the least is to use the except without mentioning any exception
attribute.

try:
file = open('input-file', 'open mode')
except:
# In case of any unhandled error, throw it away
raise
This method can be useful if you don’t have any clue about the exception possibly
thrown by your program.

Back to top
4. Re-Raising Exceptions In Python
Exceptions once raised keep moving up to the calling methods until handled. Though
you can add an except clause which could just have a [raise] call without any
argument. It’ll result in reraising the exception.

See the below example code.

try:
# Intentionally raise an exception.
raise Exception('I learn Python!')
except:
print("Entered in except.")
# Re-raise the exception.
raise
Output:
Entered in except.
Traceback (most recent call last):
File "python", line 3, in <module>
Exception: I learn Python!
Back to top
5. When To Use The Else Clause
Use an else clause right after the try-except block. The else clause will get hit only if
no exception is thrown. The else statement should always precede the except
blocks.

In else blocks, you can add code which you wish to run when no errors occurred.

See the below example. In this sample, you can see a while loop running infinitely.
The code is asking for user input and then parsing it using the built-in [int()] function.
If the user enters a zero value, then the except block will get hit. Otherwise, the code
will flow through the else block.

while True:
# Enter integer value from the console.
x = int(input())

# Divide 1 by x to test error cases


try:
result = 1 / x
except:
print("Error case")
exit(0)
else:
print("Pass case")
exit(1)
Back to top
6. Make Use Of [Finally Clause]
If you have a code which you want to run in all situations, then write it inside the
[finally block]. Python will always run the instructions coded in the [finally block]. It is
the most common way of doing clean up tasks. You can also make sure the clean up
gets through.

An error is caught by the try clause. After the code in the except block gets executed,
the instructions in the [finally clause] would run.

Please note that a [finally block] will ALWAYS run, even if you’ve returned ahead of
it.
See the below example.

try:
# Intentionally raise an error.
x = 1 / 0
except:
# Except clause:
print("Error occurred")
finally:
# Finally clause:
print("The [finally clause] is hit")
Output:
Error occurred
The [finally clause] is hit
Back to top
7. Use The As Keyword To Catch Specific Exception Types
With the help of as <identifier>, you can create a new object. And you can also the
exception object. Here, the below example, we are creating the IOError object and
then using it within the clause.

try:
# Intentionally raise an error.
f = open("no-file")
except IOError as err:
# Creating IOError instance for book keeping.
print("Error:", err)
print("Code:", err.errno)
Output:
('Error:', IOError(2, 'No such file or directory'))
('Code:', 2)
Back to top
8. Best Practice For Manually Raising Exceptions
Avoid raising generic exceptions because if you do so, then all other more specific
exceptions have to be caught also. Hence, the best practice is to raise the most
specific exception close to your problem.

Bad Example.
def bad_exception():
try:
raise ValueError('Intentional - do not want this to
get caught')
raise Exception('Exception to be handled')
except Exception as error:
print('Inside the except block: ' + repr(error))

bad_exception()
Output:
Inside the except block: ValueError('Intentional - do not want
this to get caught',)
Best Practice:
Here, we are raising a specific type of exception, not a generic one. And we are also
using the args option to print the incorrect arguments if there is any. Let’s see the
below example.

try:
raise ValueError('Testing exceptions: The input is in
incorrect order', 'one', 'two', 'four')
except ValueError as err:
print(err.args)
Output:
('Testing exceptions: The input is in incorrect order', 'one',
'two', 'four')
Back to top
9. How To Skip Through Errors And Continue Execution
Ideally, you shouldn’t be doing this. But if you still want to do, then follow the below
code to check out the right approach.

try:
assert False
except AssertionError:
pass
print('Welcome to Prometheus!!!')
Output:
Welcome to Prometheus!!!
Back to top
Now, have a look at some of the most common Python exceptions and their
examples.

Most Common Exception Errors


 IOError – It occurs on errors like a file fails to open.
 ImportError – If a python module can’t be loaded or located.
 ValueError – It occurs if a function gets an argument of right type but an
inappropriate value.
 KeyboardInterrupt – It gets hit when the user enters the interrupt key (i.e.
Control-C or Del key)
 EOFError – It gets raised if the input functions (input()/raw_input()) hit an
end-of-file condition (EOF) but without reading any data.

Examples Of Most Common Exceptions
except IOError:
print('Error occurred while opening the file.')

except ValueError:
print('Non-numeric input detected.')

except ImportError:
print('Unable to locate the module.')

except EOFError:
print('Identified EOF error.')

except KeyboardInterrupt:
print('Wrong keyboard input.')

except:
print('An error occurred.')

You might also like