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

Core Python ESD Final Draft

The document provides an introduction to the Python programming language, outlining its key features such as being interpreter-based, supporting basic data types like numbers, strings, lists and dictionaries, and object-oriented programming concepts; it also discusses Python's support for exception handling and automatic memory management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views

Core Python ESD Final Draft

The document provides an introduction to the Python programming language, outlining its key features such as being interpreter-based, supporting basic data types like numbers, strings, lists and dictionaries, and object-oriented programming concepts; it also discusses Python's support for exception handling and automatic memory management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 111

Introduction to Python

Contents

1. Introduction to Python
2. Data types in Python
3. Operators in Python
4. Input and Output
5. Arrays in Python
6. Strings and Characters in Python
7. Importing Packages and Modules
8. NumPy Arrays
9. DataFrames
10. Jupyter/Spyder
Introduction
1. Python is an interpreter-based language, which
allows execution of one instruction at a time.
2. Extensive basic data types are supported e.g.
numbers (floating point, complex, and
unlimited-length long integers), strings (both
ASCII and Unicode), lists, and dictionaries.
3. Variables can be strongly typed as well as
dynamic typed.
4. Supports object-oriented programming
concepts such as class, inheritance, objects,
module, namespace etc.
5. Cleaner exception handling support.
6. Supports automatic memory management.
Interpreter-based
https://www.youtube.com/watch?v=I1f45REi3k4
Dynamic Typed

Dynamically-typed languages do not require you to


declare the data types of your variables before you
use them

https://hackernoon.com/i-finally-understand-static-vs-
dynamic-typing-and-you-will-too-ad0c2bd0acc7
Exception Handling

https://stackify.com/application-exception-vs-error-
difference/
Applications Areas

1. Data Science
2. Machine Learning
3. Web Development
4. Image Processing
5. Internet of Things (IoT)
6. Android Apps, etc.
Data Types in Python

Data in Python can be one of the following 5 types:


1. Numbers
2. None
3. Sequence

a. String
b. List
c. Tuples
4. Dictionary
Data Types in Python
Numbers (Numeric Types -- int,
float, complex)
• Number stores numeric values. Python creates
Number objects when a number is assigned to a
variable.
• For example;
• a = 3 , b = 5 #a and b are number objects
Numbers (Numeric Types -- int,
float, complex)
• Python supports 3 types of numeric data.

- int (signed integers like 10, 2, 29, etc.)


- float (float is used to store floating point
numbers like 1.9, 9.902, 15.2, etc.)
- complex (complex numbers like 2.14j, 2.0 +
2.3j, etc.)
Exercise 1 (Integer and Float)

Output:
Exercise 2 (complex numbers)
Exercise 3
Guess the output
Exercise 4
What is the output of the below code?

num = 10
num2 = 5
num2 *= num1
print (num2)

Output: 50
Exercise 5

What is the output of the below code


snippet?
Assignment - 1

Write a python program to find and display the area


of a circle. Use the formula given for finding the area
of circle.
area=3.14*radius*radius

radius=5
area = 3.14 * (radius * radius)
print("Area of a Circle is :", area)
Assignment - 1 Code

radius=5
area = 3.14 * (radius * radius)
print("Area of a Circle is :", area)
None: Class NoneType

1. 'None' is Python's equivalent of NULL in C and


C++.
2. It signifies that the variable doesn't hold any
value as of now.

Example:
None: Interesting Points

1. We can assign None to any variable, but cannot


create other NoneType objects.
2. None is not the same as False.
3. None is not 0.
4. None is not an empty string.
5. Comparing None to anything will always return
False except None itself.
None: Examples
String Data type

• The string can be defined as the sequence of


characters represented in the quotation marks
(“”).
• In python, we can use single, double, or triple
quotes to define a string.
String vs. Character in Python

• Generally in programming languages there is a


different data type dedicated to characters only,
while in Python, there is no character data type.
• Instead characters are just treated as a string of
length 1.
Declaration of Strings and
accessing elements of Strings
Escape Sequence

Try it out:

Why did this happen?


Discuss
Using Escape sequences

- We used backslash or escape sequence at two


places, just before the quotes which we directly
want to print.
- If you want to inform the compiler to simply print
whatever you type and not try to compile it, just add
an escape sequence before it.
Exercise 6

What will be the output of?

print "\"\"\"\"\""
Operations on Strings

• Python provides a rich set of operators, functions,


and methods for working with strings.
• Operations on String:
• Concatenation (+)
• Multiple copies (*)
• In and Not in Operator
• String Indexing
• String Slicing
• Interpolating Variables Into a String
Operations on String

Concatenation:
Continued..

