0% found this document useful (0 votes)
36 views

Introduction To Computer Programming Using Python Comp 111

Uploaded by

Saffa Paul Lahai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Introduction To Computer Programming Using Python Comp 111

Uploaded by

Saffa Paul Lahai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 227

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY

SCHOOL OF TECHNOLOGY

NJALA UNIVERSITY

NJALA CAMPUS

INTRODUCTION TO COMPUTER PROGRAMMING USING PYTHON [COMPS 111]

FOR

FIRST YEAR DEGREE STUDENTS

It is said you must crawl before you can walk, and walk before
you can ride a bicycle.

Python: Interesting Facts You Need To Know


What is the first thing that comes to your mind when you hear
the word “Python”? Is it the ferocious snake or an interesting
programming language?

F.Manna Introduction to Python 2019/2020


Though both these terms sound similar, they end up having
contrasting effects!!

While Python(snake) is the dangerous hostile creature,


Python(programming language) on the other hand, is the
friendlier one. So let us know more about the friendlier one.
Before we begin, you should also know that Python
Certification is an industry-wide used skill sought-after by
most employers and recruiters today.

Do you know who invented Python?

F.Manna Introduction to Python 2019/2020


Guido Van Rossum: A Dutch programmer, popularly known as the
author of Python programming language. He created Python in
1989 and has worked for Google and Dropbox!

Ever wondered why it is named Python?

F.Manna Introduction to Python 2019/2020


There’s an interesting story about it. While implementing
Python, Van Rossum was also reading the published scripts from
“Monty Python’s Flying Circus”, a BBC comedy series from the
1970s. Since he wanted a short, unique and slightly mysterious
name for his invention, he got inspired by the series and
named it Python!

What are some real-life applications?

Over 75% of what you watch is recommended by Netflix.

Recommendations are made by Machine Learning!

F.Manna Introduction to Python 2019/2020


Facebook is using Machine Learning to tag in posts and images.

Alexa is Amazon’s Virtual Personal Assistance used for speech


recognition, weather detection etc.

Do you know different Domains catered by Python?

F.Manna Introduction to Python 2019/2020


All the above technologies make use of Python as an essential
core of their functionalities. So to sum up,

Python is an ocean of opportunities!!

Python has grown to become a popular programming language.


Let me introduce you to the BiG players:

F.Manna Introduction to Python 2019/2020


The simplicity of Python is what makes it so popular!

Let’s look at some FEATURES:

Python is not that complex! It is a high-level dynamic


programming language and is quite easy to learn. Python code
has a very ‘natural’ style to it, which makes it easy to read
and understand.

It’s really a great language for beginners, all the way up to


seasoned professionals!

So, for those of you familiar with Java or C++, Python will
break the mold you have built for a typical programming
language. The above screenshot displays the trends of these
programming languages as per Google.

Python has had a strong spike in popularity over the last


1year!!

F.Manna Introduction to Python 2019/2020


In this constantly evolving and adapting world, Python brings
in peace with its simplicity and ease that supports the
creation and maintenance of a plethora of applications.

Python is a high-level, object-oriented, interpreted


programming language, which has garnered worldwide attention.
Stack Overflow found out that 38.8% of its users mainly use
Python for their projects. According to the website’s survey,
Python’s popularity surpassed that of C# in 2018 – just like
it surpassed PHP in 2017. On the GitHub platform, Python
surpassed Java as the second-most used programming language,
with 40% more pull requests opened in 2017 than in 2016. This
makes Python certification one of the most sought-after
programming certifications.
What is Python?
As I have mentioned Python is an open-source object-oriented
programming language. It first appeared in 1991 and has become
extremely popular among data scientists. StackOverflow calls
it the fastest growing programming language.

F.Manna Introduction to Python 2019/2020


But, what I mean by interpreted language, let’s understand
what is an interpreter first.

Python Interpreter:

An interpreter is a computer program that directly executes,


i.e. performs, instructions written in a programming or
scripting language, without requiring them previously to have
been compiled into a machine language program. So unlike Java,
Python uses an interpreter.

Let us now install Python.

Python Installation:

I will be installing Python in Windows 10 OS. You can try


installing Python in Linux, Mac etc. If you face any issue
mention it in the comments section.

Following are the steps to install Python

1. Go to www.python.org/downloads/

F.Manna Introduction to Python 2019/2020


2. Select the Operating System and also the version of Python.
I am downloading 3.6.0 in my windows machine.

Open the installer and click on “Run”.

3. Click on “Install Now” and check on “Add Python 3.6 to


PATH”.

F.Manna Introduction to Python 2019/2020


4. Start IDLE which is a Python GUI and start scripting.

I don’t prefer using IDLE for coding in Python, instead, I


will download PyCharm which is an IDE (Integrated Development
Environment).

PYTHON IDE (INTEGRATED DEVELOPMENT ENVIRONMENT):

IDE typically provides a code editor, compiler/ interpreter


and debugger in one GUI (Graphical User Interface). It
encapsulates the entire process of code creation, compilation
and testing which increases the productivity of developers.

F.Manna Introduction to Python 2019/2020


A developer working with an IDE starts with a model, which the
IDE translates into suitable code. The IDE then debugs and
tests the model-driven code, with a high level of automation.
Once the build is successful and properly tested, it can be
deployed for further testing through the IDE or other tools
outside of the IDE.

I am going to use PyCharm, you can use any other IDE that you
want.

Installing PyCharm (Python IDE):

Go to www.jetbrains.com/pycharm/download/#section=windows

Here, the community version is free, but for the professional


version, you need to buy the license. I will be working on the
PyCharm community version.

Now, let us have a look at why one should even consider Python
as a preferred or first programming language.

F.Manna Introduction to Python 2019/2020


Why Learn Python?

Python’s syntax is very easy to understand. The lines of code


required for a task is less compared to other languages. Let
me give you an example – If I have to print “Welcome To
Python!” all I have to type:

print (“Welcome To Python!”)

Let’s look at some cool features of Python:

1. Simple and easy to learn


2. Free and Open Source
3. Portable
4. Supports different programming paradigm
5. Extensible

If you are wondering where you can use Python (Python


Application), let me tell you that is where Python stands out.

Python Applications:

1. Artificial Intelligence
2. Desktop Application
3. Automation
4. Web Development
5. Data Wrangling, Exploration And Visualization

Let us now start coding in Python, as I have mentioned above I


will be using PyCharm.

F.Manna Introduction to Python 2019/2020


Variables in Python:

Variables are nothing but reserved memory locations to store


values. This means that when you create a variable you reserve
some space in memory.

Fig: The figure above shows three variables A, B and C

In Python you don’t need to declare variables before using it,


unlike other languages like Java, C etc.

Assigning values to a variable

Python variables do not need explicit declaration to reserve


memory space. The declaration happens automatically when you
assign a value to a variable. The equal sign (=) is used to
assign values to variables. Consider the below example:

S = 10
print(S)

F.Manna Introduction to Python 2019/2020


This will assign value ‘10’ to the variable ‘S’ and will print
it. Try it yourself.

Data Types in Python

Python supports various data types, these data types define


the operations possible on the variables and the storage
method. Below is the list of standard data types available in
Python:

Let’s discuss each of these in detail, we’ll start with


‘Numeric’ data type.

Numeric:

Just as expected Numeric data types store numeric values. They


are immutable data types, this means that you cannot change
it’s value. Python supports three different Numeric data
types:

Integer type: It holds all the integer values i.e. all the
positive and negative whole numbers, example – 10.

Float type: It holds the real numbers and are represented by


decimal and sometimes even scientific notations with E or e

F.Manna Introduction to Python 2019/2020


indicating the power of 10 (2.5e2 = 2.5 x 102 = 250), example
– 10.24.

Complex type: These are of the form a + bj, where a and b are
floats and J represents the square root of -1 (which is an
imaginary number), example – 10+6j.

Now you can even perform type conversion. For example, you can
convert the integer value to a float value and vice-versa.
Consider the example below:

A = 10
# Convert it into float type
B = float(A)
print(B)

The code above will convert an integer value to a float type.


Similarly you can convert a float value to integer type:

A = 10.76
# Convert it into float type
B = int(A)
print(B)

List:

● You can consider the Lists as Arrays in C, but in List


you can store elements of different types, but in Array
all the elements should be of the same type.
● List is the most versatile datatype available in Python
which can be written as a list of comma-separated values
(items) between square brackets. Consider the example
below:

Subjects = ['Physics', 'Chemistry', 'Maths', 2]

print(Subjects)

F.Manna Introduction to Python 2019/2020


Notice that the Subjects List contains both words as well as
numbers. Now, let’s perform some operations on our Subjects
List.

Let’s look at few operations that you can perform with Lists:

Syntax Result Description

Subjects Physics This will give the index 0


[0] value from the Subjects
List.

Subjects Physics, Chemistry This will give the index


[0:2] values from 0 till 2, but
it won’t include 2 the
Subjects List.

Subjects [‘Physics’, It will update the List and


[3] = ‘Chemistry’, ‘Maths’, add ‘Biology’ at index 3
‘Biology’ ‘Biology’] and remove 2.

del [‘Physics’, This will delete the index


Subjects ‘Chemistry’, 2] value 2 from Subjects List.
[2]

len [‘Physics, This will return the length


(Subjects) ‘Chemistry’, ‘Maths’, of the list
2, 1, 2, 3]

Subjects * [‘Physics’, This will repeat the


2 ‘Chemistry’, ‘Maths’, Subjects List twice.
2]

F.Manna Introduction to Python 2019/2020


[‘Physics’,
‘Chemistry’, ‘Maths’,
2]

Subjects [2, ‘Maths’, This will reverse the


[::-1] ‘Chemistry’, Subjects List
‘Physics’]

Tuples:

A Tuple is a sequence of immutable Python objects. Tuples are


sequences, just like Lists. The differences between tuples and
lists are:

● Tuples cannot be changed unlike lists


● Tuples use parentheses, whereas lists use square
brackets. Consider the example below:

Chelsea = ('Hazard', 'Lampard', 'Terry')

Now you must be thinking why Tuples when we have Lists?

So the simple answer would be, Tuples are faster than Lists.
If you’re defining a constant set of values which you just
want to iterate, then use Tuple instead of a List.

Guys, all Tuple operations are similar to Lists, but you


cannot update, delete or add an element to a Tuple.

Now, stop being lazy and don’t expect me to show all those
operations, try it yourself.

Strings:

F.Manna Introduction to Python 2019/2020


Strings are amongst the most popular data types in Python. We
can create them simply by enclosing characters in quotes.
Python treats single and double quotes in exactly the same
fashion. Consider the example below:

S = "Welcome To Python!"
D = 'Python!'

Let’s look at a few operations that you can perform with


Strings.

Syntax Operation

print (len(String_Name)) String Length

print Locate a character in String


(String_Name.index(“Char”)
)

print Count the number of times a


(String_Name.count(“Char”) character is repeated in a String
)

print Slicing
(String_Name[Start:Stop])

print (String_Name[::-1]) Reverse a String

print Convert the letters in a String


(String_Name.upper()) to upper-case

F.Manna Introduction to Python 2019/2020


print Convert the letters in a String
(String_Name.lower()) to lower-case

Set:

● A Set is an unordered collection of items. Every element


is unique.
● A Set is created by placing all the items (elements)
inside curly braces {}, separated by comma. Consider the
example below:

Set_1 = {1, 2, 3}

In Sets, every element has to be unique. Try printing the


below code:

Set_2 = {1, 2, 3, 3}

Here 3 is repeated twice, but it will print it only once.

Let’s look at some Set operations:

Union:

Union of A and B is a set of all the elements from both sets.


Union is performed using | operator. Consider the below
example:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print ( A | B)

F.Manna Introduction to Python 2019/2020


Output = {1, 2, 3, 4, 5, 6}

Intersection:

Intersection of A and B is a set of elements that are common


in both sets. Intersection is performed using & operator.
Consider the example below:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print ( A & B )

Output = {3, 4}

Difference:

F.Manna Introduction to Python 2019/2020


Difference of A and B (A – B) is a set of elements that are
only in A but not in B. Similarly, B – A is a set of element
in B but not in A. Consider the example below:

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)

Output = {1, 2, 3}

Symmetric Difference:

F.Manna Introduction to Python 2019/2020


Symmetric Difference of A and B is a set of elements in both A
and B except those that are common in both. Symmetric
difference is performed using ^ operator. Consider the example
below:

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)

Output = {1, 2, 3, 6, 7, 8}

Dictionary:

F.Manna Introduction to Python 2019/2020


I am guessing you guys know about National ID Cards. For those
of you who don’t know what it is, it is nothing but a unique
ID which has been given to all Sierra Leone citizens.

So for every National ID number, there is a name and few other


details attached.

Now you can consider the National ID number as a ‘Key’ and the
person’s detail as the ‘Value’ attached to that Key.

Dictionaries contain these ‘Key Value’ pairs enclosed within


curly braces and Keys and values are separated with ‘:’.
Consider the below example:

Dict = {'Name' : 'Saurabh', 'Age' : 23}

You know the drill, now comes various Dictionary operations.

● Access elements from a dictionary:

Dict = {'Name' : 'Saurabh', 'Age' : 23}


print(Dict['Name'])

Output = Saurabh

● Changing elements in a Dictionary:

Dict = {'Name' : 'Saurabh', 'Age' : 23}


Dict['Age'] = 32
Dict['Address'] = 'Starc Tower'

