Python Keywords, Identifiers and Variables - Fundamentals
Python Keywords, Identifiers and Variables - Fundamentals
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
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.
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
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.
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.
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.
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.
>>> 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.
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.
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.
In the examples of the previous sections, you might have seen us writing simple
expression statements which didn’t have the indentation.
Example
def demo_routine(num):
print('I am a demo function')
if num % 2 == 0:
return True
else:
return False
>>> 6*5-10
File "<stdin>", line 1
6*5-10
^
IndentationError: unexpected indent
showCalender(months)
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.
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.
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.")
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.
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.
>>> 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.
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.
>>> 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.
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.
<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.
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.
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.
Since the set derives its implementation from the “Set” in mathematics, so it can’t
have multiple occurrences of the same element.
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 {}.
# 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.
# A standard set
sample_set = {"red", "green"}
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.
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.
>>> 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
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.
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.
If you want to update the String, then re-assign a new String value to the same
variable.
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.
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:
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.
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
#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.
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.
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.
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.
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.
Where: i=search starts from this index, j=search ends at this index.
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
>>> 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.
>>> 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).
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.
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
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.
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)
# output
{3, 11, 7, 15}
{(1, 2), 1.1, 11, '11'}
Follow one more example of Python Set to gain more clarity.
# 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.
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)
# 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.
# 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.
# 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.
# 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.
# 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.
symdiffAB = setA^setB
print("symdiffAB:", symdiffAB, "size:", len(symdiffAB))
symdiffBA = setB^setA
print("symdiffBA:", symdiffBA, "size:", len(symdiffBA))
The output is as follows.
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.
# 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"])
# 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.
# A standard set
std_set = set(["apple", "mango","orange"])
# A frozen set
frozen_set = frozenset(["apple", "mango","orange"])
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)
# 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.
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))
# 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.
Let’s see how can the “:” operator can come into play with the below example.
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.
# 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.
The Python’s del keyword can make you delete a tuple. Check out the below
example.
py_tuple = ('p', 'y', 't', 'h', 'o', 'n')
# 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.
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.
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.
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.
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.
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.
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.
Both methods will work the same, but the former will return a KeyError while the
latter returns None if the element is not available.
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.
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.
Let’s resume the previous example. It has a dict object which contains a key as
‘Student Name’. We’ll update its value.
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.
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.”
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.”
Let’s understand the concept with a simple example. It prints all the keys of a
dictionary in a loop.
Keys are:
Student Name
Roll No.
Subject
Follow one more example below which prints keys along with values.
{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.
Such Python dictionaries which have element index can be useful in many situations.
True
False
True
A Quick Guide to Format String in Python
* 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:
* 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:
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.
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('{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.
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.
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.
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)
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)
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
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.
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")
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
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.
>>> 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.
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.
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.
# Expression is incorrect
# Non-associative operators
# Error -> SyntaxError: invalid syntax
x = y += 12
Understand Python Namespace and Scope with
Examples
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.
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.
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.
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()
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.
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.
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 math
print("namespace_2: ", dir())
print(math.sqrt(144.2))
The output of the above example goes like this.
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.
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.
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.
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
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.
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.
num = r1 + 1
count = 0
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.
Syntax
if Logical_Expression :
Indented Code Block
Flowchart
If the result is True, then the code block following the expression would run.
Otherwise, the code indented under the else clause would execute.
Syntax
if Logical_Expression :
Indented Code Block 1
else :
Indented Code Block 2
Flowchart
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 –
>>> 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.
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 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.
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.
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)
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.
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”.
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.
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.
class PythonSwitch:
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))
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.
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.
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.
arg1 = 10
arg2 = [1, 2, 3, 4]
def fn(value):
print(value)
return
fn()
Executing the above code throws the below error as we’ve not passed the single
argument required.
If you pass the keyword arguments to a function, then Python determines it through
the parameter name used in the assignment.
def fn(value):
print(value)
return
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.
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.
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.
def fn(a, b) :
temp = 1
for iter in range(b) :
temp = temp*a
return temp
print(fn(2, 4))
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.
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.
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.
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.
var1 = 4
var2 = [2, 4, 6, 8]
def getMin(*varArgs) :
min = varArgs[0]
for i in varArgs[1:] :
if i < min :
min = i
return min
-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.
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)
f = FuncLair(2) ; f()
The output is:
fn2 called
TOC
Function Attributes
Python functions also have attributes.
testFunc.attr1 = "Hello"
testFunc.attr2 = 5
testFunc()
print(dir(testFunc))
The output is:
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.
Python has a reserved keyword known as “class” which you can use to define a new
class.
Let’s now have a clear understanding of each of the above points one by one.
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.
Python calls it automatically for every object created from the class. Its purpose is to
initialize the class attributes with user-supplied values.
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.
def bookInfo(self):
print("Book title:", self.title)
print("Book author:", self.author,"\n")
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.
# output
Book title: Great Expectations
Book author: Charles Dickens
BookStore.noOfBooks: 3
Python Inheritance and OOPs Fundamentals with
Examples
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.
class Vehicle(Taxi):
def vehicleInfo(self):
return self.getModel() + " " + self.getVariant() + "
in " + self.__color + " with " + self.getCapacity() + " seats"
# 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.
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.
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.
<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 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 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.
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.
Thus, the documentation says to quote the desired encoding while opening a file in
Python. See the Python code snippet.
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.
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.
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.
my first file
This 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)
So, to continue, first of all, you should import the <os> module in your Python script.
Example:
import os
Example:
import os
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.
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.
Next, it doesn’t treat special files any differently and won’t create their clones.
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'
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.’
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"
src="1.txt.py"
dst="2.txt.py"
cmd='copy "%s" "%s"' % (src, dst)
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)
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.
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.
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.
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.
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.
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.
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.
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,
Raise Example
>>> raise MemoryError
Traceback (most recent call last):
...
MemoryError
>>> 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)
He does it by adding a new class. The trick here is to derive the custom exception
class from the base exception class.
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.
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
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('')
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
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.
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.
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())
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.
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.')