Repetition:
Check existence of a character or
a sub-string in a string
- The keyword in is used for this.
- For example: If there is a text India won the
match and you want to check if won exist in it or
not.
TRY IT OUT!
Converting String to Int or Float
data type and vice versa
Slicing
First let's get familiar with its usage syntax:
string_name[starting_index : finishing_index :
character_iterate]
- String_name is the name of the variable holding
the string.
- starting_index is the index of the beginning
character which you want in your substring.
- finishing_index is one more than the index of the
last character that you want in your substring.
- character_iterate: To understand this, let us
consider that we have a string Hello Brother!, and
we want to use the slicing operation on this string
to extract a substring. (continued..)
Slicing continued..
- str[0:10:2] means, we want to
extract a substring starting from the
index 0 (beginning of the string), to
the index value 10, and the last
parameter means, that we want
every second character, starting
from the starting index. Hence in
the output we will get, HloBo.
- H is at index 0, then leaving e, the
second character from H will be
printed, which is l, then skipping the
second l, the second character from
the first l is printed, which is o and
so on.
String Methods

1. Capitalize
2. Lowercase
3. Uppercase
4. Swapcase
5. Title
6. Length
7. Index
8. Count
9. Starts with and Ends with
Example - String Methods
Solution - String Methods
Assignment - 2

Write a code to get the below output.


Assignment 2 - Code
Lists

• Lists are in some ways similar to arrays in C.


• However, the list can contain data of different
types.
• The items stored in the list are separated with a
comma (,) and enclosed within square brackets [].
• We can use slice [:] operators to access the data
of the list.
• The concatenation operator (+) and repetition
operator (*) works with the list in the same way
as they were working with the strings.
Lists - Example
Create a list as with the items as 1, hi, python, 2 and
perform the following to display the output as
mentioned in the screenshot..
• Display the third item from the list.
• Display first 3 items from the list.
• Display the entire list.
• Use the concatenation operator for the list.
• Display the list twice in a single line.
List Example
Operations on List

Length Extend
Append Reverse
Count Sort
Sequence
Examples on List Functions and
Methods
1. Create two lists.
2. Find the length of a List.
3. Append both the lists.
4. Count the occurrence of a item in the list.
5. Extend a specific list.
6. Reverse a specific list.
7. Sort the list created.
8. Convert a list in the form of a tuple.
Solution - Example
Solution - Example
Tuples

• A tuple is similar to the list in many ways.


• Like lists, tuples also contain the collection of the
items of different data types.
• The items of the tuple are separated with a
comma (,) and enclosed in parentheses ().
• A tuple is a read-only data structure as we can't
modify the size and value of the items of a tuple.
Example
Assignment - 3

1. Convert a list into a tuple.


2. Perform following operations on a tuple:
a. Count
b. Append
c. Length
d. Extend
e. Sort
f. Convert a tuple into a list
Assignment -3 Solution
Assignment -3 Solution
Dictionary

• Dictionary is an ordered set of a key-value pair of


items.
• It is like an associative array or a hash table where
each key stores a specific value.
• Key can hold any primitive data type whereas
value is an arbitrary Python object.
• The items in the dictionary are separated with the
comma and enclosed in the curly braces {}.
Important points - Dictionary

● More than one entry per key is not allowed (


no duplicate key is allowed)
● The values in the dictionary can be of any
type while the keys must be immutable like
numbers, tuples or strings.
● Dictionary keys are case sensitive - Same
key name but with the different case are
treated as different keys in Python
dictionaries.
Exercise 6
Dictionary Operations

Following operations can be performed on a


dictionary:
1. Accessing Values
2. Updating
3. Deleting
Examples - Dictionary
Operations
Exercise 6

What is the output of the following code?

Solution:
1 5 10
Assignment - 4 - Dictionary

1. Create a dictionary as shown below:

2. Display
the following output using dictionary
methods, string and print function.
Solution - Assignment - 4
Assignment - 5
1. Create 5 list and assign data to it as shown
below. (Emp, Dept1, Dept2, HOD_CS, HOD_IT)
2. Write a python code to display the following
output.
Assignment 5 - Solution
Operators in Python
● Operators are used for performing various types
of operations on any given operand(s).
● In python, we have 7 different types of operators,
they are:
○ Arithmetic Operators
○ Comparison Operators
○ Assignment Operators
○ Logical Operators
○ Bitwise Operators
○ Membership Operators
○ Identity Operators
● While the first five are commonly used operators
the last two i.e. Membership and Identity.
Arithmetic Operators
Arithmetic operators are the operators used for
performing arithmetic operations on numeric
operands like division, subtraction, addition etc.
Comparison Operators
Assignment Operators

• The assignment operator is used to assign a specific


value to a variable or an operand.
• The equal to (=) operator is used to assign a value to
an operand directly.
Logical Operators

The logical operators are used to perform logical


operations (like and, or, not) and to combine two or
more conditions to provide a specific result i.e. true
or false.
Bitwise Operators
Bitwise operator acts on the operands bit by bit. These
operators take one or two operands. Some of the bitwise
operators appear to be similar to logical operators but they
aren’t.
Membership Operators

The membership operators are used to test whether


a value is in a specific sequence or not like in lists,
tuples, string, etc. It returns True or False as output.
Assignment-5