Output = {'Name' = 'Saurabh', 'Age' = 32, 'Address' = 'Starc


Tower'}

Operators in Python:

F.Manna Introduction to Python 2019/2020


Operators are the constructs which can manipulate the values
of the operands. Consider the expression 2 + 3 = 5, here 2 and
3 are operands and + is called operator.

Python supports the following types of Operators:

Let’s focus on each of these Operators one by one.

Arithmetic Operators:

These Operators are used to perform mathematical operations


like addition, subtraction etc. Assume that A = 10 and B = 20
for the below table.

Operator Description Example

F.Manna Introduction to Python 2019/2020


+ Addition Adds values on either side of A + B = 30
the operator

– Subtraction Subtracts the right hand A – B = -10


operator with left hand
operator

* Multiplies values on either A * B = 200


Multiplication side of the operator

/ Division Divides left hand operand with A / B = 0.5


right hand operator

% Modulus Divides left hand operand by B % A = 0


right hand operand and returns
remainder

** Exponent Performs exponential (power) A ** B = 10


calculation on operators to the power
20

Consider the example below:

F.Manna Introduction to Python 2019/2020


a = 21
b = 10
c = 0

c = a + b
print(c)

c = a - b
print(c)

c = a * b
print(c)

c = a / b
print(c)

c = a % b
print(c)

a = 2
b = 3
c = a ** b

print(c)

Output = 31, 11, 210, 2.1, 1, 8

Now let’s see comparison Operators.

Comparison Operators:

These Operators compare the values on either sides of them and


decide the relation among them. Assume A = 10 and B = 20.

F.Manna Introduction to Python 2019/2020


Operator Description Example

== (A == B) is
not true
If the values of two
operands are equal, then the
condition becomes true.

!= (A != B) is
true
If values of two operands
are not equal, then the
condition becomes true.

> If the value of the left (a > b) is


operand is greater than the not true
value of the right operand, then
the condition becomes true.

< If the value of the left (a < b) is


operand is less than the value true
of the right operand, then the
condition becomes true.

>= If the value of the left (a >= b) is


operand is greater than or equal not true
to the value of the right

F.Manna Introduction to Python 2019/2020


operand, then the condition
becomes true.

<= If the value of the left (a <= b) is


operand is less than or equal to true
the value of the right operand,
then the condition becomes true.

Consider the example below:

a = 21
b = 10
c = 0

if (a == b):
print("a is equal to b")
else:
print("a is not equal to b")

if (a != b):
print("a is not equal to b")
else:
print("a is equal to b")

if (a < b):
print("a is less than b")
else:
print("a is not less than b")

if (a > b):
print("a is greater than b")
else:
print("a is not greater than b")

a = 5
b = 20

F.Manna Introduction to Python 2019/2020


if (a <= b):
print("a is either less than or equal to b")
else:
print("a is neither less than nor equal to b")

if (a >= b):
print("a is either greater than or equal to
b")
else:
print("a is neither greater than nor equal to
b")

Output = a is not equal to b

a is not equal to b

a is not less than b

a is greater than b

a is either less than or equal to b

b is either greater than or equal to b

Now in the above example, I have used conditional statements


(if, else). It basically means if the condition is true then
execute the print statement, if not then execute the print
statement inside else. We will understand these statements
later.

Assignment Operators:

F.Manna Introduction to Python 2019/2020


An Assignment Operator is the operator used to assign a new
value to a variable. Assume A = 10 and B = 20 for the below
table.

Operator Description Example

= Assigns values from right side c = a + b


operands to left side operand assigns value
of a + b into
c

+= Add AND It adds right operand to the left c += a is


operand and assign the result to equivalent to
left operand c = c + a

-= Subtract It subtracts right operand from c -= a is


AND the left operand and assign the equivalent to
result to left operand c = c – a

*= Multiply It multiplies right operand with c *= a is


AND the left operand and assign the equivalent to
result to left operand c = c * a

/= Divide It divides left operand with the c /= a is


AND right operand and assign the equivalent to
result to left operand c = c / a

%= Modulus It takes modulus using two c %= a is


AND operands and assign the result to equivalent to
left operand c = c % a

F.Manna Introduction to Python 2019/2020


**= Performs exponential (power) c **= a is
Exponent calculation on operators and equivalent to
AND assign value to the left operand c = c ** a

Consider the example below:

a = 21
b = 10
c = 0

c = a + b
print(c)

c += a
print(c)

c *= a
print(c)

c /= a
print(c)

c = 2
c %= a
print(c)

c **= a
print(c)

Output = 31, 52, 1092, 52.0, 2, 2097152, 99864

Bitwise Operators:

These operations directly manipulate bits. In all computers,


numbers are represented with bits, a series of zeros and ones.

F.Manna Introduction to Python 2019/2020


In fact, pretty much everything in a computer is represented
by bits. Consider the example shown below:

Following are the Bitwise Operators supported by Python:

F.Manna Introduction to Python 2019/2020


F.Manna Introduction to Python 2019/2020
Consider the example below:

a = 58 # 111010
b = 13 # 1101
c = 0

c = a & b
print(c) # 8 = 1000

c = a | b
print(c) # 63 = 111111

c = a ^ b
print(c) # 55 = 110111

c = a >> 2
print(c) # 232 = 11101000

c = a << 2
print(c) # 14 = 1110

Output = 8,63,55,232,14

F.Manna Introduction to Python 2019/2020


Logical Operators:

The following are the Logical Operators present in Python:

Operator Description Example

and True if both the operands are true X and Y

or True if either of the operands are X or Y


true

not True if operand is false (complements not X


the operand)

Consider the example below:

F.Manna Introduction to Python 2019/2020


x = True
y = False

print('x and y is', x and y)

print('x or y is', x or y)

print('not x is', not x)

Output = x and y is False

x or y is True

not x is False

Membership Operators:

These Operators are used to test whether a value or a variable


is found in a sequence (Lists, Tuples, Sets, Strings,
Dictionaries) or not. The following are the Membership
Operators:

Operator Description Example

in True if value/variable is found in the 5 in x


sequence

not in True if value/variable is not found in 5 not in x


the sequence

Consider the example below:

F.Manna Introduction to Python 2019/2020


X = [1, 2, 3, 4]
A = 3
print(A in X)
print(A not in X)

Output = True

False

Identity Operators:

These Operators are used to check if two values (or variables)


are located on the same part of the memory. Two variables that
are equal does not imply that they are identical.

Following are the Identity Operators in Python:

Operator Description Example

is True if the operands are identical x is True

is not True if the operands are not x is not


identical True

Consider the example below:

F.Manna Introduction to Python 2019/2020


X1 = 'Welcome To Python!'

X2 = 1234

Y1 = 'Welcome To Python!'

Y2 = 1234

print(X1 is Y1)

print(X1 is not Y1)

print(X1 is not Y2)

print(X1 is X2)

Output = True

False

True

False

Python Statement

F.Manna Introduction to Python 2019/2020


Instructions that a Python interpreter can execute are called
statements. For example, a = 1 is an assignment statement. if
statement, for statement, while statement, etc. are other
kinds of statements which will be discussed later.

Multi-line statement

In Python, the end of a statement is marked by a newline


character. But we can make a statement extend over multiple
lines with the line continuation character (\). For example:

a = 1 + 2 + 3 + \

4 + 5 + 6 + \
7 + 8 + 9

This is an explicit line continuation. In Python, line


continuation is implied inside parentheses ( ), brackets [ ],
and braces { }. For instance, we can implement the above
multi-line statement as:

a = (1 + 2 + 3 +

4 + 5 + 6 +
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation


implicitly. Same is the case with [ ] and { }. For example:

colors = ['red','blue','green']

F.Manna Introduction to Python 2019/2020


We can also put multiple statements in a single line using
semicolons, as follows:

a = 1; b = 2; c = 3

Python Indentation

Most of the programming languages like C, C++, and Java use


braces { } to define a block of code. Python, however, uses
indentation.

A code block (body of a function, loop, etc.) starts with


indentation and ends with the first unindented line. The
amount of indentation is up to you, but it must be consistent
throughout that block.

In Python, all the code that you type is arranged via correct
whitespaces and therefore if at any instance you have a bad
indentation, the overall code will not run and the interpreter
will simply return an error function.

Generally, four whitespaces are used for indentation and are


preferred over tabs. Here is an example.

for i in range(1,11):

print(i)

if i == 5:
break

The enforcement of indentation in Python makes the code look


neat and clean. This results in Python programs that look
similar and consistent.

F.Manna Introduction to Python 2019/2020


Indentation can be ignored in line continuation, but it's
always a good idea to indent. It makes the code more readable.
For example:

if True:

print('Hello')
a = 5

and

if True: print('Hello'); a = 5

both are valid and do the same thing, but the former style is
clearer.

Incorrect indentation will result in IndentationError.

Python follows the PEP8 whitespace ethics while arranging its

code and therefore it is suggested that there should be 4

whitespaces between every iteration and any alternative that

doesn’t have this will return an error.

Moving on with this article on Indentation Error in Python

The cause of Indentation Error in Python


As mentioned in the introduction paragraph, one of the main

reasons for the indentation error is the absence of tabs and

or whitespaces between lines of code. Since python makes use

F.Manna Introduction to Python 2019/2020


of procedural language, if you miss out on adding tabs or

spaces between your lines of code, then you will most likely

experience this error. Although in some cases the entire

program will run correctly, in others the error will come in

the middle of the execution and therefore pause the entire

process.

Mentioned below are some of the common causes of an

indentation error in Python:

● While coding you are using both the tab as well as space.
While in theory both of them serve the same purpose, if
used alternatively in a code, the interpreter gets
confused between which alteration to use and thus returns
an error.
● While programming you have placed an indentation in the
wrong place. Since python follows strict guidelines when
it comes to arranging the code, if you placed any
indentation in the wrong place, the indentation error is
mostly inevitable.
● Sometimes in the midst of finishing a long program, we
tend to miss out on indenting the compound statements
such as for, while and if and this in most cases will
lead to an indentation error.
● Last but not least, if you forget to use user defined
classes, then an indentation error will most likely pop
up.

A solution to the Indentation Error

F.Manna Introduction to Python 2019/2020


Now that you know why this error is caused in the first place,

let us explore some of the solutions to it.

#1 Solution
While there is no quick fix to this problem, one thing that

you need to keep in mind while trying to find a solution for

the indentation error is the fact that you have to go through

each line individually and find out which one contains the

error.

In Python, all the lines of code are arranged according to

blocks, so it becomes easier for you to spot an error. For

example, if you have used the if statement in any line, the

next line must definitely have an indentation.

Take a look at the example below.

If you need guidance on how the correct form of indentation

will look like, take a look at the example below.

F.Manna Introduction to Python 2019/2020


#2 Solution
If the above-mentioned solution didn’t work for you, and you

are having a hard time figuring out which line you have missed

the indentation at, then follow these steps. Go to the setting

of your code editor and enable the option which shows the tab

and whitespaces. Once this feature is turned on, you will see

small single dots in between your code, where each dot

represents whitespace or a tab. If you see that a dot is

missing somewhere that it needs to be, then that line probably

has the indentation error.

To enable the option in order to view the tabs or whitespaces,

take a look at the image below.

F.Manna Introduction to Python 2019/2020


Another option to get out of this problem is to use the built

in Indent Guide in the Python interpreter.

Enabling this option will guide through each line of code and

show you exactly where your error lies. Although this method

is highly inefficient taking into consideration that your

program contains several lines of code, this is the surest way

to find and fix all existing errors.

Python Comments

Comments are very important while writing a program. They


describe what is going on inside a program, so that a person
looking at the source code does not have a hard time figuring
it out.

F.Manna Introduction to Python 2019/2020


You might forget the key details of the program you just wrote
in a month's time. So taking the time to explain these
concepts in the form of comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a


comment.

It extends up to the newline character. Comments are for


programmers to better understand a program. Python Interpreter
ignores comments.

#This is a comment

#print out Hello


print('Hello')

Run Code

Multi-line comments

We can have comments that extend up to multiple lines. One way


is to use the hash(#) symbol at the beginning of each line.
For example:

#This is a long comment

F.Manna Introduction to Python 2019/2020


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either '''


or """.

These triple quotes are generally used for multi-line strings.


But they can be used as a multi-line comment as well. Unless
they are not docstrings, they do not generate any extra code.

"""This is also a

perfect example of
multi-line comments"""

Flow Control
Flow Control lets us define a flow in executing our programs.
To mimic the real world, you need to transform real world
situations into your program. For this you need to control the
execution of your program statements using Flow Controls.

Figure: Python Programming Language- Flow Control


There are six basic flow controls used in Python programming:

1. if
2. for
3. while
4. break

F.Manna Introduction to Python 2019/2020


5. continue
6. pass

If Statement
The Python compound statement ’if’ lets you conditionally
execute blocks of statements.
Syntax of If statement:
if expression:
statement (s)
elif expression:
statement (s)
elif expression:
statement (s)
...
else:
statement (s)

Figure: Python Programming Language – If – Facebook Login


Example
The above image explains the use of the ‘if’ statement using
an example of Facebook login.

F.Manna Introduction to Python 2019/2020


1. Facebook login page will direct you to two pages based on
whether your username and password is a match to your
account.
2. If the password entered is wrong, it will direct you to
the page on the left.
3. If the password entered is correct, you will be directed
to your homepage.

Let us now look at how Facebook would use the If statement.

password = facebook_hash(input_password)
if password == hash_password
print('Login successful.')
else
print('Login failed. Incorrect password.')

The above code just gives a high level implementation of If


statement in the Facebook login example used. Facebook_hash()
function takes the input_password as a parameter and compares
it with the hash value stored for that particular user.

For Statement
The for statement supports repeated execution of a statement
or block of statements that is controlled by an iterable
expression.
Syntax of For statement:

for target in iterable:


statement (s)

F.Manna Introduction to Python 2019/2020


Figure: Python Programming Language- For – Facebook Friends
Example

The ‘for’ statement can be understood from the above example.

● Listing ‘Friends’ from your profile will display the


names and photos of all of your friends
● To achieve this, Facebook gets your ‘friendlist’ list
containing all the profiles of your friends

F.Manna Introduction to Python 2019/2020


● Facebook then starts displaying the HTML of all the
profiles till the list index reaches ‘NULL’
● The action of populating all the profiles onto your page
is controlled by ‘for’ statement

Let us now look at a sample program in Python to demonstrate


the For statement.

travelling = input("Are you travelling? Yes or No:")


while travelling == 'yes':
num = int(input("Enter the number of people travelling:"))
for num in range(1,num+1):
name = input("Enter Details Name:")
age = input("Age:")
sex = input("Male or Female:")
print("Details Stored",name)
print(age)
print(sex)
print("Thank you!")
travelling = input("Are you travelling? Yes or No:")
print("Please come back again.")

The output is as below:


Are you travelling? Yes or No:Yes
Enter the number of people travelling:1
Enter Details
Name:Harry
Age:20
Male or Female:Male
Details Stored
Harry
20
Male
Thank you
Are you travelling? Yes or No:No

F.Manna Introduction to Python 2019/2020


Please come back again.

While Statement
The while statement in Python programming supports repeated
execution of a statement or block of statements that is
controlled by a conditional expression.
Syntax of While statement:
while expression:
statement (s)

Figure: Python Programming Language – While – Facebook


Newsfeed Example

We will use the above Facebook Newsfeed to understand the use


of while loop.

● When we login to our homepage on Facebook, we have about


10 stories loaded on our newsfeed
● As soon as we reach the end of the page, Facebook loads
another 10 stories onto our newsfeed

F.Manna Introduction to Python 2019/2020


● This demonstrates how ‘while’ loop can be used to achieve
this

Let us now look at a sample program in Python to demonstrate


the While statement.

count = 0
print('Printing numbers from 0 to 9')
while (count<10):
print('The count is ',count)
count = count+1
print('Good Bye')

This program prints numbers from 0 to 9 using the while


statement to restrict the loop till it reaches 9. The output
is as below:
The count is 0
The count is 1
The count is 2
The count is 3
The count is 4
The count is 5
The count is 6
The count is 7
The count is 8
The count is 9

Break Statement
The break statement is allowed only inside a loop body. When
break executes, the loop terminates. If a loop is nested
inside other loops, break terminates only the innermost nested
loop.
Syntax of Break statement:

F.Manna Introduction to Python 2019/2020


while True:
x = get_next()
y = preprocess(x)
if not keep_looking(x, y): break
process(x, y)

Figure: Python Programming Language- Break – Alarm And


Incoming Call
The ‘break’ flow control statement can be understood from the
above example.

● Let us consider the case of an alarm on a mobile ringing


at a particular time.
● Suppose the phone gets an incoming call in the time the
alarm is ringing, the alarm is stopped immediately and
the phone ringer starts ringing.
● This is how break essentially works.

F.Manna Introduction to Python 2019/2020


Let us now look at a sample program in Python to demonstrate
the Break statement.

for letter in 'The Quick Brown Fox. Jumps,


Over The Lazy Dog':
if letter == '.':
break
print ('Current Letter :', letter)

This program prints all the letters in a given string. It


breaks whenever it encounters a ‘.’ or a full stop. We have
done this by using Break statement. The output is as below.
Current Letter : T
Current Letter : h
Current Letter : e
Current Letter :
Current Letter : Q
Current Letter : u
Current Letter : i
Current Letter : c
Current Letter : k
Current Letter :
Current Letter : B
Current Letter : r
Current Letter : o
Current Letter : w
Current Letter : n
Current Letter :
Current Letter : F
Current Letter : o
Current Letter : x

Continue Statement
The continue statement is allowed only inside a loop body.
When continue executes, the current iteration of the loop body
terminates, and execution continues with the next iteration of
the loop.
F.Manna Introduction to Python 2019/2020
Syntax of Continue statement:
for x in some_container:
if not seems_ok(x): continue
lowbound, highbound = bounds_to_test()
if x<lowbound or x>=highbound: continue
if final_check(x):
do_processing(x)

Figure: Python Programming Language – Continue – Incoming Call


And Alarm Example
Example: The Continue statement can be understood using
incoming call and alarms.

● Suppose we are on a call and the alarm is scheduled


during the call time, then the alarm trigger recognizes
the call event

F.Manna Introduction to Python 2019/2020


● Once the call event is noted, the phone continues the
alarm to ring at the next snooze period

Let us now look at a sample program in Python to demonstrate


the Continue statement.

for num in range(10, 21):


if num % 5 == 0:
print ("Found a multiple of 5")
pass
num = num + 1
continue
print ("Found number: ", num)

This program prints all the numbers except the multiples of 5


from 10 to 20. The output is as follows.
Found a multiple of 5
Found number: 11
Found number: 12
Found number: 13
Found number: 14
Found a multiple of 5
Found number: 16
Found number: 17
Found number: 18
Found number: 19
Found a multiple of 5

Pass Statement
The pass statement, which performs no action, can be used as a
placeholder when a statement is syntactically required but you
have nothing specific to do.
Syntax of Pass statement:

F.Manna Introduction to Python 2019/2020


if condition1(x):
process1(x)
elif x>23 or condition2(x) and x<5:
pass
elif condition3(x):
process3(x)
else:
process_default(x)

Now let us look at a sample program in Python to demonstrate


the Pass statement.

for num in range(10, 21):


if num % 5 == 0:
print ("Found a multiple of 5: ")
pass
num++
print ("Found number: ", num)

This program prints the multiples of 5 with a separate


sentence. The output is as follows.

Found a multiple of 5: 10
Found number: 11
Found number: 12
Found number: 13
Found number: 14
Found a multiple of 5: 15
Found number: 16
Found number: 17
Found number: 18
Found number: 19
Found a multiple of 5: 20
After learning the above six flow control statements, let us
now learn what functions are.

F.Manna Introduction to Python 2019/2020


Functions
Functions in Python programming, is a group of related
statements that performs a specific task. Functions make our
program more organized and help in code reusability.

Figure: Python Programming Language – Understanding Functions

Uses Of Functions:

1. Functions help in code reusability


2. Functions provide organization to the code
3. Functions provide abstraction
4. Functions help in extensibility

F.Manna Introduction to Python 2019/2020


Figure: Python Programming Language – Demonstrating The Uses
Of Functions
The code used in the above example is as below:

# Defining a function to reverse a string

def reverse_a_string():
# Reading input from console
a_string = input("Enter a string")
new_strings = []

# Storing length of input string


index = len(a_string)

# Reversing the string using while loop


while index:
index -= 1
new_strings.append(a_string[index])
# Printing the reversed string
print(''.join(new_strings))
reverse_a_string()

F.Manna Introduction to Python 2019/2020


We have thus shown the power of using functions in Python.

File Handling
File Handling refers to those operations that are used to read
or write a file.
To perform file handling, we need to perform these steps:

1. Open File
2. Read / Write File
3. Close File

Figure: Python Programming Language- File Handling In Python

Opening A File

● Python has a built-in function open() to open a file


● This function returns a file object, also called a
handle, as it is used to read or modify the file
accordingly

Example program:
1 file =
2 open("C:/Users/Edureka/Hello.txt"
3 , "r")
for line in file:
print (line)

F.Manna Introduction to Python 2019/2020


The output is as below:
One
Two
Three

Writing To A File

● In order to write into a file we need to open it in write


‘w’, append ‘a’ or exclusive creation ‘x’ mode
● We need to be careful with the ‘w’ mode as it will
overwrite into the file if it already exists. All
previous data are erased
● Writing a string or sequence of bytes (for binary files)
is done using write() method

Example program:
1 with
2 open("C:/Users/Edureka/Writing_Into_File.txt
3 ", "w") as f
4 f.write("First Line
5 ")
6 f.write("Second Line
7 ")
8
9 file = open("D:/Writing_Into_File.txt", "r")
for line in file:
print (line)
The output is as below:
First Line
Second Line

Reading From A File

● To read the content of a file, we must open the file in


the reading mode
● We can use the read(size) method to read in size number
of data

F.Manna Introduction to Python 2019/2020


● If size parameter is not specified, it reads and returns
up to the end of the file

Example program:
1 file =
2 open("C:/Users/Edureka/Writing_Into_File.
3 txt", "r")
4 print(file.read(5))
print(file.read(4))
print(file.read())
The output is as below:
First Line
Second Line

Closing A File

● When we are done with operations to the file, we need to


properly close it.
● Closing a file will free up the resources that were tied
with the file and is done using the close() method.

Example program:
1 file =
2 open("C:/Users/Edureka/Hello.txt"
3 , "r")
4 text = file.readlines()
print(text)
file.close()
The output is as below:
['One
', 'Two
', 'Three']

Object & Class


Python is an object oriented programming language. Object is
simply a collection of data (variables) and methods
(functions) that act on those data. Class is a blueprint for
the object.

F.Manna Introduction to Python 2019/2020


Defining A Class
We define a class using the keyword “Class”. The first string
is called docstring and has a brief description about the
class.
1 class MyNewClass:
2 '''This is a docstring. I have created
3 a new class'''
pass

Creating An Object
A Class object can be used to create new object instances
(instantiation) of that class. The procedure to create an
object is similar to a function call.
1 ob =
MyNewClass
We have thus learnt how to create an object from a given
class.
So this concludes our Python Programming blog. I hope you
enjoyed reading this blog and found it informative. By now,
you must have acquired a sound understanding of what Python
Programming Language is. Now go ahead and practice all the
examples
In the immensely fast moving world, one needs resourceful
coding techniques that could help the programmer to sum up
voluminous codes in the simplest and most convenient ways.
Arrays are one of the data structures that help you write a
number of values into a single variable, thereby reducing the

F.Manna Introduction to Python 2019/2020


burden of memorizing an enormous number of variables. So let’s
go ahead, and see how you can implement Arrays in Python.
Here’s an overview of the topics which explains all the
aspects dealing with arrays:

Conditional Statements:

Conditional statements are used to execute a statement or a


group of statements when some condition is true. There are
namely three conditional statements – If, Elif, Else.

Consider the flowchart shown below:

F.Manna Introduction to Python 2019/2020


Let me tell you how it actually works.

● First the control will check the ‘If’ condition. If it's


true, then the control will execute the statements after
If condition.
● When the ‘If’ condition is false, then the control will
check the ‘Elif’ condition. If Elif condition is true
then the control will execute the statements after Elif
condition.
● If ‘Elif’ Condition is also false then the control will
execute the Else statements.

Below is the syntax:

F.Manna Introduction to Python 2019/2020


if
1 condition1:
2
3 statements
4
5 elif
6 condition2:
7
8 statements

else:

statements

Consider the example below:

X = 10
1 Y = 12
2
3 if X < Y: print('X is
4 less than Y')
5 elif X > Y:
6 print('X is greater
7 than Y')
8 else:
print('X and Y are
equal')

Output = X is less than Y

Now is the time to understand Loops.

Loops:

F.Manna Introduction to Python 2019/2020


● In general, statements are executed sequentially. The
first statement in a function is executed first, followed
by the second, and so on
● There may be a situation when you need to execute a block
of code several number of times

A loop statement allows us to execute a statement or group of


statements multiple times. The following diagram illustrates a
loop statement:

Let me explain you the above diagram:

● First the control will check the condition. If it is true


then the control will move inside the loop and execute
the statements inside the loop.
● Now, the control will again check the condition, if it is
still true then again it will execute the statements
inside the loop.
● This process will keep on repeating until the condition
becomes false. Once the condition becomes false the
control will move out of loop.

F.Manna Introduction to Python 2019/2020


There are two types of loops:

● Infinite: When condition will never become false


● Finite: At one point, the condition will become false and
the control will move out of the loop

There is one more way to categorize loops:

● Pre-test: In this type of loops the condition is first


checked and then only the control moves inside the loop
● Post-test: Here first the statements inside the loops are
executed, and then the condition is checked

Python does not support Post-test loops.

Learn Python From Experts

Loops in Python:

In Python, there are three loops:

● While
● For
● Nested

While Loop: Here, first the condition is checked and if it’s


true, control will move inside the loop and execute the
statements inside the loop until the condition becomes false.
We use this loop when we are not sure how many times we need
to execute a group of statements or you can say that when we
are unsure about the number of iterations.

Consider the example:

F.Manna Introduction to Python 2019/2020


count = 0
1 while (count <
2 10):
3 print (
4 count )
5 count =
6 count + 1

print ("Good
bye!")

Output = 0

Good bye!

For Loop: Like the While loop, the For loop also allows a code
block to be repeated certain number of times. The difference
is, in For loop we know the amount of iterations required
unlike While loop, where iterations depends on the condition.

F.Manna Introduction to Python 2019/2020


You will get a better idea about the difference between the
two by looking at the syntax:

for variable in
1 Sequence:
2 statements

Notice here, we have specified the range, that means we know


the number of times the code block will be executed.

Consider the example:

fruits = ['Banana', 'Apple',


1 'Grapes']
2
3 for index in
4 range(len(fruits)):
print (fruits[index])

Output = Banana

Apple

Grapes

Nested Loops: It basically means a loop inside a loop. It can


be a For loop inside a While loop and vice-versa. Even a For
loop can be inside a For loop or a While loop inside a While
loop.

Consider the example:

count = 1
1 for i in
2 range(10):
3 print (str(i)
4 * i)
5

F.Manna Introduction to Python 2019/2020


6 for j in
range(0, i):
count =
count +1

Output =

22

333

4444

55555

666666

7777777

88888888

999999999

Now is the best time to introduce functions in this Python


Tutorial.

F.Manna Introduction to Python 2019/2020


Functions:

Functions are a convenient way to divide your code into useful


blocks, allowing us to order our code, make it more readable,
reuse it and save some time.

F.Manna Introduction to Python 2019/2020


1 def add (a,
2 b):
3 return
4 a + b
c =
add(10,20)
print(c)

Output = 30

Python I/O Operation:

How To Open A File Using Python?

Python has a built-in function open(), top open a file. This


function returns a file object, also called a handle, as it is
used to read or modify the file accordingly.

We can specify the mode while opening a file. In the mode, we


specify whether we want to

● read ‘r’
● write ‘w’ or
● append ‘a’ to the file. We also specify if we want to
open the file in text mode or binary mode.

The default is reading in text mode. In this mode, we get


strings when reading from the file.

1 o = open("edureka.txt") # equivalent
2 to 'r' or 'rt'
3 o = open ("edureka.txt",'w') # write in
text mode
o = open ("img1.bmp",'rb' ) # read and
write in binary mode

How To Close A File Using Python?

F.Manna Introduction to Python 2019/2020


When we are done with operations to the file, we need to
properly close the file.

Closing a file will free up the resources that were tied with
the file and is done using Python close() method.

1 o = open
2 ("edureka.txt")
o.close()

Top 10 Reasons To Learn Python


Programming languages have been around for ages, and every
decade sees the launch of a new language sweeping developers
off their feet. Python is considered as one of the most
popular and in-demand programming language. A recent Stack
Overflow survey showed that Python has taken over languages
such as Java, C, C++ and has made its way to the top. This
makes Python certification one of the most sought-after
programming certifications. Through this blog, I will be
listing down the top 10 reasons to learn Python.
Get ready to fall in love with Python!!
Below are the major features and applications due to which
people choose Python as their first programming language:

1. Python’s popularity & high salary

F.Manna Introduction to Python 2019/2020


2. Python is used in Data Science
3. Python’s scripting & automation
4. Python used with Big Data
5. Python supports Testing
6. Computer Graphics in Python
7. Python used in Artificial Intelligence
8. Python in Web Development
9. Python is portable & extensible
10. Python is simple & easy to learn

If you are planning to start your career in Python and wish to


know the skills related to it, now is the right time to dive
in, when the technology is in its nascent state.

Top 10 Reasons to Learn Python | Learn Python Programming |


Edureka

Now, let me help you to understand these in more detail.

10. Simple & Easy To Learn


So at number 10, Python is extremely simple and easy to learn.
It is a very powerful language and it closely resembles the
English language!
So, what contributes to its simplicity? Python is

● Free & open source


● High-level
● Interpreted
● Blessed with large community

Furthermore, in Python, you don’t have to deal with complex


syntax, you can refer to the below image:

F.Manna Introduction to Python 2019/2020


If you have to print ‘hello world’, you have to write above
three lines whereas in Python, just one line is sufficient to
print “hello world”. It’s that SIMPLE guys!
So the 10th reason lies in the simplicity of the code which
makes the best suit for beginners.

9. Portable & Extensible


The portable and extensible properties of Python allow you to
perform cross-language operations seamlessly. Python is
supported by most platforms present in the industry today
ranging from Windows to Linux to Macintosh, Solaris, Play
station, among others.
Python’s extensibility features allow you to integrate Java as
well as .NET components. You can also invoke C and C++
libraries.
Get Started With Python

8. Web Development

F.Manna Introduction to Python 2019/2020


Python has an
array of frameworks for developing websites. The popular
frameworks are Django, Flask, Pylons etc. Since these
frameworks are written in Python, its the core reason which
makes the code a lot faster and stable.
You can also perform web scraping where you can fetch details
from any other websites. You will also be impressed as many
websites such as Instagram, bit bucket, Pinterest are build on
these frameworks only.

7. Artificial Intelligence

AI is the next huge development in the tech world. You can


actually make a machine mimic the human brain which has the
power to think, analyze and make decisions.

F.Manna Introduction to Python 2019/2020


Furthermore, libraries such as Keras and TensorFlow bring
machine learning functionality into the mix. It gives the
ability to learn without being explicitly programmed. Also, we
have libraries such as openCv that helps computer vision or
image recognition.

6. Computer Graphics

Python is largely
used in small, large, online or offline projects. It is used
to build GUI and desktop applications. It uses ‘Tkinter‘
library to provide fast & easy way to create applications.
It is also used in game development where you can write the
logic of using a module ‘pygame’ which also runs on android
devices.

5. Testing Framework

F.Manna Introduction to Python 2019/2020


Python is great
for validating ideas or products for established companies.
Python has many built-in testing frameworks that covers
debugging & fastest workflows. There are a lot of tools and
modules to make things easier such as Selenium and Splinter.
It supports testing with cross-platform & cross-browser with
frameworks such as PyTest and Robot Framework. Testing is a
tedious task and Python is the booster for it, so every tester
should definitely go for it!

4. Big Data

F.Manna Introduction to Python 2019/2020


Python handles a lot of
hassles of data. It supports parallel computing where you can
use Python for Hadoop as well. In Python, you have a library
called “Pydoop” and you can write a MapReduce program in
Python and process data present in the HDFS cluster.
There are other libraries such as ‘Dask‘ and ‘Pyspark‘ for big
data processing. Therefore, Python is widely used for Big Data
where you can easily process it!

3. Scripting & Automation


Many people only knows that Python is a programming language,
but Python can also be used as Scripting language. In
scripting:

● The code is written in the form of scripts and get


executed
● Machine reads and interprets the code
● Error checking is done during Runtime

Once the code is checked, it can be used several times. So by


automation, you can automate certain tasks in a program.

2. Data Science

F.Manna Introduction to Python 2019/2020


Python is the leading
language of many data scientist. For years, academic scholars
and private researchers were using the MATLAB language for
scientific research but it all started to change with the
release of Python numerical engines such as ‘Numpy’ and
‘Pandas’.
Python also deals with the tabular, matrix as well as
statistical data and it even visualizes it with popular
libraries such as ‘Matplotlib’ and ‘Seaborn‘.

1. Python’s Popularity & High Salary


Python engineers have some of the highest salaries in the
industry. The average Python Developer salary in the United
States is approximately $116,028 per year.
Also, Python has a strong spike in popularity over the last
1year. Refer the below screenshot taken from Google Trends.

F.Manna Introduction to Python 2019/2020


Many of us stumble upon the same question, “as a beginner,
should I learn Python 3?” If you are seeking the answer too,
read this article, as I unravel what Python 3 has to offer.
Programming using Python 3 has become the next-gen skill to
acquire. No doubt, most entry level programmers are inclined
towards completing Python Programming Certification. With rich
features and vivid functionality to offer, Python 3 has taken
the programming community by storm.
I have covered the following topics to help kick-start your
journey to learn Python 3.

● What is Python 3?
● Why Learn Python 3?
● Features of Python 3
● Comparison: Python 2 vs Python 3
● Fundamentals of Python
● Your First Python 3 program – Check Prime Number

What is Python 3?
Python is a free open source, multi-purpose programming
language, created by Guido Van Rossum in 1991. Since Python’s
first release, the language has gone through many changes and
improvements. It was built as a successor to programming
language ABC. Python’s primary advantage was that it had the
capability to handle exceptions and interface with an
operating system named ‘Amoeba‘. With time Python language has
evolved and grown manifolds. It’s time to study Python 3
language in detail.

Why Learn Python 3?


Python has a range of advantages over other programming
languages. I have covered a few important advantages of
Python, below.

● Utility and applicability

Python supports the re-usability and flexibility of programs.


Python supports numerous modules, making easier to implement

F.Manna Introduction to Python 2019/2020


programs under domains like data analytics, machine learning,
artificial intelligence, deep learning, etc.

● Edge over other languages

When compared to other programming languages, Python is


reliable and has rich support from its community. It’s
interpreted nature adds to it being portable and time
efficient.

● Easy readability and debugging

Python follows clear structural specifications for writing its


code, making it easy to read and edit. It redefines the
cleanliness of code and doesn’t follow the traditional
programming syntax.

● Career path and Job opportunities

According to recent surveys, it was concluded that Python is


the most demanding programming language in the IT market. To
start learning Python, you may consider reading more about the
Python Institute’s PCAP certification and the career path to
being a master in Python.
Now that we have spoken about Python 3 features, let us scoot
towards a comparison between Python 3 and its predecessor
Python 2.

Comparison: Python 2 vs Python 3


After its release in 2008, Python 3 has evolved way more than
its predecessor Python 2. Answering whether Python 3 being
better than Python 2, is a no-brainer.

F.Manna Introduction to Python 2019/2020


I have described the key differences between Python 3 and
Python 2 below:

● Python 2 support will cease to exist by 2020 and Python 3


will be the inevitable future of the language.
● Most Python 3 libraries are developed to run specifically
with Python 3. Also, many of Python 2 libraries can’t be
used with Python 3.
● Python 3 has introduced Unicode support for text strings
as compared to ASCII in Python 2.
● Syntax to define print function has changed. Python 3
uses curly braces to print a statement.

For example, look at the difference between the print function


syntax for Python 2 and Python 3, as stated below.
Python 2:
1 print "Edureka Python
Courseware"
Python 3:
1 print ("Edureka Python
Courseware")

F.Manna Introduction to Python 2019/2020


The latest release of Python is Python 3.6.1. Few key features
from the latest release are given below:

● Improved numeric literals have been introduced


● String interpolation and formatting has been improved
● Secrets module for generating cryptographically secure
authentication tokens have been made available for use

We’ve studied the differences that Python has with its


predecessor. Now, it’s time to talk about the competitors of
Python 3.

Python 3 and its Competitors


Learning the basic differences between Python and the other
leading languages like Java, R, Go Lang would help garner
Python’s upper hand over others.

● Python 3 vs Java

It is easy and efficient to read Python code. Python also


comes bundled with a single line HTTP server setup capability.
Whereas Java is complex and it has higher compile time and
memory usage.

● Python 3 vs R

Python 3 is faster in the execution of shorter codes. R is a


programming language that supports the statistical analysis
and data mining. Hence it is a field-specific language. R has
limitations when it comes to developing web applications.

● Python 3 vs Go lang

Python 3 has wide support of packages that allow applicability


across different platforms. Go lang has its applications more
inclined towards system programming, cloud computing, and web
development. Henceforth Go Lang has field-specific
applicability.
According to 2019’s index for PYPL PopularitY Index, Python
has emerged as one of the most wanted languages in the forum

F.Manna Introduction to Python 2019/2020


of developers. With this study, a natural inclination towards
beginning to learn Python 3 has emerged among every
programming individual.
The graph below shows the top 8 most wanted programming
languages and their requirements in the IT market.

Having said that, let me shed some light on the valuable


features of Python 3 in detail.

Features of Python 3
Python 3 offers rich functionality making it the most
appropriate for solving real-life problems. I have written
down a few important features of Python, below:

Let us understand each of these features in detail.

F.Manna Introduction to Python 2019/2020


● Open source

Python is an open source language and is free for use.


Download the Python environment from the Python global webpage
– http://www.python.org.

● Platform independent

Python is portable and can be executed on any platform. Python


3 stores code as a byte code before it is interpreted on a
platform.

● Interpreted

Python code doesn’t need to be compiled. It is interpreted on


the machine, it has been executed on.

● Object-oriented and procedural both

Python has features of an object-oriented as well as a


procedural programming language. It supports the usability of
functions, classes, and objects. An object-oriented approach
strengthens the diverse application of Python in various
fields.

● Fast and Efficient

Python is fast to execute and run. It is efficient to develop


and maintain scripts in Python. Python’s code is easy to read
and it’s indentation approach keeps the code clean.

● Extensive libraries

Python supports the usability of an array of open source


libraries that can be used to implement technologies like
Machine learning, Data analytics, Web design, etc.
Few of Python’s packages have been described below:

○ Numpy

Used to facilitate array handling and complex matrix functions

F.Manna Introduction to Python 2019/2020



○ OpenCV

Used for real-time digital image processing


​ Pandas

Used for data analysis


​ Matplotlib

Used for visualization of data

○ ScikitLearn

Used to develop applications using Machine learning

○ Tkinter

Used to build GUI applications


Python has numerous array of applications. Let’s have a look
at the applications that you can build with Python 3.

Python 3 Applications
Few of the most important domains in which Python is used to
develop applications is described below:

● Web applications
● Game development
● 3D modeling
● Scientific and statistical analysis

A bunch of applications that run on Python 3 code is present


in the picture below:

F.Manna Introduction to Python 2019/2020


With this perennial reach of Python, it is natural to ask,
where should one begin learning Python 3 from? To answer that
question, I have represented a fundamental learning path for
learning Python 3 in the section below:

Fundamentals of Python
I have written down the fundamental topics that you should
study in order to get started with Python 3.

● Variables, operators, and expressions

Variables are used to store information in memory. It can then


be invoked later to perform calculations.

● Functions, conditionals, and loops

Loops and conditional statements are used to control the flow


of a program. A few examples are, while loop, for loop, Switch
statement, etc.

● File handling and I/O operations

File I/O operations are ways to fetch information from one


source and send it out to a different target.

F.Manna Introduction to Python 2019/2020


● Exception Handling

Exception handling is a functionality that allows us to


identify errors and debug programs.

● Python and OOPS

Object-oriented programming enables the use of classes and


objects. Concepts like Inheritance, polymorphism, abstraction,
and encapsulation build up the foundations to Python
programming.

● Interfaces

Reusable and interactive GUI applications can be built using


libraries of Python 3.

● Web development

Python’s libraries can be used to create REST APIs and


responsive WebUI applications.

● Testing

Python’s code should be tested to meet the business


requirement and functional test jobs can be integrated with
Selenium for automated testing.

● Python modules and toolkits

Python has a wide range of supported modules. We can perform


various functions and operations with varied functionalities
the modules offer.
Awesome! You have now learned the fundamentals of Python.
Let’s write a simple code and get familiar with scripting in
Python.

Your First Python 3 Program

F.Manna Introduction to Python 2019/2020


I have written a Python 3 code to find whether the number
entered is Prime. This example will make you a little familiar
with the syntax that a Python 3 program follows.
Program to check if the number entered is a Prime number or
not.
Property of prime number – Every number that is only divisible
by 1 and itself, is a prime number. Note the exclusivity of
division by 1 and the number itself.
1 Count = 0 # Count used as a iterating variable
2 numprime = int(input("Enter the number which needs to be
3 checked for being Prime or not : "))
4 for i in range(1, numprime):
5 if numprime % i == 0: # Checks if the number is
6 divisible by numbers
7 Count+=1 # increments the counter
8 ++i # increments the loop variable
9 if Count > 1: # Checks if the number of divisible events
1 are more than 1
0 print("Darn, the number", numprime, "is not a Prime
number")
else:
print("Voila! the number", numprime, "is a Prime
number")
Congratulations! Your first Python 3 program executes without
errors. The output of the program is given below:

I hope you were able to read through the article and get a
fair understanding to learn Python 3 programming. Python 3 is
like a Swiss knife of functionalities, that a programming
language can execute. As a result, get inspired and learn
Python 3 today!

F.Manna Introduction to Python 2019/2020


Python Programming Language is a high-level and interpreted
programming language which was created by Guido Van Rossum in
1989. It was first released in 1991, which results in a great
general purpose language capable of creating anything from
desktop software to web applications and frameworks.
For those of you familiar with Java or C++, Python will break
the mold you have built for a typical programming language.
Prepare to fall in love, with Python!
In this blog, we will learn Python Programming language in the
following sequence:

1. Why Learn Python Programming?


2. Python Installation
3. Python Fundamentals
3.1 Datatypes
3.2 Flow Control
3.3 Functions
4. File Handling
5. Object & Class

Why Learn Python Programming?


Python is a high-level dynamic programming language. It is
quite easy to learn and provides powerful typing. Python code
has a very ‘natural’ style to it, in that it is easy to read
and understand (thanks to the lack of semicolons and braces).
Python programming language runs on any platform, ranging from
Windows to Linux to Macintosh, Solaris etc.
The simplicity of Python is what it makes so popular. The
following gives a highlight of its aesthetics:

● Highly readable language


● Clean visual layout
● Less syntactic exceptions
● Superior string manipulation
● Elegant and dynamic typing
● Interpreted nature
● Ideal for scripting and rapid application
● Fit for many platforms

F.Manna Introduction to Python 2019/2020


Wait! Python can do more.
It is a very popular language in multiple domains like
Automation, Big Data, AI etc. You can refer to this entire
blog on top 10 reasons to learn python.
You will also be impressed as it used by the vast multitude of
companies around the globe.

You may go through the webinar recording of Python Programming


Language where our Python training expert has explained the
topics in a detailed manner with examples that will help you
to understand Python Programming language better.

Learn Python Programming | Python Programming – Step by Step |


Edureka

Python Installation
Let us now move on to installing Python on a Windows systems.

1. Go to the the link: https://www.python.org/downloads/ and


install the latest version on your machines.

F.Manna Introduction to Python 2019/2020


Figure: Downloading Python Programming Language
2. Download and install PyCharm IDE.

Figure: Downloading PyCharm


PyCharm is an Integrated Development Environment (IDE) used in
computer programming, specifically for the Python programming
language. It provides code analysis, a graphical debugger, an
integrated unit tester, integration with version control
systems (VCSes), and supports web development with Django.

F.Manna Introduction to Python 2019/2020


Python Fundamentals
The following are the five fundamentals required to master
Python:

1. Datatypes
2. Flow Control
3. Functions
4. File Handling
5. Object & Class

Figure: Python Programming Language- Fundamentals

Datatypes
All data values in Python are represented by objects and each
object or value has a datatype.

Figure: Python Programming Language – Datatype Features

F.Manna Introduction to Python 2019/2020


There are eight native datatypes in Python.

1. Boolean
2. Numbers
3. Strings
4. Bytes & Byte Arrays
5. Lists
6. Tuples
7. Sets
8. Dictionaries

The following image will give a description for the same.

Figure: Python Programming Language – Native Datatypes


Let us look at how to implement these data types in Python.

F.Manna Introduction to Python 2019/2020


1 #Boolean
2 number = [1,2,3,4,5]
3 boolean = 3 in number
4 print(boolean)
5
6 #Numbers
7 num1 = 5**3
8 num2 = 32//3
9 num3 = 32/3
1 print('num1 is',num1)
0 print('num2 is',num2)
1 print('num3 is',num3)
1
1 #Strings
2 str1 = "Welcome"
1 str2 = " to Edureka's Python Programming Blog"
3 str3 = str1 + str2
1 print('str3 is',str3)
4 print(str3[0:10])
1 print(str3[-5:])
5 print(str3[:-5])
1
6 #Lists
1 countries = ['India', 'Australia', 'United States',
7 'Canada', 'Singapore']
1 print(len(countries))
8 print(countries)
1 countries.append('Brazil')
9 print(countries)
2 countries.insert(2, 'United Kingdom')
0 print(countries)
2
1 #Tuples
2 sports_tuple = ('Cricket', 'Basketball', 'Football')
2 sports_list = list(sports_tuple)
2 sports_list.append('Baseball')
3 print(sports_list)
2 print(sports_tuple)

F.Manna Introduction to Python 2019/2020


4
2 #Dictionary
5 #Indian Government
2 Government = {'Legislature':'Parliament', 'Executive':'PM
6 & Cabinet', 'Judiciary':'Supreme Court'}
2 print('Indian Government has ',Government)
7 #Modifying for USA
2 Government['Legislature']='Congress'
8 Government['Executive']='President & Cabinet'
2 print('USA Government has ',Government)
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4

F.Manna Introduction to Python 2019/2020


3
4
4
4
5
4
6
The output of the above code is as follows:
True

num1 is 125
num2 is 10
num3 is 10.666666666666666

str3 is Welcome to Edureka's Python Programming Blog


Welcome to
Blog
Welcome to Edureka's Python Programming

5
['India', 'Australia', 'United States', 'Canada', 'Singapore']
['India', 'Australia', 'United States', 'Canada', 'Singapore',
'Brazil']
['India', 'Australia', 'United Kingdom', 'United States',
'Canada', 'Singapore', 'Brazil']

['Cricket', 'Basketball', 'Football', 'Baseball']


('Cricket', 'Basketball', 'Football')

Indian Government has {'Legislature': 'Parliament',


'Judiciary': 'Supreme Court', 'Executive': 'PM & Cabinet'}
USA Government has {'Legislature': 'Congress', 'Judiciary':
'Supreme Court', 'Executive': 'President & Cabinet'}

1. Why use Arrays in Python?


2. What is an Array?
3. Is Python list same as an Array?
4. Creating an Array

F.Manna Introduction to Python 2019/2020


5. Accessing an Element
6. Basic Array Operations
○ Adding/ Changing elements of an Array
○ Concatenation
○ Deleting / Removing elements from an Array
○ Looping through an array
○ Slicing

You may go through the webinar recording of Python Arrays


where our Python training expert has explained the topics in a
detailed manner with examples that will help you to understand
all concepts related to Python Arrays.

Arrays In Python | Python Array Operations | Edureka


Why use Arrays in Python?
A combination of Arrays, together with Python could save you a
lot of time. As mentioned earlier, arrays help you reduce the
overall size of your code, while Python helps you get rid of
problematic syntax, unlike other languages.
For example: If you had to store integers from 1-100, you
won’t be able to remember 100 variable names explicitly,
therefore, you can save them easily using an array.

Now that you are aware of the importance of arrays in Python,


let’s study more about it in detail.

F.Manna Introduction to Python 2019/2020


What is an Array?
An array is basically a data structure which can hold more
than one value at a time. It is a collection or ordered series
of elements of the same type.
Example:
1 a=arr.array('d',[1.2,
1.3,2.3])
We can loop through the array items easily and fetch the
required values by just specifying the index number. Arrays
are mutable(changeable) as well, therefore, you can perform
various manipulations as required.
Now, there is always a question that comes up to our mind –

Is Python list same as an Array?


The ‘array’ data structure in core python is not very
efficient or reliable. Therefore, when we talk about python
arrays, we usually mean python lists.
However, python does provide Numpy Arrays which are a grid of
values used in Data Science. You can look into Numpy Arrays vs
Lists to know more.

Creating an Array:
Arrays in Python can be created after importing the array
module as follows –
→ import array as arr
The array(data type, value list) function takes two
parameters, the first being the data type of the value to be
stored and the second is the value list. The data type can be
anything such as int, float, double, etc. Please make a note
that arr is the alias name and is for ease of use. You can
import without alias as well. There is another way to import
the array module which is –
→ from array import *
This means you want to import all functions from the array
module.
The following syntax is used to create an array.

F.Manna Introduction to Python 2019/2020


Syntax:
1 a=arr.array(data type,value list) #when you
import using arr alias
OR
1 a=array(data type,value list)
#when you import using *
Example: a=arr.array( ‘d’ , [1.1 , 2.1 ,3.1] )
Here, the first parameter is ‘d’ which is a data type i.e.
float and the values are specified as the next parameter.
Note:
All values specified are of the type float. We cannot specify
the values of different data types to a single array.
The following table shows you the various data types and their
codes.
Type code Python Data Type Byte size

i int 2

I int 2

u unicode character 2

h int 2

H int 2

l int 4

L int 4

f float 4

d float 8

Accessing array elements :

To access array elements, you need to specify the index


values. Indexing starts at 0 and not from 1. Hence, the index
number is always 1 less than the length of the array.
Syntax:
Array_name[index value]

F.Manna Introduction to Python 2019/2020


Example:
1 a=arr.array( 'd', [1.1 ,
2 2.1 ,3.1] )
a[1]
Output –
2.1
The output returned is the value, present at the second place
in our array which is 2.1.
Let us have a look at some of the basic array operations now.

Basic array operations :


There are many operations that can be performed on arrays
which are as follows –

Finding the Length of an Array


Length of an array is the number of elements that are actually
present in an array. You can make use of len() function to
achieve this. The len() function returns an integer value that
is equal to the number of elements present in that array.
Syntax:
→ len(array_name)
Example:
1 a=arr.array('d', [1.1 ,
2 2.1 ,3.1] )
len(a)

F.Manna Introduction to Python 2019/2020


Output – 3
This returns a value of 3 which is equal to the number of
array elements.

Adding/ Changing elements of an Array:


We can add value to an array by using the append(), extend()
and the insert (i,x) functions.
The append() function is used when we need to add a single
element at the end of the array.
Example:
1 a=arr.array('d', [1.1 ,
2 2.1 ,3.1] )
3 a.append(3.4)
print(a)
Output –
array(‘d’, [1.1, 2.1, 3.1, 3.4])
The resultant array is the actual array with the new value
added at the end of it. To add more than one element, you can
use the extend() function. This function takes a list of
elements as its parameter. The contents of this list are the
elements to be added to the array.
Example:
1 a=arr.array('d', [1.1 ,
2 2.1 ,3.1] )
3 a.extend([4.5,6.3,6.8])
print(a)
Output –
array(‘d’, [1.1, 2.1, 3.1, 4.5, 6.3, 6.8])
The resulting array will contain all the 3 new elements added
to the end of the array.
However, when you need to add a specific element at a
particular position in the array, the insert(i,x) function can
be used. This function inserts the element at the respective
index in the array. It takes 2 parameters where the first
parameter is the index where the element needs to be inserted
and the second is the value.
Example:

F.Manna Introduction to Python 2019/2020


1 a=arr.array('d', [1.1 ,
2 2.1 ,3.1] )
3 a.insert(2,3.8)
print(a)
Output –
array(‘d’, [1.1, 2.1, 3.8, 3.1])
The resulting array contains the value 3.8 at the 3rd position
in the array.
Arrays can be merged as well by performing array
concatenation.

Array Concatenation :
Any two arrays can be concatenated using the + symbol.
Example:
1 a=arr.array('d',[1.1 , 2.1
2 ,3.1,2.6,7.8])
3 b=arr.array('d',[3.7,8.6])
4 c=arr.array('d')
5 c=a+b
print("Array c = ",c)
Output –
Array c= array(‘d’, [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
The resulting array c contains concatenated elements of arrays
a and b.
Now, let us see how you can remove or delete items from an
array.

Removing/ Deleting elements of an array:


Array elements can be removed using pop() or remove() method.
The difference between these two functions is that the former
returns the deleted value whereas the latter does not.
The pop() function takes either no parameter or the index
value as its parameter. When no parameter is given, this
function pops() the last element and returns it. When you
explicitly supply the index value, the pop() function pops the
required elements and returns it.
Example:

F.Manna Introduction to Python 2019/2020


1 a=arr.array('d', [1.1, 2.2, 3.8, 3.1,
2 3.7, 1.2, 4.6])
3 print(a.pop())
print(a.pop(3))
Output –
4.6
3.1
The first pop() function removes the last value 4.6 and
returns the same while the second one pops the value at the
4th position which is 3.1 and returns the same.
The remove() function, on the other hand, is used to remove
the value where we do not need the removed value to be
returned. This function takes the element value itself as the
parameter. If you give the index value in the parameter slot,
it will throw an error.
Example:
1 a=arr.array('d',[1.1 ,
2 2.1 ,3.1])
3 a.remove(1.1)
print(a)
Output –
array(‘d’, [2.1,3.1])
The output is an array containing all elements except 1.1.
When you want a specific range of values from an array, you
can slice the array to return the same, as follows.

Slicing an array :
An array can be sliced using the : symbol. This returns a
range of elements that we have specified by the index numbers.
Example:
1 a=arr.array('d',[1.1 , 2.1
2 ,3.1,2.6,7.8])
print(a[0:3])
Output –
array(‘d’, [1.1, 2.1, 3.1])

F.Manna Introduction to Python 2019/2020


The result will be elements present at 1st, 2nd and 3rd
position in the array.

Looping through an array:


Using the for loop, we can loop through an array.
Example:
1 a=arr.array('d', [1.1, 2.2, 3.8, 3.1,
2 3.7, 1.2, 4.6])
3 print("All values")
4 for x in a:
5 print(x)
6 print("specific values")
7 for x in a[1:3]:
print(x)
Output –
All values
1.1
2.2
3.8
3.1
3.7
1.2
4.6
specific values
2.2
3.8

The above output shows the result using for loop. When we use
for loop without any specific parameters, the result contains
all the elements of the array given one at a time. In the
second for loop, the result contains only the elements that
are specified using the index values. Please note that the
result does not contain the value at index number 3.
.

What are Sets in Python and How to use them?

F.Manna Introduction to Python 2019/2020


Data storage is something that is necessary for every domain
in today’s world. Python provides different types of data
structures to organize your data and these data structures are
an essential part of Python Certification Training. Among all
data structures available in Python, some are mutable and some
are immutable. In this article, I will be discussing one of
these i.e sets. Sets in Python are data structures that are
mutable, iterable and unordered. Here is a quick walkthrough
of all that has been covered further.
What is Set in Python?
When to use sets in Python?
How do you create a set?
Set Operations

● Finding the length of a Set


● Accessing Set elements
● Adding elements to a Set
● Removing Set elements
● Union of Sets
● Intersection of Sets
● Difference of Sets

What are Frozen Sets?

● How to Create Frozen Sets?


● Accessing Frozen Set elements

Let’s get started. :-)

What is Set in Python?


A set is basically a data type consisting of a collection of
unordered elements. These elements can be on any data types as
sets, unlike arrays, are not type specific. Sets are
mutable(changeable) and do not have repeated copies of
elements. The values of a set are unindexed, therefore,
indexing operations cannot be performed on sets.
Example:
1 My_Set={1,'s'

F.Manna Introduction to Python 2019/2020


2 ,7.8}
print(My_Set)
Output: {‘s’, 1, 7.8}
The output shows all the elements present My_Set.
Note: A set as a whole is mutable but the elements of a set
are not.
Now that you know what are sets in Python, let’s move ahead
and understand when to use sets.

When to use sets in Python?


Sets in Python are used when-

● The order of data does not matter


● You do not need any repetitions in the data elements
● You need to perform mathematical operations such as
union, intersection, etc

Now let us move ahead and see how to create sets in Python.

How do you create a set in Python?


Sets in Python can be created in two ways-

● enclosing elements within curly braces


● by using the set() function

1.Using curly braces:


Sets in Python are created using curly braces({}).
Example:
1 My_Set={1,'s'
2 ,7.8}
print(My_Set)
Output: {‘s’, 1, 7.8}
As you can see, My_Set has been created.

2. Using set() function


Sets in Python can be created using the set() function.
Example:

F.Manna Introduction to Python 2019/2020


1 a=set({1,'b',
2 6.9})
print(a)
Output: {1, ‘b’, 6.9}
You can also create an empty set using the same function.
Example:
1 Empty_Set=s
2 et()
print(Empty
_Set)
Output: set()
The above output shows an empty set named Empty_Set has been
created.
You can add elements to this empty set. I will be covering
that in the following topics.

Set Operations
A number of operations can be performed on sets such as adding
elements, deleting elements, finding the length of a set, etc.
To know what all methods can be used on sets, you can use the
dir() function.
Example:
1 My_Set={1,'s'
2 ,7.8}
dir(My_Set)
Output:
[‘__and__’,’__class__’,’__contains__’,’__delattr__’,’__dir__’,
’__doc__’,’__eq__’,’__format__’,’__ge__’,’__getattribute__’,
‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’,
‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’,
‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’,
‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’,
‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’,
‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’,
‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’,
‘difference’, ‘difference_update’, ‘discard’, ‘intersection’,

F.Manna Introduction to Python 2019/2020


‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’,
‘pop’, ‘remove’, ‘symmetric_difference’,
‘symmetric_difference_update’, ‘union’, ‘update’]
The output shows all the methods that can be used on sets. I
will be demonstrating a few of them futher in this article.

Finding the Length of a Set


To find the length of a set in Python, you can use the len()
function. This function takes the name of the set as a
parameter and returns an integer value which is equal to the
number of elements present in the set.
Example:
1 My_Set={1,'s'
2 ,7.8}
3
len(My_Set)
Output: 3
As you can see in the above output, 3 has been returned which
equal to the number of elements present in My_Set. Now, these
elements can be accessed as well, which is shown below.

Accessing Elements of a Set


Set elements cannot be accessed using the index numbers
because, as specified before, elements of a set are not
indexed. Therefore, when you want to access elements of a set,
you can loop through it and access its elements.
Example:
1 My_Set={1,'s'
2 ,7.8}
3 for x in
My_Set:
print(x)
Output:
s
1
7.8

F.Manna Introduction to Python 2019/2020


As you can see in the output, the order is different than the
order of elements supplied to the set. This is because the
elements are not ordered.

Adding elements to a Set:


Elements can be added to a set using two functions, the add()
and the update() function.
The add() function adds one element to the existing set as
shown below:
Example:
1 My_Set={1,'s'
2 ,7.8}
3 My_Set.add(3)
My_Set
Output: {1, 3, 7.8, ‘s’}
The update() function is used when you want to add more than
one element to the existing set.
Example:
1 My_Set={1,'s',7.8}
2 My_Set.update([2,4.6
3 ,1,'r'])
My_Set
Output: {1, 2, 4.6, 7.8, ‘r’, ‘s’}

As you can see in the above output, the update() function is


taking a list of 4 values and all values except 1 are added to
My_Set. This is because 1 is already present in the set and
therefore, it cannot be added again.

Removing Elements of a Set


To remove elements from a set, you can use either the
remove(), discard() and the pop() functions.
The remove() function takes one parameter which is the item to
be removed from the set.
Example:

F.Manna Introduction to Python 2019/2020


1 My_Set={1, 2, 4.6, 7.8,
2 'r', 's'}
3 My_Set.remove(2)
print(My_Set)
Output: {1, 4.6, 7.8, ‘r’, ‘s’}
As you can see, 2 has been removed from the set using the
remove() function. In case you specify some element as a
parameter to remove() that does not exist in the set, it will
throw an error.
Now, if you want to remove some element from the set, and if
you are not sure whether that element is actually present in
the set or not, you can use the discard() function. This
function will take the element to be removed from the set as a
parameter but in case the element is not present, it does not
throw an error.
Example:
1 My_Set={1, 2, 4.6, 7.8,
2 'r', 's'}
3 My_Set.discard(4.6)
4 My_Set.discard('i')
print(My_Set)
Output: {1, 2, 7.8, ‘r’, ‘s’}
The above output shows that 4.6 has been removed from My_Set
but discard() has not thrown an error when I used
My_Set.discard(‘i’) even though ‘i’ is not present in my set.
The pop() function also removes set elements, but since a set
is unordered, you will not know which element has been
removed.
Example:
1 My_Set={1, 2, 4.6, 7.8,
2 'r', 's'}
3 My_Set.pop()
print(My_Set)
Output: {2, 4.6, 7.8, ‘r’, ‘s’}
The output shows that, using pop() some random element has
been removed, which in this case is 1.

F.Manna Introduction to Python 2019/2020


Now, in case you want to delete all elements present in a set,
you can use the clear() method.
Example:
1 My_Set={1, 2, 4.6, 7.8,
2 'r', 's'}
3 My_Set.clear()
print(My_Set)
Output: set()
As you can see in the above output, My_Set is an empty set.
In case you want to completely delete the set, you can use the
del keyword.
Example:
1 My_Set={1, 2, 4.6, 7.8,
2 'r', 's'}
3 del My_Set
print(My_Set)
When you run the above code, it will throw an error because
My_Set is deleted.
You can also perform the various mathematical operations on a
set such as union, intersection, difference, etc which is
discussed below.

Union of Sets
Union of sets refers to the concatenation of two or more sets
into a single set by adding all unique elements present in
both sets. This can be done in two ways:

● Using pipeline
● Using union() function

Using pipeline symbol:


Two sets can be concatenated using the | symbol as follows:

Example:

F.Manna Introduction to Python 2019/2020


1 a={1, 2, 4.6, 7.8,
2 'r', 's'}
3 b={2,5,'d','abc'}
4 c=a|b
print(a|b)
Output:{1, 2, 4.6, 5, 7.8, ‘r’, ‘abc’, ‘s’, ‘d’}
As you can see, in the above output, a union of set a and set
b is stored in a new set c. You can concatenate more than two
sets as well using | symbol.
Example:
1 a={1, 2, 4.6, 7.8,
2 'r', 's'}
3 b={2,5,'d','abc'}
4 c={2,3,4,5}
5 d=a|b|c
print(d)
Output:
{1, 2, 3, 4, 4.6, 5, 7.8, 'abc', 'd', 'r', 's'}
Using the union() method:
To cancatenate two or more sets, you can use the union()
method as follows:
Example:
1 a={1, 2, 4.6, 7.8, 'r',
2 's'}
3 b={2,5,'d','abc'}
4 c={'m',23,76,4.7}
5 print("Set a U b =
",a.union(b))
print("Set a U b U c =
",a.union(b,c))
Output:
Set a U b = {1, 2, 4.6, 5, 7.8, ‘r’, ‘abc’, ‘s’, ‘d’}
Set a U b U c = {1, 2, 4.6, 5, 4.7, 7.8, ‘r’, 76, 23, ‘abc’,
‘m’, ‘s’, ‘d’}
The above output shows that the d is a union of sets a, b and
c.

F.Manna Introduction to Python 2019/2020


Intersection of Sets
The intersection of two or more sets is a new set consisting
of only the common elements present in those sets.
This can be done in two ways:

● Using ‘&’ symbol


● Using intersection() function

Using ‘&’ symbol:


You can determine the intersection of two or more sets using
the ‘&’ symbol as follows:
Example:
1 a={1, 2,5, 4.6, 7.8,
2 'r', 's'}
3 b={2,5,'d','abc'}
4 c={2,3,4,}
5 print(a&b)
print(a&b&c)
Output:
{2, 5}
{2}

The above output shows the union of sets a,b and c.


Using intersection() function:
You can determine the intersection of two or more sets using
the intersection() function as follows:
Example:
1 a={1, 2,5, 4.6, 7.8, 'r', 's'}
2 b={2,5,'d','abc'}
3 c={2,3,4}
4 print("Set a intersection b =
5 ",a.intersection(b))
print("Set a intersection b intersection c =
",a.intersection(b,c))
Output:
Set a intersection b = {2, 5}
F.Manna Introduction to Python 2019/2020
Set a intersection b intersection c = {2}
The above output shows the intersection of sets a, b and c
using intersection().

Difference of Sets:
The difference of sets produces a new set consisting of
elements that are present only in one of those sets. This
means that all elements except the common elements of those
sets will be returned.
This can be done in two ways:

● Using the ‘-‘ symbol


● Using difference() function

Using the ‘-‘ symbol:


To find the difference of two sets using ‘-‘ symbol, you can
do as follows:
Example:
1 a={1, 2,5, 4.6, 7.8,
2 'r', 's'}
3 b={2,5,'d','abc'}
4 c={2,3,4}
print(a-b-c)
Output: {1, 4.6, 7.8, ‘r’, ‘s’}
The output consists of all elements of set ‘a’ except those
that are present in ‘b’ and ‘c’.

Using the difference() function:


The difference of sets can be determined using the built-in
difference() function as follows:
Example:
1 a={1, 2,5, 4.6, 7.8, 'r', 's'}
2 b={2,5,'d','abc'}
3 c={2,3,4}
4 print("Set a - b =
5 ",a.difference(b))
print("Set a - b - c =

F.Manna Introduction to Python 2019/2020


",a.difference(b,c))
Output:
Set a – b = {1, 4.6, 7.8, ‘r’, ‘s’}
Set a – b – c = {1, 4.6, 7.8, ‘r’, ‘s’}
The above output is the result for difference using the
difference() function.
Now what if you do not want to change the elements of your set
at all, you can make use of frozen sets which is discussed
below.

What is a frozen set?


A frozen set in Python is a set whose values cannot be
modified. This means that it is immutable unlike a normal set
which I have discussed previously. Frozen sets help serve as a
key in dictionary key-value pairs.

How to create frozen sets?


Frozen sets can be obtained using the frozenset() method. This
function takes any iterable items and converts it to
immutable.
Example:
1 a={1, 2,5, 4.6, 7.8,
2 'r', 's'}
3 b=frozenset(a)
print(b)
Output: frozenset({1, 2, 4.6, 5, 7.8, ‘r’, ‘s’})
The above output consists of set b which is a frozen version
of set a.

Accessing Elements of a Frozen Set


Elements of a frozen set can be accessed by looping through it
as follows:
Example:
1 b=frozenset([1, 2, 4.6, 5,
2 7.8, 'r', 's'])
3 for x in b:

F.Manna Introduction to Python 2019/2020


print(x)
Output:
1
2
4.6
5
7.8
s
The above output shows that using the for loop, all elements
of the frozen set b have been returned one after the other.
Frozen sets are immutable, therefore, you cannot perform
operations such as add(), remove(), update(), etc.

Loops In Python: Why Should You Use One?

Dealing with redundant code and repetitive commands can be a


nightmare for any programmer. Python makes use of loops,
control and conditional statements to overcome this hurdle.
This article will help you understand loops in python and all
the terminologies that surround loops.

1. What are Loops in Python?


2. What is for loop and while loop?
3. Loop control statements

If you want to master the concepts of loops in Python by


Certified Python Expert, you can check out the below video
where these topics are covered on a broader gauge

What Are Loops In Python?


Loops in Python allow us to execute a group of statements
several times. Lets take an example to understand why loops
are used in python.
Suppose, you are a software developer and you are required to
provide a software module for all the employees in your
office. So, you must print the details of the payroll of each

F.Manna Introduction to Python 2019/2020


employee separately. Printing the details of all the employees
will be a tiresome task, instead you can use the logic for
calculating the details and keep on iterating the same logic
statement. This will save your time and make your code
efficient.
The illustration below is the flowchart for a loop:

The execution starts and checks if the condition is True or


False. A condition could be any logic that we want to test in
our program. If its true it will execute the body of the loop
and if its false, It will exit the loop.

Conditional Statements
Conditional statements in Python support the usual logical
conditions from mathematics.
For example:

● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b

F.Manna Introduction to Python 2019/2020


● Greater than: a > b
● Greater than or equal to : a >= b

These statements can be used in several ways, most commonly in


if statement.
Let us understand the concept of if statements.

‘if’ Statement
An if statement is written using the ‘if’ keyword, The syntax
is the keyword ‘if’ followed with the condition.
Below is the flowchart of the if statement:

As you can see, the execution encounters the if condition and


acts accordingly. If it is true, it executes the body and if
it is false, it exits the if statement.
1 a = 10
2 b = 20
3 if a < b :
4 print(" b is
greater")

F.Manna Introduction to Python 2019/2020


Above code snippet illustrates the basic example of how a
condition is used in the if statement.
When it reaches the if statement it checks whether the value
of b is greater or not. If b is greater, it prints “b is
greater“. Now if the condition is false, it exits the if
statement and executes the next statement. In order to print
the next statement, we can add a keyword ‘else’ for the
alternate result that we wish to execute. Lets move to the
else statement for better understanding.

‘else’ Statement
The else keyword catches anything that is not caught by the
preceding conditions. When the condition is false for the if
statement, the execution will move to the else statement.
Lets take a look at the flowchart of else statement below:

As you can see, when the if statement was false the execution
moved to the body of else. Lets understand this with an
example.

F.Manna Introduction to Python 2019/2020


1 a = 10
2 b = 20
3 if a < b :
4 print(" b is
5 greater")
6 else:
print(" a is
greater")
The first condition is not true, so we will move to the next
statement which is the else statement and print “b is
greater”.
In case we have more conditions to test, we can also use elif
statement.

‘elif’ Statement
elif statement in layman term means “try this condition
instead”. Rest of the conditions can be used by using the elif
keyword.
Let us look at the code below:
1 a = 10
2 b = 20
3 if a < b :
4 print(" b is
5 greater")
6 elif a == b :
7 print(" a is equal
8 to b ")
else:
print(" a is
greater")
“When the if statement is not true, the execution will move to
the elif statement and check if it holds true. And in the end
the else statement if and elif are false.
Since a != b, “b is greater” will get printed here.
Note: python relies on indentation, other programming
languages use curly brackets for loops.

F.Manna Introduction to Python 2019/2020


What Is ‘for’ Loop and ‘while’ Loop

A for loop is used to execute statements, once for each item


in the sequence. The sequence could be a list, a Dictionary, a
set or a string.
A for loop has two parts, the block where the iteration
statement is specified and then there is the body which is
executed once every iteration.
Unlike while loop, we already specify the number of times the
iterations must execute. for loop syntax takes three fields, a
Boolean condition, initial value of the counting variable and
the increment of the counting variable.
Look at the example to understand this better:
1 days = ["sun" , "mon" , "tue" , "wed",
2 "thu", "fri", "sat"]
3 for x in days:
print(x)

F.Manna Introduction to Python 2019/2020


Here we were iterating through the list. To iterate through a
code for a specified number of times we could use the range()
function.

Range Function
Range function requires a specific sequence of numbers. It
starts at 0 and then the value increments by 1 until the
specified number is reached.
For example:
1 for x in
2 range(3)
print(x)
It will print from 0-2, the output will look like
0
1
2
Note: the range (3) does not mean the values from 0-3 but the
values from 0-2.
Below is another example using the condition statements:

F.Manna Introduction to Python 2019/2020


1 num =
2 int(input("number"
3 ))
4
5 factorial = 1
6 if num < 0 :
7 print(" invalid
8 input")
9 elif num == 0:
1 print(" factorial
0 is 1")
1 else:
1 for i in range( 1
, num+1):
factorial =
factorial * i
print(factorial)

‘while’ Loop
The ‘while’ loop executes the set of statements as long as the
condition is true.
It consists of a condition block and the body with the set of
statements, It will keep on executing the statement until the
condition becomes false. There is no guarantee to see how long
the loop will keep iterating.
Following is the flowchart for while loop:

F.Manna Introduction to Python 2019/2020


To understand this let’s take a look at the example below.
Example:
1 i = 1
2 while i <
3 6 :
4
print(i)
i +=
1
Output: it will print 1 2 3 4 5
The execution will continue until value of i reaches 6.
The while loop requires the relevant variable to be ready,
here we need an indexing variable, which could be any value.
Lets consider another example:

F.Manna Introduction to Python 2019/2020


1 num = int(input("enter
2 number"))
3 while num > 0:
4 if num < 13:
5 print("the number is
6 too large")
7 break
8 elif num < 13:
9 print("number too
1 small")
0 break
1 elif num == 13:
1 print("exit:
congratulations")
break
Note: remember to iterate i or the loop will continue forever.
if there is no control statement here, loop will continue
forever. try removing the break statement and run again.
We might need to control the flow of the execution to favor a
few conditions in some cases, so let’s understand the loop
control statements in Python.

Loop Control Statements

F.Manna Introduction to Python 2019/2020


To control the flow of the loop or to alter the execution
based on a few specified conditions we use the loop control
statements discussed below. The control statements are used to
alter the execution based on the conditions.
In Python we have three control statements:

Break
Break statement is used to terminate the execution of the loop
containing it. As soon as the loop comes across a break
statement, the loop terminates and the execution transfers to
the next statement following the loop.

As you can see the execution moves to the statement below the
loop, when the break returns true.
Let us understand this better with an example:
1 for val in
2 "string" :
3 if val ==
4 "i":
5 break

F.Manna Introduction to Python 2019/2020


print(val)
print("the
end")

Output:
s
t
r
The end
Here the execution will stop as soon as the string “i” is
encountered in the string. And then the execution will jump to
the next statement.

Continue
The continue statement is used to skip the rest of the code in
the loop for the current iteration. It does not terminate the
loop like the break statement and continues with the remaining
iterations.

F.Manna Introduction to Python 2019/2020


When continue is encountered it only skips the remaining loop
for that iteration only.
For example:
1 for val in
2 "string" :
3 if val ==
4 "i":
5
continue

print(val)
print("the
end")
Output:
s
t
r
n
g

F.Manna Introduction to Python 2019/2020


the end

It will skip the string “i” in the output and the rest of the
iterations will still execute. All letters in the string
except “i” will be printed.

Pass
The pass statement is a null operation. It basically means
that the statement is required syntactically but you do not
wish to execute any command or code.
Take a look at the code below:
1 for val in
2 "please":
3 if val == "a":
4 pass
5 print("pass
block")
print(val)
Output:
p
l
e
pass block
a
s
e
The execution will not be affected and it will just print the
pass block once it encounters the “a” string. And the
execution will start at “a” and execute the rest of the
remaining iterations.

‘while’ Loop Using The Break Statement


Lets understand how we use a while loop using a break
statement with an example below:

F.Manna Introduction to Python 2019/2020


1 i = 1
2 while i <
3 6 :
4
5 print(i)
6 if i
== 3 :

break
i
+= 1
Output: it will print 1 2
The execution will be terminated when the iteration comes to 3
and the next statement will be executed.

Using Continue Statement


Let’s take an example for continue statement in a while loop:
1 i = 1
2 while i <
3 6:
4
5 print(i)
6 if i ==
3 :

continue
i +=
1
Output: 1 2 4 5
Here the execution will be skipped, and the rest of the
iterations will be executed.

Nested Loops
Python allows us to use one loop inside another loop,
Following are a few examples

Nested for loop

F.Manna Introduction to Python 2019/2020


An example to use a for loop inside another for loop:
1 for i in range(1
2 , 6):
3 for j in
4 range(i):
print( i ,
end="")
print()
Output:
1 1
2 2 2
3 3 3
4 3
4 4
4 4

Nested ‘while’ loop


Below is the basic syntax to use a nested while loop:
1 while
2 expression:
3 while
4 expression:
statement(s)
statement(s)
Example:
An example to show a nested while and for loop:
1 travelling = input("yes or
2 no")
3 while travelling == "yes" :
4 num = int(input("number
5 of people"))
6 for num in range( 1 , num+1):
7 name = input("name")
8 age = input("age")
9 gender = input("gender")
1 print(name)

F.Manna Introduction to Python 2019/2020


0 print(age)
1 print(gender)
1 travelling = input("oops
missed someone")
In this program we have used a while loop and inside the body
of the while loop, we have incorporated a for loop.

Python Functions

Introduction To Python Functions


In today’s fast-paced IT world, it is always an advantage to
have an edge over the others in terms of in-depth knowledge of
a certain technology. Python is a widely used language and
provides ‘n’ number of opportunities to enthusiastic learners.
Learning to use the functions in Python in the right way is a
notable skill for any Python Developer.
In this Python Functions blog, the goal is to get you the
expertise required to get started and work with functions
using Python. I will be covering the following topics in this
Python Functions blog:

● Why Need Python Functions?


● What are Python Functions?
● Types of Python Functions
● Built-in Functions in Python
● Python Recursive Function
● Python Lambda Function
● User-defined Functions in Python

Python Functions Tutorial | Working With Functions In Python


| Python Training | Edureka
Let us begin this Python Functions blog by first checking out
why we need Python Functions.

Why We Need Python Functions?

F.Manna Introduction to Python 2019/2020


Functions manage the inputs and outputs in computer programs.
Programming languages are designed to work on data and
functions are an effective way to manage and transform this
data.
The modifications are generally done to drive outcomes like
performing tasks and finding results. And, the set of
operations or instructions required to do so comes from
logically functional blocks of code that can be reused
independently from the main program.
In fact, the main code is also a function, just a very
important one at that. Every other function is logically
aligned and maintained to functionally execute from your main
code. But, if the function has not been defined previously,
you’ll just have to define one yourself before using it. This
is because the definition lists the steps of its operation.

Would you rather write a single piece of code 10 times or just


once and use it 10 times?
So, functions are nothing but tasks that a user wants to
perform. But, defining it once with a name will let you reuse
that functionality without making your main programs look too
scary. This drastically reduces lines of code and even make
debugging easier.
We’ll be getting into that shortly, but the first reason
behind why use a function is because of its reusability. The
fact that even complex operations could be put together as
singular tasks that would run with just a call by its name is
what has made computer codes of today so much clearer as well.

F.Manna Introduction to Python 2019/2020


Every programming language lets you create and use these
functions to perform various tasks with just a call. And, you
could call it any number of times without having to worry
about logically structuring its code into your main code every
single time.
Let’s try and understand their need to us through a simple
example first.

Say, you have a television that stores many channels on it,


receives their digital radio broadcasts, converts them into

F.Manna Introduction to Python 2019/2020


what we watch, while also giving us additional options for a
variety of other features as well.
But that doesn’t mean there is someone logically scripting the
lines of codes for what you watch every time you turn on your
tv or flip a channel. Rather, functions for each task in its
working have been logically defined once and keep getting
reused time and again according to the features you try to
use.
All of it happens by calling its different functions as many
times as needed from the main function that is running. So,
even if you’re turning the volume up or down, its defined
function is being called repeatedly.
And, having a system operating the main code to keep calling
these functions as and when needed has also made designing and
innovating upon it all the easier.
The important thing to note is that whenever this function is
called, it executes its tasks depending on the instructions
specified in it.
That’s how machines can have different functions. A calculator
is probably the most common example of this. It has the
provision of addition, subtraction, multiplication, division,
and other functions. All its functions have been clearly
predefined into it, but it only performs those that you choose
to call by pressing its respective button.
Programmers reduce coding time and debugging time, thereby
reducing overall development time, by using functions.
Next up on this Python Functions blog, let us look at what the
Python Functions actually are.

What Are Python Functions?


The functions in Python are a classic example of such
reusability. So, to serve a wide range of applications from
GUI and mathematical computing to web development and testing,
Python’s interpreter already comes equipped with numerous
functions that are always available for use. And, you could
also bring in other libraries or modules to your program that
contain pre-defined functions readily available for use.

F.Manna Introduction to Python 2019/2020


All you’ll really have to do is download required packages
that according to their documentation and freely avail all its
useful functionalities by just importing them over to your
code.
So, once defined, a function can be used any number of times
at any point in any of your codes. Now, this is because Python
falls in-line with the DRY principle of software engineering,
which aims to replace any repetition of software patterns or
codes with abstractions to avoid redundancy and ensure that
they can be used freely without revealing any inner details on
their implementations.
DRY expands to Don’t Repeat Yourself and this concept of
having re-usable blocks of codes is very crucial for achieving
abstraction in Python. Thus, in order to use a function all
that you’ll really need is its name, its purpose, its
arguments if it takes any and its result’s type if it returns
any.
It’s almost like using an automobile or a telephone, where you
don’t necessarily need to understand the working of its
components to use them. Rather, they’ve been already built to
serve common purposes that you can just use directly to
achieve your goals and devote your precious time to
implementing all the innovative aspects of your application
program. And, nobody really wants to know how a function in
your program works on the inside, as long as it does the job.
So, with Python, unless you must write a new function or
change how an existing one works, you won’t even need to
understand anything about what goes on inside till it works
the way you need it to. It’s just like with a vehicle or a
phone again, where you’ll need to know how it works in order
to build or fix one. And, similarly, once you’ve written a
working function, you can use it repeatedly without having to
look at the contents inside it ever again.
A function can be called as a section of a program that is
written once and can be executed whenever required in the
program, thus making code reusability.
The function is a subprogram that works on data and produces
some output.

F.Manna Introduction to Python 2019/2020


To define a Python function, you’d have to use the ‘def’
keyword before the name of your function and add parentheses
to its end, followed by a colon(:).
Python uses indentation to indicate blocks instead of brackets
to make codes more readable.
A function in Python may contain any number of parameters or
none. So, for times when you need your function to operate on
variables from other blocks of code or from your main program,
it could take any number of parameters and produce results.
A Python function could also optionally return a value. This
value could be a result produced from your function’s
execution or even be an expression or value that you specify
after the keyword ‘return’. And, after a return statement is
executed, the program flow goes back to the state next to your
function call and gets executed from there.
So, to call a Python function at any place in your code,
you’ll only have to use its name and pass arguments in its
parentheses, if any.
The rules for naming a function are the same as naming a
variable. It begins with either letter from A-Z, a-z in both
upper & lower cases or an underscore(_). The rest of its name
can contain underscores(_), digits(0-9), any letters in upper
or lower case.

1. A reserved keyword may not be chosen as an identifier.


2. Good usage of grammar to ensure enhanced readability of
code.

It is good practice to name a Python function according to


what it does. use a docstring right under the first line of a
function declaration. This is a documentation string, and it
explains what the function does.
Next up in this Python Functions blog, let us check out the
types of Functions available in Python.

Types Of Python Functions

F.Manna Introduction to Python 2019/2020


There are many types of Python Functions. And each of them is
very vital in its own way. The following are the different
types of Python Functions:

● Python Built-in Functions


● Python Recursion Functions
● Python Lambda Functions
● Python User-defined Functions

Let us check out these functions in detail. Beginning with


Built-in functions as they are very easy to understand and
implement.

Python Built-in Functions:


The Python interpreter has a number of functions that are
always available for use. These functions are called built-in
functions. For example, print() function prints the given
object to the standard output device (screen) or to the text
stream file.
In Python 3.6, there are 68 built-in functions. But for the
sake of simplicity let us consider the majorly used functions
and we can build on from there.

Python abs() Function:


Definition
The abs() method returns the absolute value of the given
number. If the number is a complex number, abs() returns its
magnitude.
Syntax
The syntax of abs() method is:
abs(num)
Parameters
The abs() method takes a single argument:

● num – A number whose absolute value is to be returned.


The number can be:
1. integer
2. floating number

F.Manna Introduction to Python 2019/2020


3. complex number

Example
1 # random integer
2 integer = -20
3 print('Absolute value of -20 is:',
4 abs(integer))
5
6 #random floating number
7 floating = -30.33
print('Absolute value of -30.33 is:',
abs(floating))
Output
Absolute value of -20 is: 20 Absolute value of -30.33 is:
30.33

Python all() Function:


Definition
The all() method returns True when all elements in the given
iterable are true. If not, it returns False.
Syntax
The syntax of all() method is:
all(iterable)
Parameters
The all() method takes a single parameter:

● iterable – Any iterable (list, tuple, dictionary, etc.)


which contains the elements

Example

F.Manna Introduction to Python 2019/2020


1 # all values
2 true
3 l = [1, 3, 4,
4 5]
5 print(all(l))
6
7 # all values
8 false
9 l = [0,
1 False]
0 print(all(l))
1
1 # one false
1 value
2 l = [1, 3, 4,
1 0]
3 print(all(l))
1
4 # one true
1 value
5 l = [0,
1 False, 5]
6 print(all(l))
1
7 # empty
1 iterable
8 l = []
1 print(all(l))
9
Output
True
False
False
False
True

Python ascii() Function:

F.Manna Introduction to Python 2019/2020


Definition
The ascii() method returns a string containing a printable
representation of an object. It escapes the non-ASCII
characters in the string using x, u or U escapes.
Syntax
The syntax of ascii() method is:
ascii(object)
Parameters
The ascii() method takes an object (like strings, list etc).
Example
1 normalText = 'Python is
2 interesting'
3 print(ascii(normalText))
4
5 otherText = 'Pythön is
6 interesting'
7 print(ascii(otherText))

print('Pythn is
interesting')
Output
'Python is interesting'
'Pythn is interesting'
Pythön is interesting

Python bin() Function:


Definition
The bin() method converts and returns the binary equivalent
string of a given integer. If the parameter isn’t an integer,
it has to implement __index__() method to return an integer.
Syntax
The syntax of bin() method is:
bin(num)
Parameters
The bin() method takes a single parameter:

F.Manna Introduction to Python 2019/2020


● num – an integer number whose binary equivalent is to be
calculated.
If not an integer, should implement __index__() method
to return an integer.

Example
1 number = 5
2 print('The binary equivalent of 5
is:', bin(number))
Output
The binary equivalent of 5 is: 0b101

Python bool() Function:


Definition
The bool() method converts and returns the binary equivalent
string of a given integer. If the parameter isn’t an integer,
it has to implement __index__() method to return an integer.
Syntax
The syntax of bool() method is:
bool([value])
Parameters
It’s not mandatory to pass a value to bool(). If you do not
pass a value, bool() returns False.
In general use, bool() takes a single parameter value.
Example

F.Manna Introduction to Python 2019/2020


1 test = []
2 print(test,'is',boo
3 l(test))
4
5 test = [0]
6 print(test,'is',boo
7 l(test))
8
9 test = 0.0
1 print(test,'is',boo
0 l(test))
1
1 test = None
1 print(test,'is',boo
2 l(test))
1
3 test = True
1 print(test,'is',boo
4 l(test))
1
5 test = 'Easy
1 string'
6 print(test,'is',boo
1 l(test))
7
Output
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True

Python compile() Function:


Definition
The compile() method returns a Python code object from the
source (normal string, a byte string, or an AST object).
F.Manna Introduction to Python 2019/2020
Syntax
The syntax of compile() method is:
compile(source, filename, mode, flags=0, dont_inherit=False,
optimize=-1)
Parameters

● source – a normal string, a byte string, or an AST object


● filename – file from which the code was read. If it
wasn’t read from a file, you can give a name yourself
● mode – Either exec or eval or single.
○ eval – accepts only a single expression.
○ exec – It can take a code block that has Python
statements, class and functions and so on.
○ single – if it consists of a single interactive
statement
● flags (optional) and dont_inherit (optional) – controls
which future statements affect the compilation of the
source. Default Value: 0
● optimize (optional) – optimization level of the compiler.
Default value -1.

Example
1 codeInString = 'a = 5
2 b=6
3 sum=a+b
4 print("sum =",sum)'
5 codeObejct = compile(codeInString,
6 'sumstring', 'exec')
7
exec(codeObejct)
Output
sum = 11

Python dict() Function:


Definition
The dict() constructor creates a dictionary in Python.
Syntax

F.Manna Introduction to Python 2019/2020


Different forms of dict() constructors are:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Example
1 numbers = dict(x=5,
2 y=0)
3 print('numbers =
4 ',numbers)
5 print(type(numbers)
6 )
7
empty = dict()
print('empty =
',empty)
print(type(empty))
Output
empty = dict()
print('empty = ',empty)
print(type(empty))

Python enumerate() Function:


Definition
The enumerate() method adds counter to an iterable and returns
it (the enumerate object).
Syntax
The syntax of enumerate() method is:
enumerate(iterable, start=0)
Parameters
The enumerate() method takes two parameters:

● iterable – a sequence, an iterator, or objects that


support iteration
● start (optional) – enumerate() starts counting from this
number. If start is omitted, 0 is taken as the start.

Example

F.Manna Introduction to Python 2019/2020


1 grocery = ['bread', 'milk',
2 'butter']
3 enumerateGrocery =
4 enumerate(grocery)
5
6 print(type(enumerateGrocery))
7
8 # converting to list
9 print(list(enumerateGrocery))
1
0 # changing the default
1 counter
1 enumerateGrocery =
enumerate(grocery, 10)
print(list(enumerateGrocery))
Output
<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]

Python eval() Function:


Definition
The eval() method parses the expression passed to this method
and runs python expression (code) within the program.
Syntax
The syntax of eval() method is:
eval(expression, globals=None, locals=None)
Parameters
The eval() takes three parameters:

● expression – this string is parsed and evaluated as a


Python expression
● globals (optional) – a dictionary
● locals (optional)- a mapping object. Dictionary is the
standard and commonly used mapping type in Python.

Example

F.Manna Introduction to Python 2019/2020


1 x = 1
2 print(eval('x
+ 1'))
Output
sum = 11

Python filter() Function:


Definition
The filter() method constructs an iterator from elements of an
iterable for which a function returns true.
Syntax
The syntax of filter() method is:
filter(function, iterable)
Parameters
The filter() method takes two parameters:

● function – function that tests if elements of an iterable


return true or false
If None, the function defaults to Identity function –
which returns false if any elements are false
● iterable – iterable which is to be filtered, could be
sets, lists, tuples, or containers of any iterators

Example

F.Manna Introduction to Python 2019/2020


1 # list of alphabets
2 alphabets = ['a', 'b', 'd', 'e',
3 'i', 'j', 'o']
4
5 # function that filters vowels
6 def filterVowels(alphabet):
7 vowels = ['a', 'e', 'i', 'o',
8 'u']
9
1 if(alphabet in vowels):
0 return True
1 else:
1 return False
1
2 filteredVowels =
1 filter(filterVowels, alphabets)
3
1 print('The filtered vowels are:')
4 for vowel in filteredVowels:
1 print(vowel)
5
1
6
1
7
Output
The filtered vowels are:
a
e
i
o

Python getattr() Function:


Definition
The getattr() method returns the value of the named attribute
of an object. If not found, it returns the default value
provided to the function.
F.Manna Introduction to Python 2019/2020
Syntax
The syntax of getattr() method is:
getattr(object, name[, default])
Parameters
The getattr() method takes multiple parameters:

● object – object whose named attribute’s value is to be


returned
● name – string that contains the attribute’s name
● default (Optional) – value that is returned when the
named attribute is not found

Example
1 class Person:
2 age = 23
3 name = "Adam"
4
5 person = Person()
6 print('The age is:',
7 getattr(person, "age"))
print('The age is:',
person.age)
Output
The age is: 23
The age is: 23

Python help() Function:


Definition
The help() method calls the built-in Python help system.
Syntax
The syntax of help() method is:
help(object)
Parameters
The help() method takes the maximum of one parameter.

● object (optional) – you want to generate the help of the


given object

F.Manna Introduction to Python 2019/2020


Example
>>> help('print')

Python id() Function:


Definition
The id() function returns identity (unique integer) of an
object.
Syntax
The syntax of id() method is:
id(object)
Parameters
The id() function takes a single parameter object.
Example
1 class Foo:
2 b = 5
3
4 dummyFoo = Foo()
5 print('id of dummyFoo
=',id(dummyFoo))
Output
id of dummyFoo = 140343867415240

Python len() Function:


Definition
The len() function returns the number of items (length) in an
object.
Syntax
The syntax of len() method is:
len(s)
Parameters
s – a sequence (string, bytes, tuple, list, or range) or a
collection (dictionary, set or frozen set)
Example

F.Manna Introduction to Python 2019/2020


1 testList = []
2 print(testList, 'length is',
3 len(testList))
4
5 testList = [1, 2, 3]
6 print(testList, 'length is',
7 len(testList))
8
9 testTuple = (1, 2, 3)
1 print(testTuple, 'length is',
0 len(testTuple))
1
1 testRange = range(1, 10)
print('Length of', testRange, 'is',
len(testRange))
Output
[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9

Python max() Function:


Definition
The max() method returns the largest element in an iterable or
largest of two or more parameters.
Syntax
The syntax of max() method is:
max(iterable, *iterables[,key, default])
max(arg1, arg2, *args[, key])
Parameters
max() has two forms of arguments it can work with.

1. max(iterable, *iterables[, key, default])


○ iterable – sequence (tuple, string), collection
(set, dictionary) or an iterator object whose
largest element is to be found

F.Manna Introduction to Python 2019/2020


○ *iterables (Optional) – any number of iterables
whose largest is to be found
○ key (Optional) – key function where the iterables
are passed and the comparison is performed based on
its return value
○ default (Optional) – default value if the given
iterable is empty
2. max(arg1, arg2, *args[, key])
○ arg1 – mandatory first object for comparison (could
be number, string or other object)
○ arg2 – mandatory second object for comparison (could
be number, string or another object)
○ *args (Optional) – other objects for comparison
○ key – key function where each argument is passed and
the comparison is performed based on its return
value

Example
1 # using max(arg1, arg2,
2 *args)
3 print('Maximum is:', max(1,
4 3, 2, 5, 4))
5
6 # using max(iterable)
num = [1, 3, 2, 8, 5, 10, 6]
print('Maximum is:',
max(num))
Output
Maximum is: 5
Maximum is: 10

Python min() Function:


Definition
The min() method returns the smallest element in an iterable
or smallest of two or more parameters.
The syntax of min() method is:
min(iterable, *iterables[,key, default])

F.Manna Introduction to Python 2019/2020


min(arg1, arg2, *args[, key])
Parameters
min() has two forms of arguments it can work with.

1. min(iterable, *iterables[, key, default])


○ iterable – sequence (tuple, string), collection
(set, dictionary) or an iterator object whose
smallest element is to be found
○ *iterables (Optional) – any number of iterables
whose smallest is to be found
○ key (Optional) – key function where the iterables
are passed and the comparison is performed based on
its return value
○ default (Optional) – default value if the given
iterable is empty
2. min(arg1, arg2, *args[, key])
○ arg1 – mandatory first object for comparison (could
be number, string or other object)
○ arg2 – mandatory second object for comparison (could
be number, string or other object)
○ *args (Optional) – other objects for comparison
○ key – key function where each argument is passed and
a comparison is performed based on its return value

Example
1 # using min(arg1, arg2,
2 *args)
3 print('Minimum is:', min(1,
4 3, 2, 5, 4))
5
6 # using min(iterable)
num = [3, 2, 8, 5, 10, 6]
print('Minimum is:',
min(num))
Output
Minimum is: 1
Minimum is: 2

F.Manna Introduction to Python 2019/2020


Python oct() Function:
Definition
The oct() method takes an integer number and returns its octal
representation. If the given number is an int, it must
implement __index__() method to return an integer.
The syntax of oct() method is:
oct(x)
Parameters
The oct() method takes a single parameter x.
This parameter could be:

● an integer number (binary, decimal or hexadecimal)


● if not an integer, must implement __index__() method to
return an integer

Example
1 # decimal number
2 print('oct(10) is:',
3 oct(10))
4
5 # binary number
6 print('oct(0b101) is:',
7 oct(0b101))
8
# hexadecimal number
print('oct(0XA) is:',
oct(0XA))
Output
oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12

Python pow() Function:


Definition

F.Manna Introduction to Python 2019/2020


The pow() method returns x to the power of y. If the third
argument (z) is given, it returns x to the power of y modulus
z, i.e. pow(x, y) % z.
The syntax of pow() method is:
pow(x, y[, z])
Parameters
The pow() method takes three parameters:

● x – number which is to be powered


● y – number which is to be powered with x
● z (Optional) – number which is to be used for modulus
operation

Example
1 # positive x, positive
2 y (x**y)
3 print(pow(2, 2))
4
5 # negative x, positive
6 y
7 print(pow(-2, 2))
8
9 # positive x, negative
1 y (x**-y)
0 print(pow(2, -2))
1
1 # negative x, negative
y
print(pow(-2, -2))
Output
4
4
0.25
0.25

Python reversed() Function:


Definition

F.Manna Introduction to Python 2019/2020


The reversed() method returns the reversed iterator of the
given sequence.
The syntax of reversed() method is:
reversed(seq)
Parameters
The reversed() method takes a single parameter:

● seq – sequence that should be reversed


Could be an object that supports sequence protocol
(__len__() and __getitem__() methods) as tuple, string,
list or range
Could be an object that has implemented __reversed__()

Example
1 # for string
2 seqString = 'Python'
3 print(list(reversed(seqString
4 )))
5
6 # for tuple
7 seqTuple = ('P', 'y', 't',
8 'h', 'o', 'n')
9 print(list(reversed(seqTuple)
1 ))
0
1 # for range
1 seqRange = range(5, 9)
1 print(list(reversed(seqRange)
2 ))
1
3 # for list
1 seqList = [1, 2, 4, 3, 5]
4 print(list(reversed(seqList))
1 )
5
Output
['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']

F.Manna Introduction to Python 2019/2020


[8, 7, 6, 5]
[5, 3, 4, 2, 1]

Python sum() Function:


Definition
The sum() method returns the reversed iterator of the given
sequence.
The syntax of sum() method is:
sum(iterable, start)
Parameters

● iterable – iterable (list, tuple, dict etc) whose item’s


sum is to be found. Normally, items of the iterable
should be numbers.
● start (optional) – this value is added to the sum of
items of the iterable. The default value of start is 0
(if omitted)

Example
1 numbers = [2.5, 3, 4,
2 -5]
3
4 # start parameter is
5 not provided
6 numbersSum =
7 sum(numbers)
8 print(numbersSum)
9
# start = 10
numbersSum =
sum(numbers, 10)
print(numbersSum)
Output
4.5
14.5

F.Manna Introduction to Python 2019/2020


Python type() Function:
Definition
If a single argument (object) is passed to type() built-in, it
returns the type of the given object. If three arguments
(name, bases, and dict) are passed, it returns a new type
object.
The syntax of type() method is:
type(object)
type(name, bases, dict)
Parameters

● If the single object argument is passed to type(), it


returns the type of the given object.

Example
1 numberList = [1, 2]
2 print(type(numberList))
3
4 numberDict = {1: 'one',
5 2: 'two'}
6 print(type(numberDict))
7
8 class Foo:
9 a = 0
1
0 InstanceOfFoo = Foo()
1 print(type(InstanceOfFo
1 o))
Output
<class 'dict'>
<class 'Foo'>
Next up on this Python Functions blog, let us check out the
Recursive Function in Python.

Python Recursive Functions

F.Manna Introduction to Python 2019/2020


What is recursion in Python?
Recursion is the process of defining something in terms of
itself.
A physical world example would be to place two parallel
mirrors facing each other. Any object in between them would be
reflected recursively.

Python Recursive Function


We know that in Python, a function can call other functions.
It is even possible for the function to call itself. These
type of construct are termed as recursive functions.
Following is an example of a recursive function to find the
factorial of an integer.
Factorial of a number is the product of all the integers from
1 to that number. For example, the factorial of 5 (denoted as
5!) is 1*2*3*4*5 = 120.
Example:
1 # An example of a recursive function to
2 # find the factorial of a number
3
4 def calc_factorial(x):
5 <em>"""This is a recursive function
6 to find the factorial of an integer"""
7
8 </em>if x == 1:
9 return 1
1 else:
0 return (x * calc_factorial(x-1))
1
1 num = 4
1 print("The factorial of", num, "is",
2 calc_factorial(num))
1
3
1
4

F.Manna Introduction to Python 2019/2020


In the above example, calc_factorial() is a recursive function
as it calls itself.
When we call this function with a positive integer, it will
recursively call itself by decreasing the number.
Each function call multiples the number with the factorial of
number 1 until the number is equal to one.
Our recursion ends when the number reduces to 1. This is
called the base condition. Every recursive function must have
a base condition that stops the recursion or else the function
calls itself infinitely.

Advantages of Recursion

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler
sub-problems using recursion.
3. Sequence generation is easier with recursion than using
some nested iteration.

Disadvantages of Recursion

1. Sometimes the logic behind recursion is hard to follow


through.
2. Recursive calls are expensive (inefficient) as they take
up a lot of memory and time.
3. Recursive functions are hard to debug.

Next up on this Python Functions blog, let us check out the


Lambda Function in Python.

Python Lambda Functions

What Are Lambda functions?


In Python, an anonymous function is a function that is defined
without a name.
While normal functions are defined using the def keyword, in
Python anonymous functions are defined using the lambda
keyword.

F.Manna Introduction to Python 2019/2020


Hence, anonymous functions are also called lambda functions.

How To Use Lambda Functions In Python?


A Lambda function in python has the following syntax:
lambda arguments: expression

Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda
functions can be used wherever function objects are required.
Example
1 # Program to show the use of
2 lambda functions
3
4 double = lambda x: x * 2
5
6 # Output: 10
print(double(5))
Output
10
In [1]:
In the above program, lambda x: x * 2 is the Lambda function.
Here x is the argument and x * 2 is the expression that gets
evaluated and returned.
This function has no name. It returns a function object which
is assigned to the identifierdouble We can now call it as a
normal function. The statement
double = lambda x: x * 2

is nearly the same as


def double(x):
return x * 2

Next up on this Python Functions blog, let us check out the


how we can make use of User-defined functions in Python

Python User-Defined Functions

F.Manna Introduction to Python 2019/2020


What Are User-Defined Functions In Python?
Functions that we define ourselves to do the certain specific
task are referred to as user-defined functions. The way in
which we define and call functions in Python are already
discussed.
Functions that readily come with Python are called built-in
functions. If we use functions written by others in the form
of the library, it can be termed as library functions.
All the other functions that we write on our own fall under
user-defined functions. So, our user-defined function could be
a library function to someone else.
Advantages of user-defined functions

1. User-defined functions help to decompose a large program


into small segments which makes the program easy to
understand, maintain and debug.
2. If repeated code occurs in a program. The function can be
used to include those codes and execute when needed by
calling that function.
3. Programmers working on a large project can divide the
workload by making different functions.

Syntax
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
Example
1 # Program to illustrate
2 # the use of user-defined
3 functions
4
5 def add_numbers(x,y):
6 sum = x + y
7 return sum
8
9 num1 = 5

F.Manna Introduction to Python 2019/2020


1 num2 = 6
0
1 print("The sum is",
1 add_numbers(num1, num2))
Output
Enter a number: 2.4
Enter another number: 6.5
The sum is 8.9

Next up on this Python Functions blog, let us check out how we


can create a simple application using Python.

Python Program To Create A Simple Calculator Application


In this example, you will learn to create a simple calculator
that can add, subtract, multiply or divide depending upon the
input from the user.
Code

F.Manna Introduction to Python 2019/2020


1 # Program make a simple calculator that can add,
2 subtract, multiply and divide using functions
3
4 # This function adds two numbers
5 def add(x, y):
6 return x + y
7
8 # This function subtracts two numbers
9 def subtract(x, y):
1 return x - y
0
1 # This function multiplies two numbers
1 def multiply(x, y):
1 return x * y
2
1 # This function divides two numbers
3 def divide(x, y):
1 return x / y
4
1 print("Select operation.")
5 print("1.Add")
1 print("2.Subtract")
6 print("3.Multiply")
1 print("4.Divide")
7
1 # Take input from the user
8 choice = input("Enter choice(1/2/3/4):")
1
9 num1 = int(input("Enter first number: "))
2 num2 = int(input("Enter second number: "))
0
2 if choice == '1':
1 print(num1,"+",num2,"=", add(num1,num2))
2
2 elif choice == '2':
2 print(num1,"-",num2,"=", subtract(num1,num2))
3
2 elif choice == '3':

F.Manna Introduction to Python 2019/2020


4 print(num1,"*",num2,"=", multiply(num1,num2))
2
5 elif choice == '4':
2 print(num1,"/",num2,"=", divide(num1,num2))
6 else:
2 print("Invalid input")
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4

F.Manna Introduction to Python 2019/2020


3
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210

In this program, we ask the user to choose the desired


operation. Options 1, 2, 3 and 4 are valid. Two numbers are
taken and an if...elif...else branching is used to execute a
particular section. User-defined functions add(), subtract(),
multiply() and divide() evaluate respective operations.

Introduction To File Handling In Python

File Handling In Python


Python Programming Language is a high-level and interpreted
programming language which was created by Guido Van Rossum in
1989. It has been widely used in almost all the domains today
and shows no sign of slowing down. This is because of all the
features that Python provides to the developers. And, file
handling is one among this top feature of Python.
According to the website’s survey, Python’s popularity
surpassed that of C# in 2018 – just like it surpassed PHP in
2017. On the GitHub platform, Python surpassed Java as the
second-most used programming language, with 40% more pull
requests opened in 2017 than in 2016.
This makes Python certification one of the most sought-after
programming certifications.
In this post on “File Handling in Python” I have included the
following topics:

F.Manna Introduction to Python 2019/2020


● Why you need File Handling?
● Types of files supported by Python
● File operations using Python
● Creating a text file using Python
● Reading a text file using Python
● Looping over a file object in Python
● File Write method in Python
● Closing a file in Python
● Splitting lines in a text file

Python File Handling | File Operations in Python | Learn


python programming | Edureka
Let’s begin this “File Handling in Python” blog by checking
out why we need File Handling!

Why Do You Need File Handling?


File handling has always been vital to a huge part of the
development community. But, why?
Take a minute and think about this situation – You have a
server up and running and you need to access files present on
that server. You can do this remotely or you need to work with
files locally by giving some input to your python program on
the server or so.
If I had to answer this personally – I use files a lot for my
Deep Learning models to import my data-sets into the program,
so I think I agree with a good chunk of the community when I
say that usage of files is extremely vital in Python.
So coming back to the basics again – How can we input
something to Python?

● Standard input – The usual keyboard input


● Command line arguments – To input some parameter into
the code while executing

F.Manna Introduction to Python 2019/2020


But, think of this situation too – What if you had to read
lots and lots of data which is not practical to type in every
single time. or even so, it doesn’t make sense to type it out
all the time.
So, what is the easiest way out here to store whatever input
you want in one place and keep using it as long as your
requirement is met? The answer is? Files!
This concept is very easy, I am sure everyone reading this
“File Handling in Python” blog will relate to that by the end
of the blog.
Working with files basically opens another door among
thousands. Each door with Python again opens up to ‘n’ number
of opportunities.
Next up in this “File Handling in Python” blog, let us look at
the different types of files supported by Python.

Types Of Files Supported By Python


Can you quickly think of all of the types of files that you
know? Image, audio, video, text, scripts and many more.
The dependency on the native Operating System is the most
important thing to keep in mind when considering the type of
files supported.

F.Manna Introduction to Python 2019/2020


Windows supports all of the file types mentioned in the first
line. But does it support every type of file? Absolutely not!
There are certain limitations here as well.
Now, coming to Python – There are 2 types of files mainly:

● Binary
● Text

Binary files are categorized as the


generic 0’s and 1’s in Python too.
A binary file is any type of file that is not a text file.
Because of their nature, binary files can only be processed by
an application that knows or understand the file’s structure.
In other words, they must be applications that can read and
interpret binary.
Text files are structured as a sequence of lines, where each
line includes a sequence of characters. This is what you know
as code or syntax. Each line is terminated with a special
character, called the EOL or End of Line character.
Next up on this “File Handling in Python” blog, let us look at
the different file operations supported by Python.

F.Manna Introduction to Python 2019/2020


File Operations Using Python – CRUD Operation In Python:
What are the various file operations that you can generally
perform?
We call it CRUD. CRUD stands for:

● Create
● Read
● Update
● Delete

However, do note that there are many other operations that can
be performed with the files as well. Such as, copying a file
or changing the properties of the file and filter.
All of these operations are important to manipulate the file.
This manipulation ensures that the file operations can be
performed as per the exact requirement of the user working on
the file.

F.Manna Introduction to Python 2019/2020


Check out the above flow diagram to get a quick picture of
what needs to be done. First, we create a file and later open
that file. We work on that file – either read or write or
anything for that matter. And lastly, we close the file when
are doing using it.
Coming to Python now – Creation of file can be done manually
or through Python. For now, let us consider that we will do it
manually by going to the location and creating a file like a
text file.
Later on this Python File Handling blog, I will show you how
easy it is to make Python create the file for us as well so
stay tuned.

open() Function in Python:


Now we will check out how we can open a file in Python. It is
very simple – we have an inbuilt function called the open
function which is used for this exact purpose. The open
function takes in 2 parameters – one is the filename and the
other is the mode.
And this is the syntax for the open function.

F.Manna Introduction to Python 2019/2020


file_object = open(“filename”, “mode”) where file_object is
the variable to add the file object.
So what do the 2 parameters mean? One is the filename you want
to open. It can be anything at this point of time along with
the extension of the filetype. This is important, so make sure
to keep this in your mind.
And second, we have the mode. We know this means something to
do with opening the file, right? Check this out.

Open Modes:
These are the various modes available to open a file. We can
open in read mode, write mode, append mode and create mode as
well. Pretty straightforward. But do note that the default
mode is the read mode.
Including a mode argument is optional because a default value
of ‘r’ will be assumed if it is omitted. The ‘r’ value stands
for read mode, which is just one of many.
The modes are:
‘r’ – Read mode which is used when the file is only being read
‘w’ – Write mode which is used to edit and write new
information to the file (any existing files with the same name
will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end
of the file; that is new information is automatically amended
to the end
‘r+’ – Special read and write mode, which is used to handle
both actions when working with a file
Note that you can open a file in read more only if it exists
as well. If you try to read something that doesn’t exist then
Python will greet you with a beautiful error message.
In addition, you can specify if the file should be handled as
binary or text mode along with the mode as well. You can have
the mode as WT so it means that the file is to be opened in
the write mode and the file Python is opening is a text file.
Example
1 f =
2 open(“workfile”,”
w”)

F.Manna Introduction to Python 2019/2020


print f
This snippet opens the file named “workfile” in writing mode
so that we can make changes to it. The current information
stored within the file is also displayed – or printed – for us
to view.
Once this has been done, you can move on to call the objects
functions. The two most common functions are read and write.
Next up on this “File Handling in Python” blog, let us look at
how we can create a text file using Python.

Creating A Text File Using Python


To get more familiar with text files in Python, what’s better
than beginning by creating our own. We will check out some
examples as well!
Using any simple text editor of your choice, let’s create a
file first. You can name it anything you like at this point,
and it’s better to use something you’ll identify with. This is
usually done to increase readability. Readability helps to
understand the code better, debug and document it as well!
For the purpose of this tutorial, however, we are going to
call it “demofile.txt”. Just create the file and leave it
blank.
Check out the following code, you could copy the same thing
and post it over into your editor as well!
1 file = open(“demo.txt”,”w”)
2
3
4 file.write(“Hello World”)
5
6 file.write(“This is our new text
7 file”)
8
9 file.write(“and this is another
1 line.”)
0
1 file.write(“Why? Because we can do it

F.Manna Introduction to Python 2019/2020


1 this easily.”)
1
2
1 file.close()
3
Output
$ cat demo.txt
Hello World
This is our new text file
and this is another line.
Why? Because we can do it this easily.
Next up on this “File Handling in Python” blog, let us look at
how we can read a text file using Python.

Reading A Text File In Python


There are so many ways in which you can read a text file in
Python. But, let us start with the simple stuff and work on
from there.
If you need to extract a string that contains all the
characters in the file, you can use the following method:
1 file.re
ad()
The full code to work with this method will look something
like this:
1 file =
2 open(“demo.txt”,
“r”)
print file.read()
The output of that command will display all the text inside
the file, the same text we told the interpreter to add
earlier. There’s no need to write it all out again, but if you
must know, everything will be shown except for the “$ cat
demo.txt” line.
Another way to read a file is to call a certain number of
characters.

F.Manna Introduction to Python 2019/2020


For example, with the following code the interpreter will read
the first five characters of stored data and return it as a
string:
1 file =
2 open(“demo.txt”,
3 “r”)

print file.read(5)
Notice how we’re using the same file.read() method, only this
time we specify the number of characters to process?
The output for this will look like:
Hello
If you want to read a file line by line – as opposed to
pulling the content of the entire file at once – use the
readline() function.
Why would you use something like this?
Let’s say you only want to see the first line of the file – or
the third. You would execute the readline()function as many
times as possible to get the data you were looking for.
Each time you run the method, it will return a string of
characters that contains a single line of information from the
file.
1 file =
2 open(“demo.txt”,
“r”)
print
file.readline():
This would return the first line of the file, like so:
Hello World
If we wanted to return only the third line in the file, we
would use this:
1 file =
2 open(“testfile.txt”,
“r”)
print file.readline(3):

F.Manna Introduction to Python 2019/2020


But what if we wanted to return every line in the file,
properly separated? You would use the same function, only in a
new form. This is called the file.readlines() function.
1 file =
2 open(“testfile.txt”,
“r”)
print file.readlines()
The output you would get from this is:
[‘Hello World’, ‘This is our new text file’, ‘and this is
another line.’, ‘Why? Because we can.’]
Notice how each line is separated accordingly? Note that this
is not the ideal way to show users the content in a file. But
it’s great when you want to collect information quickly for
personal use during development or recall.
Next up on this “File Handling in Python” blog, let us look at
how we can loop over a file object using Python.

Looping Over A File Object In Python


When you want to read – or return – all the lines from a file
in a more memory efficient, and fast manner, you can use the
loop over method. The advantage to using this method is that
the related code is both simple and easy to read.
1 file =
2 open(“demo.txt”,
3 “r”)
for line in file:
print line
This will return:
Hello World
This is our new text file
and this is another line.
Why? Because we can.
See how much simpler that is than the previous methods?
Next up on this “File Handling in Python” blog, let us look at
how we can write a text file using Python.

F.Manna Introduction to Python 2019/2020


File Write Method In Python
One thing you’ll notice about the file write method is that it
only requires a single parameter, which is the string you want
to be written.
This method is used to add information or content to an
existing file. To start a new line after you write data to the
file, you can add an EOL character.
1 file = open(“demo.txt”,
2 “w”)
3
4 file.write(“This is a
5 test”)
6 file.write(“To add more
lines.”)

file.close()
Obviously, this will amend our current file to include the two
new lines of text. There’s no need to show output.
Next up on this “File Handling in Python” blog, let us look at
how we can close a text file using Python.

Closing A File In Python


When you’re done working, you can use the fh.close() command
to end things. What this does is close the file completely,
terminating resources in use, in turn freeing them up for the
system to deploy elsewhere.
It’s important to understand that when you use the fh.close()
method, any further attempts to use the file object will fail.
Notice how we have used this in several of our examples to end
interaction with a file? This is a good practice.
Next up on this “File Handling in Python” blog, let us look at
how we can split lines in a text file using Python.

Splitting Lines In A Text File

F.Manna Introduction to Python 2019/2020


As a final example, let’s explore a unique function that
allows you to split the lines taken from a text file. What
this is designed to do, is split the string contained in
variable data whenever the interpreter encounters a space
character.
But just because we are going to use it to split lines after a
space character, doesn’t mean that’s the only way. You can
actually split your text using any character you wish – such
as a colon, for instance.
The code to do this (also using a with statement) is
1 with open(“hello.text”,
2 “r”) as f:
3 data = f.readlines()
4
5 for line in data:
6 words = line.split()
print words
If you wanted to use a colon instead of a space to split your
text, you would simply change line.split() to line.split(“:”).
The output for this will be:
[“hello”, “world”, “how”, “are”, “you”, “today?”]
[“today”, “is”, “Saturday”]
The reason the words are presented in this manner is that they
are stored – and returned – as an array. Be sure to remember
this when working with the split function.

Python Classes And Objects – Object Oriented Programming


After Stack Overflow predicted that by 2019, Python will
outstrip other languages in terms of active developers, the
demand for Certified Python Developers is only growing. Python
follows object-oriented programming paradigm. It deals with
declaring python classes, creating objects from them and
interacting with the users. In an object-oriented language,
the program is split into self-contained objects or you can
say into several mini-programs. Each object is representing a
different part of the application which can communicate among
themselves.

F.Manna Introduction to Python 2019/2020


In this python class blog, you will understand each aspect of
classes and objects in the following sequence:

● What is a Python Class?


● Methods and Attributes in a class
● What are Objects?
● OOPs Concepts:
■ Inheritance
■ Polymorphism
■ Abstraction

Let’s get started.:-)

What is a Python Class?


A class in python is the blueprint from which specific objects
are created. It lets you structure your software in a
particular way. Here comes a question how? Classes allow us to
logically group our data and function in a way that it is easy
to reuse and a way to build upon if need to be. Consider the
below image.

In the first image (A), it represents a blueprint of a house


that can be considered as Class. With the same blueprint, we
can create several houses and these can be considered as
Objects. Using a class, you can add consistency to your
programs so that they can be used in cleaner and efficient
ways. The attributes are data members (class variables and
instance variables) and methods which are accessed via dot
notation.

F.Manna Introduction to Python 2019/2020


● Class variable is a variable that is shared by all the
different objects/instances of a class.
● Instance variables are variables which are unique to each
instance. It is defined inside a method and belongs only
to the current instance of a class.
● Methods are also called as functions which are defined in
a class and describes the behaviour of an object.

Now, let us move ahead and see how it works in PyCharm. To get
started, first have a look at the syntax of a python class.
Syntax:
1 class
2 Class_name:
3 statement-1
4 .
5 .
statement-N
Here, the “class” statement creates a new class definition.
The name of the class immediately follows the keyword “class”
in python which is followed by a colon. To create a class in
python, consider the below example:

1 class employee:
2 pass
3 #no attributes and methods
4 emp_1=employee()
5 emp_2=employee()
6 #instance variable can be
7 created manually
8 emp_1.first='aayushi'
9 emp_1.last='Johari'
1
0 emp_1.email='[email protected]
1 '
1 emp_1.pay=10000
1
2 emp_2.first='test'

F.Manna Introduction to Python 2019/2020


1 emp_2.last='abc'
3 emp_2.email='[email protected]'
1 emp_2.pay=10000
4 print(emp_1.email)
1 print(emp_2.email)
5
1
6
1
7
Output –
[email protected]
[email protected]
Now, what if we don’t want to manually set these variables.
You will see a lot of code and also it is prone to error. So
to make it automatic, we can use “init” method. For that,
let’s understand what exactly are methods and attributes in a
python class.

Methods and Attributes in a Python Class


Now creating a class is incomplete without some functionality.
So functionalities can be defined by setting various
attributes which acts as a container for data and functions
related to those attributes. Functions in python are also
called as Methods. Talking about the init method, it is a
special function which gets called whenever a new object of
that class is instantiated. You can think of it as initialize
method or you can consider this as constructors if you’re
coming from any another object-oriented programming background
such as C++, Java etc. Now when we set a method inside a
class, they receive instance automatically. Let’s go ahead
with python class and accept the first name, last name and
salary using this method.

F.Manna Introduction to Python 2019/2020


1 class employee:
2 def __init__(self, first, last,
3 sal):
4 self.fname=first
5 self.lname=last
6 self.sal=sal
7 self.email=first + '.' + last
8 + '@company.com'
9
1 emp_1=employee('aayushi','johari',3500
0 00)
1 emp_2=employee('test','test',100000)
1 print(emp_1.email)
print(emp_2.email)
Now within our “init” method, we have set these instance
variables (self, first, last, sal). Self is the instance which
means whenever we write self.fname=first, it is same as
emp_1.first=’aayushi’. Then we have created instances of
employee class where we can pass the values specified in the
init method. This method takes the instances as arguments.
Instead of doing it manually, it will be done automatically
now.
Next, we want the ability to perform some kind of action. For
that, we will add a method to this class. Suppose I want the
functionality to display the full name of the employee. So
let’s us implement this practically.

F.Manna Introduction to Python 2019/2020


1 class employee:
2 def __init__(self, first, last,
3 sal):
4 self.fname=first
5 self.lname=last
6 self.sal=sal
7 self.email=first + '.' + last +
8 '@company.com'
9
1 def fullname(self):
0 return
1 '{}{}'.format(self.fname,self.lname)
1
1 emp_1=employee('aayushi','johari',35000
2 0)
1 emp_2=employee('test','test',100000)
3 print(emp_1.email)
1 print(emp_2.email)
4 print(emp_1.fullname())
1 print(emp_2.fullname())
5
1
6
Output –
[email protected]
[email protected]
aayushijohari
testtest
As you can see above, I have created a method called “full
name” within a class. So each method inside a python class
automatically takes the instance as the first argument. Now
within this method, I have written the logic to print full
name and return this instead of emp_1 first name and last
name. Next, I have used “self” so that it will work with all
the instances. Therefore to print this every time, we use a
method.
Moving ahead with Python classes, there are variables which
are shared among all the instances of a class. These are

F.Manna Introduction to Python 2019/2020


called as class variables. Instance variables can be unique
for each instance like names, email, sal etc. Complicated?
Let’s understand this with an example. Refer the code below to
find out the annual rise in the salary.
1 class employee:
2 perc_raise =1.05
3 def __init__(self, first, last,
4 sal):
5 self.fname=first
6 self.lname=last
7 self.sal=sal
8 self.email=first + '.' + last +
9 '@company.com'
1
0 def fullname(self):
1 return
1 '{}{}'.format(self.fname,self.lname)
1 def apply_raise(self):
2 self.sal=int(self.sal*1.05)
1
3 emp_1=employee('aayushi','johari',35000
1 0)
4 emp_2=employee('test','test',100000)
1
5 print(emp_1.sal)
1 emp_1.apply_raise()
6 print(emp_1.sal)
1
7
1
8
1
9
Output –
350000
367500
As you can see above, I have printed the salary first and then
applied the 1.5% increase. In order to access these class

F.Manna Introduction to Python 2019/2020


variables, we either need to access them through the class or
an instance of the class. Now, let’s understand the various
attributes in a python class.

Attributes in a Python Class


Attributes in Python defines a property of an object, element
or a file. There are two types of attributes:
Built-in Class Attributes: There are various built-in
attributes present inside Python classes. For example _dict_,
_doc_, _name _, etc. Let me take the same example where I want
to view all the key-value pairs of employee1. For that, you
can simply write the below statement which contains the class
namespace:

print(emp_1.__dict__)


After executing it, you will get output such as:
{‘fname’: ‘aayushi’, ‘lname’: ‘johari’, ‘sal’: 350000,
’email’: ‘[email protected]’}
● Attributes defined by Users: Attributes are created
inside the class definition. We can dynamically create
new attributes for existing instances of a class.
Attributes can be bound to class names as well.

Next, we have public, protected and private attributes. Let’s


understand them in detail:
Naming Type Meaning

Name Public These attributes can be freely used


inside or outside of a class
definition

_name Protected Protected attributes should not be


used outside of the class definition,
unless inside of a subclass definition

F.Manna Introduction to Python 2019/2020


__name Private This kind of attribute is inaccessible
and invisible. It’s neither possible
to read nor to write those
attributes, except inside of the class
definition itself

Next, let’s understand the most important component in a


python class i.e Objects.

What are objects in a Python Class?

As we have discussed above, an object can be used to access


different attributes. It is used to create an instance of the
class. An instance is an object of a class created at
run-time.
To give you a quick overview, an object basically is
everything you see around. For eg: A dog is an object of the
animal class, I am an object of the human class. Similarly,
there can be different objects to the same phone class. This

F.Manna Introduction to Python 2019/2020


is quite similar to a function call which we have already
discussed. Let’s understand this with an example:
1 class MyClass:
2
3 def
4 func(self):
5
6 print('Hello')
7
8 # create a new
MyClass
ob = MyClass()
ob.func()
Moving ahead with python class, let’s understand the various
OOPs concepts.

OOPs Concepts
OOPs refers to the Object-Oriented Programming in Python.
Well, Python is not completely object-oriented as it contains
some procedural functions. Now, you must be wondering what is
the difference between a procedural and object-oriented
programming. To clear your doubt, in a procedural programming,
the entire code is written into one long procedure even though
it might contain functions and subroutines. It is not
manageable as both data and logic get mixed together. But when
we talk about object-oriented programming, the program is
split into self-contained objects or several mini-programs.
Each object is representing a different part of the
application which has its own data and logic to communicate
among themselves. For example, a website has different objects
such as images, videos etc.
Object-Oriented programming includes the concept of Python
class, object, Inheritance, Polymorphism, Abstraction etc.
Let’s understand these topics in detail.

Python Class: Inheritance

F.Manna Introduction to Python 2019/2020


Inheritance allows us to inherit attributes and methods from
the base/parent class. This is useful as we can create
sub-classes and get all of the functionality from our parent
class. Then we can overwrite and add new functionalities
without affecting the parent class. Let’s understand the
concept of parent class and child class with an example.

As
we can see in the image, a child inherits the properties from
the father. Similarly, in python, there are two classes:
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )
A class which inherits the properties is known as Child Class
whereas a class whose properties are inherited is known as
Parent class.

Inheritance refers to the ability to create Sub-classes that


contain specializations of their parents. It is further
divided into four types namely single, multilevel,
hierarchical and multiple inheritances. Refer the below image
to get a better understanding.

F.Manna Introduction to Python 2019/2020


Let’s go ahead with python class and understand how
inheritance is useful.
Say, I want to create classes for the types of employees. I’ll
create ‘developers’ and ‘managers’ as sub-classes since both
developers and managers will have a name, email and salary and
all these functionalities will be there in the employee class.
So, instead of copying the code for the subclasses, we can
simply reuse the code by inheriting from the employee.
1 class employee:
2 num_employee=0
3 raise_amount=1.04
4 def __init__(self, first, last,
5 sal):
6 self.first=first
7 self.last=last
8 self.sal=sal
9 self.email=first + '.' + last
1 + '@company.com'
0 employee.num_employee+=1
1 def fullname (self):
1 return '{}
1 {}'.format(self.first, self.last)
2 def apply_raise (self):
1 self.sal=int(self.sal *
3 raise_amount)
1 class developer(employee):
4 pass
1
5 emp_1=developer('aayushi', 'johari',

F.Manna Introduction to Python 2019/2020


1 1000000)
6 print(emp_1.email)
1
7
1
8
Output - [email protected]
As you can see in the above output, all the details of the
employee class are available in the developer class. Now what
if I want to change the raise_amount for a developer to 10%?
let’s see how it can be done practically.
1 class employee:
2 num_employee=0
3 raise_amount=1.04
4 def __init__(self, first, last,
5 sal):
6 self.first=first
7 self.last=last
8 self.sal=sal
9 self.email=first + '.' + last
1 + '@company.com'
0 employee.num_employee+=1
1 def fullname (self):
1 return '{}
1 {}'.format(self.first, self.last)
2 def apply_raise (self):
1 self.sal=int(self.sal*
3 raise_amount)
1
4 class developer(employee):
1 raise_amount = 1.10
5
1 emp_1=developer('aayushi', 'johari',
6 1000000)
1 print(emp_1.raise_amount)
7
1

F.Manna Introduction to Python 2019/2020


8
1
9
Output - 1.1
As you can see that it has updated the percentage rise in
salary from 4% to 10%. Now if I want to add one more
attribute, say a programming language in our init method, but
it doesn’t exist in our parent class. Is there any solution
for that? Yes! we can copy the entire employee logic and do
that but it will again increase the code size. So to avoid
that, let’s consider the below code:
1 class employee:
2 num_employee=0
3 raise_amount=1.04
4 def __init__(self, first, last,
5 sal):
6 self.first=first
7 self.last=last
8 self.sal=sal
9 self.email=first + '.' + last +
1 '@company.com'
0 employee.num_employee+=1
1 def fullname (self):
1 return '{}
1 {}'.format(self.first, self.last)
2 def apply_raise (self):
1 self.sal=int(self.sal*
3 raise_amount)
1 class developer(employee):
4 raise_amount = 1.10
1 def __init__(self, first, last,
5 sal, prog_lang):
1 super().__init__(first, last,
6 sal)
1 self.prog_lang=prog_lang
7
1 emp_1=developer('aayushi', 'johari',

F.Manna Introduction to Python 2019/2020


8 1000000, 'python')
1 print(emp_1.prog_lang)
9
2
0
2
1
Therefore, with just a little bit of code, I have made
changes. I have used super.__init__(first, last, pay) which
inherits the properties from the base class. To conclude,
inheritance is used to reuse the code and reduce the
complexity of a program.

Python Class: Polymorphism


Polymorphism in Computer Science is the ability to present the
same interface for differing underlying forms. In practical
terms, polymorphism means that if class B inherits from class
A, it doesn’t have to inherit everything about class A, it can
do some of the things that class A does differently. It is
most commonly used while dealing with inheritance. Python is
implicitly polymorphic, it has the ability to overload
standard operators so that they have appropriate behaviour
based on their context.
Let us understand with an example:
1 class Animal:
2 def
3 __init__(self,name):
4
5 self.name=name
6 def
7 talk(self):
8 pass
9 class Dog(Animal):
1 def
0 talk(self):
1
1 print('Woof')

F.Manna Introduction to Python 2019/2020


1 class Cat(Animal):
2 def talk(self):
1
3 print('MEOW!')
1 c= Cat('kitty')
4 c.talk()
1 d=Dog(Animal)
5 d.talk()
Output –
Meow!
Woof
Next, let us move to another object-oriented programming
concept i.e Abstraction.

Python Class: Abstraction


Abstraction is used to simplify complex reality by modelling
classes appropriate to the problem. Here, we have an abstract
class which cannot be instantiated. This means you cannot
create objects or instances for these classes. It can only be
used for inheriting certain functionalities which you call as
a base class. So you can inherit functionalities but at the
same time, you cannot create an instance of this particular
class. Let’s understand the concept of abstract class with an
example below:

F.Manna Introduction to Python 2019/2020


1 from abc import ABC,
2 abstractmethod
3
4 class Employee(ABC):
5 @abstractmethod
6
7 def
8 calculate_salary(self,sal):
9 pass
1
0 class Developer(Employee):
1
1 def
1 calculate_salary(self,sal):
2 finalsalary=
1 sal*1.10
3 return finalsalary
1
4 emp_1 = Developer()
1 print(emp_1.calculate_salar
5 y(10000))
1
6
Output –
11000.0
As you can see in the above output, we have increased the base
salary to 10% i.e. the salary is now 11000. Now, if you
actually go on and make an object of class “Employee”, it
throws you an error as python doesn’t allow you to create an
object of abstract class. But using inheritance, you can
actually inherit the properties and perform the respective
tasks.

What is Mutithreading in Python and How to Achieve it?


Time is the most critical factor in life. Owing to its
importance, the world of programming provides various tricks
and techniques that significantly help you reduce the time

F.Manna Introduction to Python 2019/2020


consumption, thereby increasing performance. One such approach
is Multithreading in Python, which is one of the most
important concepts covered under Python Certification
Training.
Here is a quick summary of all the majors covered in this
article:
What is multitasking in Python?
What is a thread?
What is multithreading in python?
When to use multithreading in Python?
How to achieve Multithreading in Python?
How to create threads in Python?

● without creating a class


● by extending thread class
● without extending thread class

Advantages of using multithreading in Python


To begin with, let us first try to understand multitasking
before we start learning about Multithreading in Python.

What is Multitasking in Python?


Multitasking, in general, is the capability of performing
multiple tasks simultaneously. In technical terms,
multitasking refers to the ability of an operating system to
perform different tasks at the same time. For instance, you
are downloading something on your PC as well as listening to
songs and concurrently playing a game, etc. All these tasks
are performed by the same OS an in sync. This is nothing but
multitasking which not just helps you save time but also
increases productivity.
There are two types of multitasking in an OS:

● Process-based
● Thread-based

In this article, you will be learning about Thread-based


multitasking or Multithreading.

F.Manna Introduction to Python 2019/2020


What is a thread?

A thread is basically an independent flow of execution. A


single process can consist of multiple threads. Each thread in
a program performs a particular task. For Example, when you
are playing a game say FIFA on your PC, the game as a whole is
a single process, but it consists of several threads
responsible for playing the music, taking input from the user,
running the opponent synchronously, etc. All these are
separate threads responsible for carrying out these different
tasks in the same program.
Every process has one thread that is always running. This is
the main thread. This main thread actually creates the child
thread objects. The child thread is also initiated by the main
thread. I will show you all further in this article how to
check the current running thread.
So with this, I hope you have clearly understood what is a
thread. Moving on, let’s see what is Multithreading in Python.
When to use Multithreading in Python?
Multithreading is very useful for saving time and improving
performance, but it cannot be applied everywhere.
In the previous FIFA example, the music thread is independent
of the thread that takes your input and the thread that takes

F.Manna Introduction to Python 2019/2020


your input is independent of the thread that runs your
opponent. These threads run independently because they are not
inter-dependent.
Therefore, multithreading can be used only when the dependency
between individual threads does not exist.
This article further shows how you can achieve Multithreading
in Python.

How to achieve Multithreading in Python?


Multithreading in Python can be achieved by importing the
threading module.
Before importing this module, you will have to install this
it. To install this on your anaconda environment, execute the
following command on your anaconda prompt:
conda install -c conda-forge tbb
After its successfully installed, you can use any of the
following commands to import the threading module:
1 import threading
2 from threading
import *
Now that you have threading module installed, let us move
ahead and do Multithreading in Python.

How to create threads in Python?

Threads in Python can be created in three ways:

1. Without creating a class


2. By extending Thread class
3. Without extending Thread class

Without creating a class


Multithreading in Python can be accomplished without creating
a class as well. Here is an example to demonstrate the same:
Example:

F.Manna Introduction to Python 2019/2020


1 from threading import *
2 print(current_thread().getName())
3 def mt():
4 print("Child Thread")
5 child=Thread(target=mt)
6 child.start()
7 print("Executing thread name
:",current_thread().getName())
Output:
MainThread
Child Thread
Executing thread name : MainThread
The above output shows that the first thread that is present
is, the main thread. This main thread then creates a child
thread that is executing the function and then the final print
statement is executed again by the main thread.
Now let us move ahead and see how to do Multithreading in
python by extending the Thread class.

By extending the Thread class:


When a child class is created by extending the Thread class,
the child class represents that a new thread is executing some
task. When extending the Thread class, the child class can
override only two methods i.e. the __init__() method and the
run() method. No other method can be overridden other than
these two methods.
Here is an example of how to extend the Thread class to create
a thread:
Example:

F.Manna Introduction to Python 2019/2020


1 import threading
2 import time
3 class
4 mythread(threading.Thread):
5 def run(self):
6 for x in range(7):
7 print("Hi from child")
8 a = mythread()
9 a.start()
1 a.join()
0 print("Bye
from",current_thread().getName(
))
Output:
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Bye from MainThread
The above example shows that class myclass is inheriting the
Thread class and the child class i.e myclass is overriding the
run method. By default, the first parameter of any class
function needs to be self which is the pointer to the current
object. The output shows that the child thread executes the
run() method and the main thread waits for the childs
execution to complete. This is because of the join() function,
which makes the main thread wait for the child to finish.
This method of creating threads is the most preferred method
because its the standard method. But in case you want to
create threads without inheriting or extending the Thread
class, you can do it in the following manner.

Without Extending Thread class


To create a thread without extending the Thread class, you can
do as follows:
F.Manna Introduction to Python 2019/2020
Example:
1 from threading import *
2 class ex:
3 def myfunc(self): #self necessary as first
4 parameter in a class func
5 for x in range(7):
6 print("Child")
7 myobj=ex()
8 thread1=Thread(target=myobj.myfunc)
9 thread1.start()
1 thread1.join()
0 print("done")
Output:
Child
Child
Child
Child
Child
Child
Child
done
The child thread executes myfunc after which the main thread
executes the last print statement.

Advantages of using threading


Multithreading has many advantages some of which are as
follows:

● Better utilization of resources


● Simplifies the code
● Allows concurrent and parallel occurrence of various
tasks
● Reduces the time consumption or response time, thereby,
increasing the performance.

Here is an example to check how long it takes for a code to


execute with and without multithreading in python:
Example:

F.Manna Introduction to Python 2019/2020


1 import time
2 def sqr(n):
3 for x in n:
4
5 time.sleep(1)
6 x%2
7 def cube(n):
8 for x in n:
9
1 time.sleep(1)
0 x%3
1 n=[1,2,3,4,5,6,
1 7,8]
1 s=time.time()
2 sqr(n)
1 cube(n)
3 e=time.time()
1 print(e-s)
4
1
5
Output:
16.042309284210205

The above is the output time taken to execute the program


without using threads. Now let us use threads and see what
happens to the same program:
Example:

F.Manna Introduction to Python 2019/2020


1 import threading
2 from threading import *
3 import time
4 def sqr(n):
5 for x in n:
6 time.sleep(1)
7 print('Remainder after
8 dividing by 2',x%2)
9 def cube(n):
1 for x in n:
0 time.sleep(1)
1 print('Remainder after
1 dividing by 3',x%3)
1 n=[1,2,3,4,5,6,7,8]
2 start=time.time()
1 t1=Thread(target=sqr,args=(n,))
3 t2=Thread(target=cube,args=(n,))
1 t1.start()
4 time.sleep(1)
1 t2.start()
5 t1.join()
1 t2.join()
6 end=time.time()
1 print(end-start)
7
1
8
1
9
2
0
2
1
2
2
Output: 9.040220737457275

F.Manna Introduction to Python 2019/2020


The above output clearly shows that the time taken when we use
threads is much less compared to the time taken for the same
program to execute without using threads.

Cheat Sheet To Python RegEx With Examples

Python RegEx:
Regular Expressions can be used to search, edit and manipulate
text. This opens up a vast variety of applications in all of
the sub-domains under Python. Python RegEx is widely used by
almost all of the startups and has good industry traction for
their applications as well as making Regular Expressions an
asset for the modern day programmer.
In this Python RegEx blog, we will be checking out the
following concepts:

● Why we use Regular Expressions?


● What are Regular Expressions?
● Basic Regular Expressions operations
● Email verification using Regular Expressions
● Phone number verification using Regular Expressions
● Web Scraping using Regular Expressions

Python RegEx | Python Regular Expressions Tutorial | Python


Tutorial | Python Training | Edureka
Let’s begin this Python RegEx blog by checking out why we need
to make use of Regular Expressions.

Why Use Regular Expression?


To answer this question, we will look at the various problems
faced by us which in turn is solved by using Regular
Expressions.
Consider the following scenario:
You have a log file which contains a large sum of data. And
from this log file, you wish to fetch only the date and time.

F.Manna Introduction to Python 2019/2020


As you can look at the image, readability of the log file is
low upon first glance.

Regular Expressions can be used in this case to recognize the


patterns and extract the required information easily.
Consider the next scenario – You are a salesperson and you
have a lot of email addresses and a lot of those addresses are
fake/invalid. Check out the image below:

F.Manna Introduction to Python 2019/2020


What you can do is, you can make use of Regular Expressions
you can verify the format of the email addresses and filter
out the fake IDs from the genuine ones.
The next scenario is pretty similar to the one with the
salesperson example. Consider the following image:

F.Manna Introduction to Python 2019/2020


How do we verify the phone number and then classify it based
on the country of origin?
Every correct number will have a particular pattern which can
be traced and followed through by using Regular Expressions.
Next up is another simple scenario:

We have a Student Database containing details such as name,


age, and address. Consider the case where the Area code was
originally 59006 but now has been changed to 59076. To
manually update this for each student would be time-consuming
and a very lengthy process.
Basically, to solve these using Regular Expressions, we first
find a particular string from the student data containing the
pin code and later replace all of them with the new ones.

F.Manna Introduction to Python 2019/2020


Regular expressions can be used with multiple languages. Such
as:

● Java
● Python
● Ruby
● Swift
● Scala
● Groovy
● C#
● PHP
● Javascript

There is other ‘n’ number of scenarios in which Regular


Expressions help us. I will be walking you through the same in
the upcoming sections of this Python RegEx blog.
So, next up on this Python RegEx blog, let us look at what
Regular Expressions actually are.

What Are Regular Expressions?


A Regular Expression is used for identifying a search pattern
in a text string. It also helps in finding out the correctness
of the data and even operations such as finding, replacing and
formatting the data is possible using Regular Expressions.
Consider the following example:

Among all of the data from the given string, let us say we
require only the City. This can be converted into a dictionary
with just the name and the city in a formatted way. The
question now is that, can we identify a pattern to guess the

F.Manna Introduction to Python 2019/2020


name and the city? Also, we can find out the age too. With
age, it is easy, right? it is just an integer number.
How do we go about with the name? If you take a look at the
pattern, all of the names start with an uppercase. With the
help of the Regular expressions, we can identify both the name
and the age using this method.
Consider the following code:
1 import re
2
3 Nameage = '''
4 Janice is 22 and Theon is 33
5 Gabriel is 44 and Joey is 21
6 '''
7
8 ages = re.findall(r'd{1,3}',
9 Nameage)
1 names =
0 re.findall(r'[A-Z][a-z]*',Name
1 age)
1
1 ageDict = {}
2 x = 0
1 for eachname in names
3 ageDict[eachname] =
1 ages[x]
4 x+=1
1 print(ageDict)
5
1
6
There is no need to worry about the syntax at this point of
time but since Python has amazing readability, you could very
well guess what is happening the Regular Expression part of
the code.
Output:
{'Janice': '22', 'Theon': '33', 'Gabriel': '44', 'Joey': '21'}
Next up on this Python RegEx blog, let us check out all the
operations we can perform using Regular Expressions.

F.Manna Introduction to Python 2019/2020


Operations You Can Perform With Regular Expressions – RegEx
Examples:
There are many operations you can perform by making use of
Regular Expressions. Here, I have listed a few which are very
vital in helping you understand the usage of Regular
Expressions better.
Let us begin this Python RegEx blog by first checking out how
we can find a particular word in a string.
Finding a word in the string:
Consider the following piece of code:
1 import re
2
3 if re.search("inform","we need to inform him with the
4 latest information"):
print("There is inform")
All we are doing here to search if the word inform exists in
our search string. And if it does, then we get an output
saying There is inform.
We can up this a little bit by writing a method which will do
a similar thing.
1 import re
2
3 allinform = re.findall("inform","We need to inform him
4 with the latest information!")
5
6 for i in allinform:
print(i)
Here, in this particular case inform will be found twice. One
from the inform and the other from the information.
And it is as simple as this to find a word in a Regular
Expression as shown above.
Next up on this Python RegEx blog, we will check out how we
can generate an iterator using Regular Expressions.
Generating an iterator:

F.Manna Introduction to Python 2019/2020


Generating an iterator is the simple process of finding out
and reporting the starting and the ending index of the string.
Consider the following example:
1 import re
2
3 Str = "we need to inform him with the
4 latest information"
5
6 for i in re.finditer("inform.", Str):
7 locTuple = i.span()
print(locTuple)
For every match found, the starting and the ending index is
printed. Can you take a guess of the output that we get when
we execute the above program? Check it out below.
Output:
(11, 18)
(38, 45)
Pretty simple, right?
Next up on this Python RegEx blog, we will be checking out how
we can match words with patterns using Regular Expressions.
Matching words with patterns:
Consider an input string where you have to match certain words
with the string. To elaborate, check out the following example
code:
1 import re
2
3 Str = "Sat, hat, mat,
4 pat"
5
6 allStr =
7 re.findall("[shmp]at",
8 Str)

for i in allStr:
print(i)
What is common in the string? You can see that the letters ‘a’
and ‘t’ are common among all of the input strings. [shmp] in

F.Manna Introduction to Python 2019/2020


the code denotes the starting letter of the words to be found.
So any substring starting with the letters s, h, m or p will
be considered for matching. Any among that and compulsorily
followed by ‘at’ at the end.
Output:
hat
mat
pat
Do note that they are all case sensitive. Regular expressions
have amazing readability. Once you get to know the basics, you
can start working on them in full swing and it’s pretty much
easy, right?
Next up on this Python RegEx blog, we will be checking out how
we can match a range of characters at once using Regular
Expressions.
Matching series of range of characters:
We wish to output all the words whose first letter should
start in between h and m and compulsorily followed by at.
Checking out the following example we should realize the
output we should get is hat and mat, correct?
1 import re
2
3 Str = "sat, hat, mat,
4 pat"
5
6 someStr =
7 re.findall("[h-m]at",
8 Str)

for i in someStr:
print(i)
Output:
hat
mat
Let us now change the above program very slightly to obtain a
very different result. Check out the below code and try to
catch the difference between the above one and the below one:

F.Manna Introduction to Python 2019/2020


1 import re
2
3 Str = "sat, hat, mat, pat"
4
5 someStr =
6 re.findall("[^h-m]at",
7 Str)
8
for i in someStr:
print(i)
Found the subtle difference? We have added a caret symbol(^)
in the Regular Expression. What this does it negates the
effect of whatever it follows. Instead of giving us the output
of everything starting with h to m, we will be presented with
the output of everything apart from that.
The output we can expect is words which are NOT starting with
letters in between h and m but still followed by at the last.
Output:
sat
pat
Next up on this Python RegEx blog, I will explain how we can
replace a string using Regular Expressions.
Replacing a string:
Next up, we can check out another operation using Regular
Expressions where we replace an item of the string with
something else. It is very simple and can be illustrated with
the following piece of code:
1 import re
2
3 Food = "hat rat mat
4 pat"
5
6 regex =
7 re.compile("[r]at")
8
9 Food =
regex.sub("food",

F.Manna Introduction to Python 2019/2020


Food)

print(Food)
In the above example, the word rat is replaced with the word
food. The final output will look like this. The substitute
method of the Regular Expressions is made use of this case and
it has a vast variety of practical use cases as well.
Output:
hat food mat pat
Next up on this Python RegEx blog, we will check out a unique
problem to Python called the Python Backslash problem.
The Backslash Problem:
Consider an example code shown below:
1 import re
2
3 randstr = "Here is
4 Edureka"
5
print(randstr)
Output:
Here is Edureka
This is the backslash problem. One of the slashes vanished
from the output. This particular problem can be fixed using
Regular Expressions.
1 import re
2
3 randstr = "Here is
4 Edureka"
5
print(re.search(r"Edureka"
, randstr))
The output can be as follows:
<re.Match object; span=(8, 16), match='Edureka'>
As you can check out, the match for the double slashes has
been found. And this is how simple it is to solve the
backslash problem using Regular Expressions.

F.Manna Introduction to Python 2019/2020


Next up on this Python RegEx blog, I will walk you through how
we can match a single character using Regular Expressions.
Matching a single character:
A single character from a string can be individually matched
using Regular Expressions easily. Check out the following code
snippet:
1 import re
2
3 randstr = "12345"
4
5 print("Matches: ",
len(re.findall("d{5}", randstr)))
The expected output is the 5th number that occurs in the given
input string.
Output:
Matches: 1
Next up on this Python RegEx blog, I will walk you through how
we can remove newline spaces using Regular Expressions.
Removing Newline Spaces:
We can remove the newline spaces using Regular Expressions
easily in Python. Consider another snippet of code as shown
here:
1 import re
2
3 randstr = '''
4 You Never
5 Walk Alone
6 Liverpool FC
7 '''
8
9 print(randstr)
1
0 regex = re.compile("
1 ")
1
1 randstr = regex.sub("
2 ", randstr)

F.Manna Introduction to Python 2019/2020


1
3 print(randstr)
1
4
1
5
1
6
Output:
You Never
Walk Alone
Liverpool FC

You Never Walk Alone Liverpool FC


As you can check out from the above output, the new lines have
been replaced with whitespace and the output is printed on a
single line.
There are many other things you could use as well depending on
what you want to replace the string with. They are listed as
follows:

● : Backspace
● : Formfeed

: Carriage Return
● : Tab
● : Vertical Tab

Consider another example as shown below:


1 import re
2
3 randstr = "12345"
4
5 print("Matches:",
len(re.findall("d", randstr)))
Output:
Matches: 5

F.Manna Introduction to Python 2019/2020


As you can see from the above output, d matches the integers
present in the string. However if we replace it with D, it
will match everything BUT an integer, the exact opposite of d.
Next up on this Python RegEx blog, let us walk through some
important practical use-cases of making use of Regular
Expressions in Python.

Practical Use Cases Of Regular Expressions


We will be checking out 3 main use-cases which are widely used
on a daily basis. Following are the concepts we will be
checking out:

● Phone Number Verification


● E-mail Address Verification
● Web Scraping

Let us begin this section of Python RegEx tutorial by checking


out the first case.
Phone Number Verification:
Problem Statement – The need to easily verify phone numbers in
any relevant scenario.
Consider the following Phone numbers:

● 444-122-1234
● 123-122-78999
● 111-123-23
● 67-7890-2019

The general format of a phone number is as follows:

● Starts with 3 digits and ‘-‘ sign


● 3 middle digits and ‘-‘ sign
● 4 digits in the end

We will be using w in the example below. Note that w =


[a-zA-Z0-9_]

F.Manna Introduction to Python 2019/2020


1 import re
2
3 phn = "412-555-1212"
4
5 if
6 re.search("w{3}-w{3}-w{4}
", phn):
print("Valid phone
number")
Output:
Valid phone number
E-mail Verification:
Problem statement – To verify the validity of an E-mail
address in any scenario.
Consider the following examples of email addresses:

[email protected]
● Anirudh @ com
● AC .com
● 123 @.com

Manually, it just takes you one good glance to identify the


valid mail IDs from the invalid ones. But how is the case when
it comes to having our program do this for us? It is pretty
simple considering the following guidelines are followed for
this use-case.
Guidelines:
All E-mail addresses should include:

● 1 to 20 lowercase and/or uppercase letters, numbers, plus


. _ % +
● An @ symbol
● 2 to 20 lowercase and uppercase letters, numbers and plus
● A period symbol
● 2 to 3 lowercase and uppercase letters

Code:

F.Manna Introduction to Python 2019/2020


1 import re
2
3 email = "[email protected] [email protected] @seo.com [email protected]"
4
5 print("Email Matches: ",
len(re.findall("[w._%+-]{1,20}@[w.-]{2,20}.[A-Za-z]{2,3}",
email)))
Output:
Email Matches: 1
As you can check out from the above output, we have one valid
mail among the 4 emails which are the inputs.
This basically proves how simple and efficient it is to work
with Regular Expressions and make use of them practically.
Web Scraping
Problem Statement – Scrapping all of the phone numbers from a
website for a requirement.
To understand web scraping, check out the following diagram:

We already know that a single website will consist of multiple


web pages. And let us say we need to scrape some information
from these pages.
Web scraping is basically used to extract the information from
the website. You can save the extracted information in the

F.Manna Introduction to Python 2019/2020


form of XML, CSV or even a MySQL database. This is achieved
easily by making use of Python Regular Expressions.
1 import urllib.request
2 from re import findall
3
4 url =
5 "http://www.summet.com/dmsi/html/codesamples/ad
6 dresses.html"
7
8 response = urllib.request.urlopen(url)
9
1 html = response.read()
0
1 htmlStr = html.decode()
1
1 pdata = findall("(d{3}) d{3}-d{4}", htmlStr)
2
1 for item in pdata:
3 print(item)
1
4
1
5
Output:
(257) 563-7401
(372) 587-2335
(786) 713-8616
(793) 151-6230
(492) 709-6392
(654) 393-5734
(404) 960-3807
(314) 244-6306
(947) 278-5929
(684) 579-1879
(389) 737-2852
(660) 663-4518
(608) 265-2215
(959) 119-8364

F.Manna Introduction to Python 2019/2020


(468) 353-2641
(248) 675-4007
(939) 353-1107
(570) 873-7090
(302) 259-2375
(717) 450-4729
(453) 391-4650
(559) 104-5475
(387) 142-9434
(516) 745-4496
(326) 677-3419
(746) 679-2470
(455) 430-0989
(490) 936-4694
(985) 834-8285
(662) 661-1446
(802) 668-8240
(477) 768-9247
(791) 239-9057
(832) 109-0213
(837) 196-3274
(268) 442-2428
(850) 676-5117
(861) 546-5032
(176) 805-4108
(715) 912-6931
(993) 554-0563
(357) 616-5411
(121) 347-0086
(304) 506-6314
(425) 288-2332
(145) 987-4962
(187) 582-9707
(750) 558-3965
(492) 467-3131
(774) 914-2510
(888) 106-8550
(539) 567-3573

F.Manna Introduction to Python 2019/2020


(693) 337-2849
(545) 604-9386
(221) 156-5026
(414) 876-0865
(932) 726-8645
(726) 710-9826
(622) 594-1662
(948) 600-8503
(605) 900-7508
(716) 977-5775
(368) 239-8275
(725) 342-0650
(711) 993-5187
(882) 399-5084
(287) 755-9948
(659) 551-3389
(275) 730-6868
(725) 757-4047
(314) 882-1496
(639) 360-7590
(168) 222-1592
(896) 303-1164
(203) 982-6130
(906) 217-1470
(614) 514-1269
(763) 409-5446
(836) 292-5324
(926) 709-3295
(963) 356-9268
(736) 522-8584
(410) 483-0352
(252) 204-1434
(874) 886-4174
(581) 379-7573
(983) 632-8597
(295) 983-3476
(873) 392-8802
(360) 669-3923

F.Manna Introduction to Python 2019/2020


(840) 987-9449
(422) 517-6053
(126) 940-2753
(427) 930-5255
(689) 721-5145
(676) 334-2174
(437) 994-5270
(564) 908-6970
(577) 333-6244
(655) 840-6139
We first being by importing the packages which are needed to
perform the web scraping. And the final result comprises of
the phone numbers extracted as a result of the web scraping
done using Regular Expressions.

F.Manna Introduction to Python 2019/2020

You might also like