Unit-3 Advance
Python
GRADE X
DELHI PUBLIC SCHOOL, BANGALORE- EAST
Introduction to Anaconda
Anaconda is a free and open-source distribution of the Python language for scientific computing
(data science, machine learning applications, large-scale data processing, predictive analytics,
etc.), that aims to simplify package management and deployment.
It provides the facility to create different virtual environments, each having its own packages and
settings, as per user’s need.
Anaconda Navigator is a desktop graphical user interface(GUI) included in Anaconda that allows
you to launch applications and easily manage conda packages, environments and channels
without the need to use command line commands.
How to install Anaconda?
Anaconda distribution is open source and is available for Windows, Linux and Mac OS.
Here are the steps of how to download and install Anaconda for windows.
1) Log on to https://www.anaconda.com/products/individual
2. Scroll down to the Anaconda Installers
with operating system options
3) Under Python 3.7 version, select the
right option according to the configuration
of your pc(32-bit/64-bit). The download will
begin.
4) Double click the installer to launch.
5) Click on “Next”.
6) Read the license agreement and click on “I Agree”.
7) Select an install for “Just Me” unless you’re installing for all users (which
requires Windows Administrator privileges) and click “Next”.
8) Select destination folder, and click “Next”.
9) Do not change anything in PATH Options, click “Next”.
10) Wait for the installation to complete.
11) Click on “Skip” to continue.
12) Click on “Finish”. Your Anaconda setup is complete
What did we install?
Anaconda Prompt- Anaconda’s Command Line Interface.
Anaconda Prompt is a Python CLI where we can create different virtual environments and install
packages into them as per our need.
Anaconda prompt can be opened by writing “Anaconda Prompt” in windows search bar.
Introduction: Jupyter Notebook
The Jupyter Notebook is an incredibly powerful tool for interactively developing and presenting
AI related projects.
The Jupyter project is the successor to the earlier IPython Notebook, which was first published
as a prototype in 2010.
In other words, we can say that the Jupyter Notebook is an open source web application that
you can use to create and share documents that contain live code, equations, visualizations, and
text.
Installing Jupyter Notebook
The easiest way to install and start using Jupyter Notebook is through Anaconda.
Anaconda is the most widely used Python distribution for data science and comes pre-loaded
with all the most popular libraries and tools.
With Anaconda, comes the Anaconda Navigator through which we can scroll around all the
applications which come along with it.
Jupyter notebook can easily be accessed using the Anaconda Prompt with the help of a local
host.
Working with Jupyter Notebook
To work with Jupyter Notebook, it is necessary to have a kernel on which it operates.
A kernel provides programming language support in Jupyter.
IPython is the default kernel for Jupyter Notebook.
Therefore, whenever we need to work with Jupyter Notebook in a virtual environment, we first
need to install a kernel inside the environment in which the Jupyter notebook will run.
Start->Anaconda Prompt
Here, base is the active environment
and the default environment.
Steps to create one are:
1. Open Anaconda Prompt.
2. Let us now create a virtual environment named env. To create the environment, write
conda create -n env python=3.7
This code will create an environment named env and will install Python 3.7 and other basic packages into it
3. Once an environment has been successfully created, we can access it by writing the following:
conda activate env
But, to open and work with Jupyter Notebooks in this environment, we need to install the packages which
help in working with Jupyter Notebook. These packages get installed by default in the base environment
when Anaconda gets installed.
To install Jupyter Notebook dependencies, we need to activate our virtual environment env and write:
conda install ipykernel nb_conda jupyter
How to install the kernel?
To install the kernel, Open Anaconda Prompt and execute the following command:
Here, Jupyter is an extension to the Jupyter Notebook which gets installed.
Ipykernel is a powerful and interactive Python shell and a jupyter kernel to work with python
code in Jupyter Notebooks.
nb_conda refers to notebook conda which is an extension to jupyter kernel to set the kernel for
a notebook’s execution.
Once the installation is done, write the following command to open the Jupyter Notebook.
Jupyter Notebook opens in the default
browser with http://localhost:8888/tree
URL.
How to open a new Jupyter
notebook?
In this page, click on New and select Python3 which would open a new Jupyter notebook with
Python3 as the default language.
Notebook Interface - Explained!
Let us take a tour around the Notebook and understand its features.
1. File:
Helps to create a new Notebook, open a pre-existing one, rename a Notebook, create Save and
Checkpoint option(allows you to create checkpoints that you can roll back to)
2. Edit Menu:
Helps you to cut, copy, paste, delete, split, merge and reorder cells.
3. View menu:
Helps in toggling the visibility of the Header, Toolbar, Line Numbers within cells on or off.
4. Insert menu:
Helps in inserting cells above or below the currently selected cell.
5. Cell menu:
Helps to run one cell, a group of cells, all the cells, change a cell’s type(although the toolbar is
more intuitive for that) and clear a cell’s output.
6. Kernel Menu:
Helps to work with the kernel that is running in the background. Here you can restart the kernel,
reconnect to it, shut it down, or even change which kernel your Notebook is using.
7. Widgets Menu:
Helps for saving and clearing widget state. Widgets are basically JavaScript widgets that you can
add to your cells to make dynamic content using Python (or another Kernel).
8. Help Menu:
Helps to learn about the Notebook’s keyboard shortcuts, a user interface tour, and lots of
reference material.
Tool bar commands
Tool bar commands (contd.)
Recap: Introduction to Python
Python is a programming language which was created by Guido Van Rossum in Centrum
Wiskunde & Informatica.
The language was publicly released in 1991 and it got its name from a BBC comedy series from
1970s – ‘Monty Python’s Flying Circus’.
It can be used to follow both procedural approach and object-oriented approach of
programming.
Python has a lot of functionalities which makes it so popular to use.
Features of Python
Applications of Python
There exist a wide variety of applications when it comes to Python. Some of the applications are:
What is an Algorithm?
An algorithm is a step-by-step method to solve the identified problem.
In order to solve a mathematical or computer problem, this is the first step of the procedure.
It includes calculations, reasoning and data processing.
Example : Algorithm to Print 1 to 20:
What is a flowchart?
A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program.
FLOWCHART EXAMPLE
Activity
Write an algorithm to Convert Temperature from Fahrenheit ( ℉) to Celsius ( ℃)
Also Draw the flowchart.
Answer
Printing Statements
To print any statement, we use print() function in Python.
Python Statements
Instructions written in the source code for execution are called statements.
There are different types of statements in the Python programming language like Assignment
statement, Conditional statement, Looping statements etc. These help the user to get the
required output.
For example, n = 50 is an assignment statement.
Multi-line statement
In Python, end of a statement is marked by a newline character.
However, Statements in Python can be extended to one or more lines using parentheses (),
braces {}, square brackets [], semi-colon (;), continuation character slash (\).
Type of Multi-line Statement
Python Comments
A comment is text that doesn't affect the outcome of a code, it is just a piece of text to let
someone know what you have done in a program or what is being done in a block of code.
In Python, we use the hash (#) symbol to start writing a comment.
Python Keywords
Keywords are the reserved words in Python used by Python interpreter to recognize the
structure of the program.
Identifiers
Identifiers Examples
abc
X12y
india_123
Please Note: Keywords cannot be used as identifiers.
keywords and Identifiers are case-sensitive.
Variables
A variable is a named location used to store data in the memory. For example:
X = 10 # X variable contains numerical data
Letters = ‘XYZ’ # Letters variable contains alphabetic data
number = 13.95 # number variable contains a decimal value
word = ‘k’ # word variable contains a character
Constants:
A constant is a type of variable whose value cannot be changed. They are written in all capital
letters. For example:
NAME = "Ajay"
AGE = 24
Rules and Naming
convention for variables and
constants
Datatypes
Variables contain different types of data in them. The type of data is defined by the term
datatype in Python.
Python Numbers
Number data type stores Numerical Values. These are of three different types:
a) Integer & Long
b) Float / floating point
Integer & Long Integer
Range of an integer in Python can be from -2147483648 to 2147483647 and long integer has unlimited range subject to available
memory.
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17. While writing a large integer value,
don’t use commas to separate digits. Also, integers should not have leading zeros.
Floating Point:
Numbers with fractions or decimal point are called floating point numbers.
A floating-point number will consist of sign (+,-) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963. These
numbers can also be used to represent a number in engineering/ scientific notation.
-2.0 x 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5
None
This is special data type with single value.
It is used to signify the absence of value/false in a situation.
It is represented by None.
Sequence
A sequence is an ordered collection of items, indexed by positive integers. It is a combination of
mutable and non-mutable data types. Three types of sequence data type available in Python
are:
a) Strings
b) Lists
c) Tuples
Sequence(contd.)
String
String is an ordered sequence of letters/characters. They are enclosed in single quotes (‘ ‘) or
double (“ “). The quotes are not part of string. They only tell the computer where the string
constant begins and ends. They can have any character or sign, including space in them.
Lists
List is also a sequence of values of any type. Values in the list are called elements / items. These are
indexed/ordered. List is enclosed in square brackets. For Example
dob = [19,"January",1990]
Tuples:
Tuples are a sequence of values of any type, and are indexed by integers. They are immutable.
Tuples are enclosed in (). For Example
t = (5,'program',2.5)
Sets
Set is an unordered collection of values, of any type, with no duplicate entry. For Example:
>>> a = {1,2,2,3,3,3}
>>> a
{1,2,3}
Mapping
This data type is unordered. Dictionaries fall under Mappings.
Dictionaries
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge
amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the
value.
In Python, dictionaries are defined within braces {} with each item being a pair in the form key:
value. Key and value can be of any type.
Example
>>> d = {1:'Ajay','key':2}
>>> type(d)
<class 'dict'>
Python inputs
To collect the data from the user at the time of execution, input() function is used.
Datatype of the expected input is required to be mentioned so that the machine does not
interpret the received data in an incorrect manner.
By default data taken as input is string (sequence of characters) datatype.
For example:
Str = input(<String>) # Python expects the input to be of string datatype
Number = int(input(<string>)) # Input string gets converted to an integer
value before assignment
Value = float(input(<String>)) # Input string gets converted to a decimal
value before assignment
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.
Implicit Type Conversion
Example
Code to calculate the Simple Interest
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type
of the objects.
Syntax:
(required_datatype)(expression)
Typecasting can be done by assigning the required data type function to the expression.
Explicit Type Conversion: Example
Adding of string and an integer using explicit
conversion
Python Operators
Operators are special symbols which represent computation.
They are applied on operand(s), which can be values or variables.
Same operators can behave differently on different data types.
Operators when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and Assignment.
Value and variables when used with operators are known as operands.
Arithmetic Operators
Conditional Operators/Comparison
operators
Logical Operators
Assignment Operators
Let’s Practice
More About Lists and Tuples
List is a sequence of values of any type.
Values in the list are called elements / items.
List is enclosed in square brackets [ ], separated by commas..
Example:
How to access elements of a
list ?
A list is made up of various elements which need to be individually accessed on the basis of the
application it is used for. There are two ways to access an individual element of a list:
1) List Index
2) Negative Indexing
More Examples
Adding Element to a List
We can add an element to any list using two methods :
1) Using append() method
2) Using insert() method
3) Using extend() method
Adding Element to a List
1) Using append() method
Adding Element to a List:
Using insert() method
Adding Element to a List:
Using extend() method
Removing Elements from a List
Elements from a list can removed using two methods :
1) Using remove() method
2) Using pop() method
Removing Elements from a List
Using remove() method
The remove() method removes
the specified item.
Removing Elements from a List
Using pop() method
The pop() method removes the specified index or the last item if the index is not specified.
Example: Output :
thislist = ["apple", "banana", "cherry"] ['banana', 'cherry']
thislist.pop(0)
print(thislist)
Example: Output :
thislist = ["apple", "banana", "cherry"] ['apple', 'banana']
thislist.pop()
print(thislist)
Slicing of a List
Slice operation is performed on Lists with the use of colon(:)
To print elements from beginning to a range use [:Index]
To print elements from end use [:-Index]
To print elements from specific Index till the end use [Index:]
To print elements within a range, use [Start Index: End Index]
To print whole List with the use of slicing operation, use [:]
Further, to print whole List in reverse order, use [::-1]
To print elements of List from rear end, use Negative Indexes.
Let’s Practice
Download the Jupyter Notebook, go to the following link : http://bit.ly/lists_jupyter
Introduction to Tuples
Tuple is a collection of Python objects which is ordered and unchangeable.
The sequence of values stored in a tuple can be of any type, and they are indexed by integers.
In Python, tuples are created by placing sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of data sequence. It can contain any number of
elements and of any datatype (like strings, integers, list, etc.).
Example
fruits = ("apple", "banana", "cherry") print(fruits[1])
The above code will give the output as "banana"
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple gets
deleted by the use of del() method.
Example
num = (0, 1, 2, 3, 4)
del num
Flow of Control and Conditions
There are three control flow statements in Python - if, for and while.
Decision Making Statements/
Conditional Statements
Conditional statements help the machine in taking a decision according to the condition which
gets fulfilled.
There exist different types of conditional statements in Python.
According to the number of conditions and their dependency on each other, the relevant type of
conditional statement is used.
If Statement
The if statement is used to check a condition:
if the condition is true, we run a block of statements (called the if-block).
Syntax:
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed.
If Statement Example
if...else Statement
Syntax of if...else
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
if...else Statement Example
In the above example, when if the age entered by the person is greater than or equal to 18,
he/she can vote. Otherwise, the person is not eligible to vote
if...elif...else Statement
Syntax of if...elif...else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
if...elif...else Statement Example
Nested if statements
We can have an if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting.
This can get confusing, so must be avoided if it can be.
The For Loop
The for..in statement is another looping statement which iterates over a sequence of objects i.e.
go through each item in a sequence.
Syntax of for Loop
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using indentation.
For Loop Example
The while Statement
The while statement allows you to repeatedly execute a block of statements as long as a
condition is true.
A while statement is an example of what is called a looping statement.
A while statement can have an optional else clause.
Syntax of while Loop in Python
while Loop Example
Let’s Practice
Let’s Go through the flow control Jupyter Notebook to get an experiential learning experience
for ‘for’ and ‘while’ loop .
To download the Jupyter Notebook, go to the following link :
http://bit.ly/loops_jupyter
Introduction to Virtual
Environments
A virtual environment is a tool that helps to keep dependencies required by different projects
separate, by creating isolated Python virtual environments for them. This is one of the most
important tools that most of the Python developers use.
Steps to create virtual
environments:
1. Open Anaconda Prompt.
2
base is the default environment in which the anaconda works.
3
To create a virtual environment named env, write
conda create -n env python=3.7
This code will create an environment named env and will install Python 3.7 and other basic
packages into it.
4
After some processing, the prompt will ask if you wish to proceed with installations or not. Type
Y on it and press Enter.
Once you press Enter, the packages will start getting installed in the environment.
5
Depending upon the internet speed, the downloading of packages might take varied time. The
processing screen will look like this:
6
Once all the packages are downloaded and installed, you will get a message like this:
7
Once an environment has been successfully created, you can access it by writing the following:
conda activate env
To install Jupyter Notebook dependencies, activate your virtual environment env and write:
conda install ipykernel nb_conda jupyter
Python Packages
A package is nothing but a space where you can find codes or functions or modules of similar
type.
There are various packages readily available to use for free (perks of Python being an open-
sourced language) for various purposes.
To use any package in Python, we need to install it. Installing Python packages is easy.
Some of the readily available
packages are
Steps for package installation
are:
1. Open Anaconda Navigator and activate your working environment.
2. Let us assume you wish to install the numpy package.
conda install numpy
3. It would ask you to type Y if you wish to proceed with the installations. As soon as you type Y,
the installations will start and your package will be installed in your selected environment.
4. You can also install multiple packages all at once by mentioning all of them in one line in your
environment.
conda install numpy pandas matplotlib
Importing a package
In Jupyter Notebook, include the package by writing the import command.
import numpy
Meaning: Import numpy in the file to use its functionalities in the file to which it has been imported.
import numpy as np
Meaning: Import numpy and refer to it as np wherever it is used.
from numpy import array
Meaning: import only one functionality (array) from the whole numpy package. While this gives faster
processing, it limits the package’s usability.
from numpy import array as arr
Meaning: Import only one functionality (array) from the whole numpy package and refer to it as arr
wherever it is used.
Exploring NumPy!
NumPy package provides us with various features and functions which helps us in arithmetic
and logical operations. Let us look at some of them:
NumPy Arrays: Arrays are homogenous collection of datatypes. With NumPy, we can create n-
dimensional arrays (where n can be any integer) and operate on them using other mathematical
functions.
One of the features of array is that we can perform arithmetic functions on the elements of the
array directly by performing them on the whole array.
Ways by which you can create
arrays using NumPy package
Various operations that could be
implemented on a NumPy array:
One of the features of array is that we can perform arithmetic functions on the elements of the
array directly by performing them on the whole array.
Let us assume the array is “ARR” and it has been initialized as:
ARR = numpy.array([1,2,3,4,5])
Functions to find properties of a
Numpy array:
Some other mathematical
functions available with NumPy
are:
Thank You