Write a Python program to calculate and display the


interest on a loan amount (Rupees) using the
formula:
interest=(principal * rate of interest * time)/100
Test your code by using the given sample inputs:
Solution-5

principal=7800
rate_of_interest=7.7
time=26
interest=0

interest = (principal * rate_of_interest * time)/100


print(interest)
Input and Output
Assignment - 6

1. Take 2 numbers as input from user.


2. Perform arithmetic operations (addition,
subtraction, multiplication, division)
3. Print the output of the operations.
Assignment - 6 Solution
Arrays in Python

• An array is defined as a collection of items that are stored


at contiguous memory locations.
• It is a container which can hold a fixed number of items,
and these items should be of the same type.
• Array operations:
• Traverse - It prints all the elements one by one.
• Insertion - It adds an element at the given index.
• Deletion - It deletes an element at the given index.
• Search - It searches an element using the given index
or by the value.
• Update - It updates an element at the given index.
Array Operations

1. Accessing array element:

2. Update or Add elements in array:


Array Operations (Cont..)

3.Deleting elements in an array:

4.Find length of an array:


Importing Modules and
Packages
• A module is a piece of software that has a specific
functionality.
• Modules in Python are simply Python files with a
.py extension.
• Use the import keyword to import a module.
• Various ways to import a module in python:
• Import using the import keyword.
• Import with renaming.
• Import using the from keyword
• Importing all (*) names from a module.
Examples - Import Module and
Packages
1. Import build in math module and display the
value of pi for the following operations.
a. Import using the import keyword.
b. Import with renaming.
c. Import using the from keyword
d. Importing all (*) names from a module.
Solution - Import Module and
Packages
Difference between Modules
and Packages
NumPy Arrays

NumPy: Numerical Python

What and Why?


1. NumPy is a general-purpose array-processing
package.
2. It provides a high-performance multi-dimensional
array object, and tools for working with these
arrays.
3. It is the fundamental package for scientific
computing with Python.
Installing NumPy
Installing NumPy
Installing NumPy with pip
NumPy: ndarray

- The ndarray or multi-dimensional array is one of


the most important object in NumPy.
- A multi-dimensional array is an array of arrays.
- Example of multi-dimensional array:
Let’s do some coding now
Zeros function of NumPy
Creating a NumPy array from
List
List vs. Array in NumPy
Continued..

What is the
conclusion?
Summarising 1D arrays

- A numpy array is a grid of values, all of the same


type, and is indexed by a tuple of non-negative
integers.
- The number of dimensions is the rank of the
array;
- The shape of an array is a tuple of integers giving
the size of the array along each dimension.
Continued..
Creating 2D arrays using NumPy

Now, let’s look into how to create a two-dimensional


array using NumPy. Instead of passing the list now
we have to pass a list of tuples or list of lists.
Continued..
Can we create an array of float?
or bool?
Points:
To summarise, the main differences with python
lists are:
1. Arrays support vectorised operations, while lists
don’t.
2. Once an array is created, we cannot change its
size. We will have to create a new array or
overwrite the existing one.
3. Every array has one and only one dtype. All items
in it should be of that dtype.
4. An equivalent numpy array occupies much less
space than a python list of lists.
Inspecting the size and shape of
a NumPy array
Let’s suppose you were handed a numpy vector that
you didn’t create yourself. What are the things you
would want to explore in order to know about that
array?
Continued..

1. If it is a 1D or a 2D array or more. (ndim)


2. How many items are present in each dimension
(shape)
3. What is its datatype (dtype)
4. What is the total number of items in it (size)
5. Samples of first few items in the array (through
indexing)
Continued..
Extract specific items from an
array: Slicing
- We can extract specific portions on an array using
indexing starting with 0, something similar to how
you would do with python lists.
- But unlike lists, numpy arrays can optionally
accept as many parameters in the square
brackets as there is number of dimensions.
Reverse the rows and the whole
array
Compute mean, min, max on the
ndarray
Homework Assignment

Can we find min, max, mean row-wise or column-


wise?
If yes, how it can be done?
Pandas Dataframe
• Pandas DataFrame is two-dimensional size-
mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns).
• Pandas DataFrame consists of three principal
components, the data, rows, and columns.
Creating a Dataframe using List

• Pandas DataFrame can be created from the lists,


dictionary, and from a list of dictionary etc.
• Let us create a Dataframe which displays the
following output:
Example Code
Creating a Dataframe using a
Dictionary
• To create DataFrame from dict of narray/list, all
the narray must be of same length.
• If index is passed then the length index should be
equal to the length of arrays.
• If no index is passed, then by default, index will
be range(n) where n is the array length.
• Let us create a Dataframe which displays the
following output:
Example Code
Column Selection in Data Frames

Define a dictionary containing employee data (Name,


Age, Address, Qualification) and display only the
Employee N
ame and Qualification.
Expected Output:
Example Solution
THANK YOU

You might also like