DATA ANALYTICS
PYTHON BASICS
❏ What is Python?
● Python is a popular programming language.
● Python is a widely used general-purpose, high-level
programming language.
● It is used for web development(server-side),software
development,system scripting ,data science, data
analytics etc.
● It is derived from many other languages including
C,C++, java etc.
❏ Why Python is Popular?
● Simple English-like syntax
● Large community support
● Huge collection of libraries
● Cross-platform (Windows, Linux, Mac)
● Used by top companies.
❏ History of Python
● Created by Guido van Rossum
● First released in 1991
● Named after Monty Python .
● Currently maintained by Python
Software Foundation.
➢ Why Python called Python?
The inspiration for the name came
from the BBC’s TV Show
‘ Monty Python’s Flying Circus’.
❏ Features of Python
● Easy-to-learn
● Simple syntax
● Easy-to-read
● Easy-to-maintain
● Open source & free
● Interpreted language
● Portable: works on different platforms
● Dynamically typed language
● Large standard library
❏ Applications of Python
● Web Development (Django, Flask)
● Data Science & Machine Learning
● Artificial Intelligence
● Automation & Scripting
● Game Development
❏ Python in Real Life
● Netflix: Recommendation system
● Google: Backend services
● Amazon: Product analysis
● Instagram: Image processing
❏ Evolution of Python
● The language was finally released in 1991.
● Following are the illustrations of different versions of
Python along with the timeline.
● The latest stable release of Python is Python 3.14 , with
version 3.14.2 being the most recent update as of late
2025/early 2026 .
❏ Python 2 vs Python 3 :Key difference
● What is Python 2?
Python 2 made code development process easier than earlier versions. It
implemented technical details of Python Enhancement Proposal (PEP). Python 2.7
(last version in 2.x ) is no longer under development and in 2020 will be
discontinued.
● What is Python 3?
On December 2008, Python released version 3.0. This version was mainly
released to fix problems which exist in Python 2. The nature of these change is
such that Python 3 was incompatible with Python 2. It is backward incompatible
Some features of Python 3 have been backported to Python 2.x versions to make
the migration process easy in Python 3.
❏ VARIABLES IN PYTHON
● Variables are containers for storing data values.
● Unlike other programming languages, Python has no command
for declaring a variable.
● A variable is created the moment you first assign a value to it.
eg:
a=19
b=”hello”
print (a)
print (b)
➢ Rules for Python variables:
● A variable name must start with a letter or the underscore
character .
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are
three different variables).
● Variables do not need to be declared with any particular type
and can even change type after they have been set.
● The reserved words(keywords) in Python cannot be used to
name the variable in Python.
● String variables can be declared either by using single or double
quotes.
● Python allows you to assign values to multiple variables in one
line.
Eg : a, b, c = 10, 20, 30 , x = y = z = 5
➢ Global variable and Local variables in Python
Local Variables:
Local variables in Python are the ones that are defined and declared
inside a function. We cannot call this variable outside the function.
Global Variables:
Global variables in Python are the ones that are defined and declared
outside a function ,and we need to use them inside a function.
❏ Escape sequences
● Special character combinations that are used to represent
characters which are difficult or impossible to type directly.
● They start with a ‘\’ .
\n - new line
\t - tab space
\b - backspace
\\ - literal backslash
➢ print() in Python :
The print() function prints the specified message to the screen.
Syntax:
print(object(s), separator=separator, end=end, file=file, flush=flush)
object(s) Any object, and as many as you like.
separator-Optional. Specify how to separate the objects. Default value is white space
end-Optional. Specify what to print at the end. Default value is ‘\n’
file - Optional. An object with a write method
flush - Optional.A Boolean, specifying if the output is flushed or buffered
❏ KEYWORDS IN PYTHON
● Keywords are reserved words in Python
● They have special meaning
● Cannot be used as variable names.
➢ Common Python Keywords
● True, False
● if, else, elif
● for, while
● break, continue
● def, return
● class
❏ DATA TYPES IN PYTHON
● The data stored in memory can be of many types.
● For example, a person's age is stored as a numeric value and
his or her address is stored as alphanumeric characters.
● Python has various standard data types that are used to define
the operations possible on them and the storage method for
each of them.
● It represents the kind of value that tells what operations can
be performed on a particular data.
➢ The following are the standard or built-in data types in
Python:
● Numeric datatype
● Sequence Type
● Boolean datatype
● Set
● Dictionary
● Binary Types
➢ Example:
x = 10 # int
y = 3.14 # float
name = "Python" # str
➢ What is Python Data Types?
To define the values of various data types of Python and
check their data types we use the type() function .
➢ Why Data Types are Important?
● Memory management
● Correct operations
● Avoid runtime errors
● Data processing accuracy
❖ Numeric Data Types:
● Integers, floating point numbers and complex numbers falls
under Python numeric type category.
● They are defined as int, float and complex class in Python.
● Integers can be of any length, it is only limited by the memory
available.
● A floating point number is accurate up to 15 decimal places.
● Integer and floating points are separated by decimal points.
● 1 is integer, 1.0 is floating point number.
● Complex numbers are written in the form, x + yj, where x is the
real part and y is the imaginary part.
● Here is an example,
a = 5 print("Type of a: ", type(a))
b =5.0 print("\n Type of b: ", type(b))
c = 2+4j print("\n Type of c: ", type(c))
Output :
Type of a: < class ‘int’>
Type of b: < class ‘float’>
Type of c: < class ‘complex’>
❖ Sequence Data Types:
● The sequence Data Type in Python is the ordered collection of
similar or different Python data types.
● Sequences allow storing of multiple values in an organized and
efficient fashion.
● There are several sequence data types of Python:
■ Python String
■ Python List
■ Python Tuple
■ Range
● Stringsin Python are identified as a contiguous set of characters
represented in the quotation marks.
Python allows for either pairs of single or double quotes.
● List is a collection which is ordered and changeable.
Allows duplicate members.
● Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
● The range() type returns an immutable sequence of numbers between
the given start integer to the stop integer.
Eg :
1. str = 'Hello World!'
print str # Prints complete string
Output:Hello World!
2. List = ['Red',’White’,’Blue’,’Black’]
print(List)
Output:['Red',’White’,’Blue’,’Black’]
3. Tuple1 = (0, 1, 2, 3)
Tuple2 = ('black', 'blue')
print(Tuple1)
print(Tuple2)
Output:
(0, 1, 2, 3)
('black', 'blue')
4. range(1, 10) - Used to generate sequence of numbers
❖ Boolean Data Types:
The bool() method is used to return or convert a value to a Boolean
value. i.e., True or False, using the standard truth testing procedure.
Syntax: bool([x])
➢ The bool() method in general takes only one parameter(here x),on which the
standard truth testing procedure can be applied.
➢ If no parameter is passed, then by default it returns False. So, passing a
parameter is optional. It can return one of the two values.
● It returns True if the parameter or value passed is True.
● It returns False if the parameter or value passed is False.
Eg:
print(type(True))
print(type(False))
print(type(true)
Output:
< class ‘bool’>
< class ‘bool’>
NameError: name 'true' is not defined
❖ Set Data Types:
● A Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements.
● The order of elements in a set is undefined though it may
consist of various elements.
● The major advantage of using a set, as opposed to a list, is
that it has a highly optimized method for checking whether a
specific element is contained in the set.
Eg : a = {1, 2, 3}
❖ Dictionary Data Type:
A dictionary in Python is an unordered collection of data values,
used to store data values like a map.
● Key-value pairs
● Unordered
Eg:
student = {"name": "Hari", "age": 25}
❖ Binary Types :
● bytes and bytearray are used for manipulating binary data.
● The Bytes type in Python is immutable and stores a sequence of
values ranging from 0-255 (8-bits).
● You can get the value of a single byte by using an index like an
array, but the values can not be modified.
● It is defined like a string with a ‘b’ as its prefix.
❏ OPERATORS IN PYTHON
Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical
and arithmetic operations.
➔ OPERATORS:These are the special symbols. Eg- + , * , /, etc.
OPERAND:It is the value on which the operator is applied.
➢ Python divides the operators into six groups,
➢ Types of Operators in Python
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Identity Operators
6. Membership Operators
❖ Arithmetic Operators :
Arithmetic operators are used with numeric values to perform
common mathematical operations.
Operator Name Example
+ Addition x+y
Subtraction x-y
-
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Eg:
a = 10
b=3
print(a + b) print(a % b) print(a ** b)
❖ Assignment Operators :
Assignment operators are used to assign values to variables.
Operator Example Same as
= x=5 x=5
+= x += 5 x = x+5
-= x -= 5 x = x-5
*= x *= 5 x = x*5
/= x /= 5 x = x/5
%= x %= 5 x = x%5
//= x //= 5 x = x//5
**= x **= 5 x = x**5
❖ Comparison Operators :
Comparison operators are used to compare two values.
Operator Name Example
== Equal x==y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x>=y
<= Less than or equal to x<=y
❖ Logical Operators:
Logical operators are used to combine conditional statement.
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, not(x < 5 and x < 10)
returns False if the result
is true
❖ Identity Operators:
Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory
location.
Operator Description Example
is Returns True if both variables x is y
are the same object
is not Returns True if both variables x is not y
are not the same object
❖ Membership Operators:
Membership operators are used to test if a sequence is present in an
object.
Operator Description Example
in Returns True if a sequence with the x in y
specified value is present in the
object
not in Returns True if a sequence with the x not in y
specified value is not present in the
object
❏ USER INPUT IN PYTHON
➢ Most programs today use a dialog box as a way of asking the user to
provide some type of input.
➢ While Python provides us with two inbuilt functions to read the input
from the keyboard.
● raw_input ( prompt )
● input ( prompt )
❖ raw_input( ) :
● This function works in older version (like Python 2.x).
● This function takes exactly what is typed from the keyboard, convert it to
string and then return it to the variable in which we want to store.
g = raw_input("Enter your name : ")
print g
Output:
Enter your name : python
python
❖ input( ) :
This function first takes the input from the user and then evaluates the
expression, which means Python automatically identifies whether user
entered a string or a number or list. If the input provided is not correct then
either syntax error or exception is raised by python.
val = input("Enter your value: ")
print(val)
Output:
Enter your value:123
123
❏ DECISION MAKING STATEMENTS
Decision making statements in programming languages decides the direction
of flow of program execution. Decision making statements available in
python are:
1. The if statement
2. The if-else statement
3. The nested-if statement
4. The if-elif-else ladder
❖ if statement:
● if statement is the most simple decision making statement.
● It is used to decide whether a certain statement or block of statements
will be executed or not .
● i.e if a certain condition is true then a block of statement is executed
otherwise not.
● Syntax:
if condition:
# Statements to execute if
# condition is true
Eg:
a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
b is greater than a
❖ if -else statement:
● The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it
won’t.
● But what if we want to do something else if the condition is
false.
● Here comes the else statement.
● We can use the else statement with if statement to execute a
block of code when the condition is false.
● Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Eg:
i = 20
if (i < 15):
print ("i is smaller than 15")
else:
print ("i is greater than 15")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
❖ if-elif-else statement:
● The elif keyword is pythons way of saying "if the previous conditions
were not true, then try this condition".
● A user can decide among multiple options.
● The if statements are executed from the top down.
● As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder
is bypassed.
● If none of the conditions is true, then the final else statement will be
executed.
● Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Eg:
a = 33
b = 33
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
else: Output:
print(“a is greater than b”)
a and b are equal
❖ Nested-if statement:
● A nested if is an if statement that is the target of another if
statement.
● Nested if statements means an if statement inside another if
statement.
● Python allows us to nested if statements within if statements.
● i.e, we can place an if statement inside another if statement.
● Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Eg:
i = 10
if (i == 10):
if (i < 15):
print ("i is smaller than 15")
if (i < 12):
print ("i is smaller than 12 too")
Output:
else: i is smaller than 15
i is smaller than 12 too
print ("i is greater than 15")
❏ LOOPING STATEMENTS
➢ What is a Loop?
■ A loop is used to execute a block of code repeatedly
■ Reduces code repetition
■ Saves time and effort
➢ Why Loops are Required?
● Avoid duplicate code
● Handle large data
● Automation
● Improve efficiency
➢ Types of Loops in Python
● for Loop
● while Loop
❖ for loop:
A for loop is used for iterating over a sequence (that is either a list,
a tuple, a dictionary, a set, or a string).
Syntax:
for iterating_variable in sequence:
Eg :
for i in range(0,6):
print (i)
Eg:
fruits = ["Apple", "Banana", "Cherry"]
for x in fruits:
print(x)
Output:
Apple
Banana
Cherry
❖ while loop:
With the while loop we can execute a set of statements as long as a condition is
true.
Syntax: While condition:
statement
Eg:
count = 0
Output : Hello World
while (count < 3):
Hello World
count = count + 1
Hello World
print("Hello World")
Eg:
Output:
count = 0 0
1
while (count < =10): 2
3
print(count) 4
5
count = count + 1 6
7
8
9
10
❖ Loop Control Statements:
Loop control statements change execution from its normal
sequence. When execution leaves a scope, all automatic objects that
were created in that scope are destroyed. Python supports the following
control statements:
● Continue Statement
● Break Statement
● Pass statement
➢ Continue Statement
● It returns the control to the beginning of the loop.
● With the continue statement we can stop the current iteration of the loop, and continue
with the next.
Eg:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
Output:
if x == "banana":
apple
continue
print(x) cherry
➢ Break Statement
With the break statement we can stop the loop before it has looped through all the
items.
Eg:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
if x == "banana": apple
Break banana
➢ Pass Statement
● The pass statement in Python is used when a statement is required syntactically
but you do not want any command or code to execute.
● The pass statement is a null operation; nothing happens when it executes.
● The pass is also useful in places where your code will eventually go, but has
not been written yet .
Eg:
a = 33
b = 200
if b > a:
pass # having an empty if statement like this, would raise an error
without the pass statement.
❏ STRING
● Python string is a sequence of Unicode characters that is enclosed in
quotation marks.
● Python has a set of built-in methods that you can use on strings.
● All string methods returns new values. They do not change the
original string.
● Every string method does not change the original string instead
returns a new string with the changed attributes.
❖ Case Changing of Strings
The below functions are used to change the case of the strings.
● lower(): Converts all uppercase characters in a string into
lowercase
● upper(): Converts all lowercase characters in a string into
uppercase
● title(): Convert string to title case
● swapcase(): Swap the cases of all characters in a string
● capitalize() : Convert the first character of a string to uppercase
❖ STRING FUNCTIONS
● count() returns the number of times a specified value appears in the string .
Eg: string = ‘celebrate’
print([Link](‘e’))
print([Link](‘e’, 4)) # start index (4)
print([Link](‘e’, 4 ,7)) #start and end index; default end of the string
● center() center align the string,
● startswith() returns True if the
using a specified character (space is
string starts with the specified value
default) as the fill character.
Eg: string = ‘Python’ Eg: txt = "My name is Sam“
print([Link](15,’*’)) print([Link](‘M'))
Output: *****Python**** print([Link]('m',5)) # start index
● swapcase() Make the lower case
● endswith() returns True if the letters upper case and the upper case
string ends with the specified value, letters lower case
otherwise False.
Eg:print('WindoWs'.swapcase())
Eg: txt = "My name is Sam“
print([Link]('m'))
print([Link]('m',1,5))
# (start index, end index)
● casefold() converts string into ● isalnum() check if all the
lower case; for caseless matching characters in the text is
alphanumeric
of unicode characters
Eg: txt = "Company12“
Eg: Print(“Hello World”.casefold()) txt1 = "Company 12"
print([Link]())
Output: hello world print([Link]())
● capitalize() converts the first
● isalpha() returns True if all the
character to uppercase characters are alphabet letters
Eg: string = ‘learn’ Eg: txt = "Company“
txt1 = "Company 12"
[Link]() print([Link]())
print([Link]())
● isnumeric() returns True if all ● isdigit() returns True if all the
the characters are numeric (0-9, characters are digits, otherwise
subscripts etc, False; supports subscripts,
Eg: superscripts etc.
a = "\u0030" #unicode for 0 Eg:
b = "\u00B2" #unicode a = "\u0030" #unicode for 0
for² b = "\u00B2" #unicode for ²
c = "10km2" print([Link]())
d = "-1" print([Link]())
print([Link]()) Output: True
print([Link]()) True
print([Link]())
print([Link]())
● islower() check if all the ● isspace() check if all the
characters in the text are in characters in the text are whitespaces
lower case
● isidentifier() check if the string is
a valid identifier
● isupper() check if all the
characters in the text are in
● istitle() check if each word start
upper case with an uppercase letter
Eg:
● isprintable() returns True if print(‘Check Whether This Is A
all the characters are printable Title’.istitle())
Eg:
print('hello\n'.isprintable())
❏ COLLECTION DATA TYPES IN PYTHON
❖ LIST:
A list is a collection which is ordered and changeable.
● A list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
● It can have any number of items and they may be of different types
(integer, float, string etc.).
● A list can even have another list as an item.
● List can have duplicate values. ● Items can be accessed with index.
➢ LIST-Creation
● empty list
my_list = []
● list of integers
my_list = [1, 2, 3]
● list with mixed data types
my_list = [1, "Hello", 3.4]
● nested list
my_list = ["mouse", [8, 4, 6], ['a']]
➢ How to access elements from a list?
● We can use the index operator [] to access an item in a list.
● Index starts from 0. So, a list having 5 elements will have index from
0 to 4.
● Trying to access an element other than that this will raise an
IndexError.
● The index must be an [Link] can’t use float or other types,this
will result into TypeError.
● Nested list are accessed using nested indexing.
my_list = ['p','r','o','b','e']
● print(my_list[0]) - Output: p
● print(my_list[2]) - Output: o
● print(my_list[4]) - Output: e
● my_list[4.0] – Output : Error! Only integer can be used for
indexing
n_list = ["Happy", [2,0,1,5]] – Nested list
● print(n_list[0][1]) - Output: a
● print(n_list[1][3]) – Output 5
➢ How to slice lists in Python?
We can access a range of items in a list by using the slicing operator(colon).
my_list = ['p','r','o','g','r','a','m','i','z']
● print(my_list[2:5]) #index 2nd to 4th (4th=n-1) Output : ['o', 'g', 'r']
● print(my_list[:-5]) #index 0 to 3rd Output : ['p', 'r', 'o', 'g']
● print(my_list[5:]) #index 5th to end Output : ['a', 'm', 'i', 'z']
● print(my_list[:]) #all elements Output : ['p', 'r', 'o', 'g', 'r', 'a',
'm', 'i', 'z']
➢ Negative indexing
Python allows negative indexing for its sequences.
● The index of -1 refers to the last item,
● -2 to the second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1]) - Output : e
print(my_list[-5]) - Output : p
➢ How to change or add elements to a list?
● List are mutable, meaning, their elements can be changed unlike string or
tuple.
● We can use assignment operator (=) to change an item or a range of items.
★ odd = [2, 4, 6, 8]
➔ odd[0] = 1 # change the 1st item
print(odd) Output: [1, 4, 6, 8]
➔ odd[1:4] = [3, 5, 7] # change 2nd to 4th items
print(odd) Output: [1, 3, 5, 7]
● len() – to find the length of a list
● append() – add one item to a list at the end
● extend() – add several items to a list at the end
➢ odd = [1, 3, 5]
● [Link](7)
print(odd) Output: [1, 3, 5, 7]
● [Link]([9, 11, 13])
print(odd) Output: [1, 3, 5, 7, 9, 11, 13]
● insert() – insert an item in a desired location
odd = [1, 9]
[Link](1,3)
print(odd) Output: [1, 3, 9]
● insert multiple items by squeezing it into an empty slice of a list.
odd[2:2] = [5, 7]
print(odd) Output: [1, 3, 5, 7, 9]
➢ How to delete or remove elements from a list?
● Delete one or more items using the keyword ‘del’.
● This can also delete the entire list.
my_list = ['p','r','o','b','l','e','m']
del my_list[2] #delete one item in the index position 2
print(my_list) Output: ['p', 'r', 'b', 'l', 'e', 'm']
● Delete multiple items
del my_list[1:5] # delete multiple items (index 1 to 4)
print(my_list) Output: ['p', 'm']
● Delete entire list
del my_list print(my_list) # Error: List not defined
● we can also delete items in a list by assigning an empty list to a slice of
elements.
➔ my_list = ['p','r','o','b','l','e','m']
my_list[2:3] = []
print(my_list) Output : ['p', 'r', 'b', 'l', 'e', 'm']
my_list[2:5] = []
print(my_list) Output : ['p', 'r', 'm']
● remove() – to remove a given item
➢ my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list) Output: ['r', 'o', 'b', 'l', 'e', 'm']
● pop() - to remove an item at the given index. pop() removes and
returns the last item if index is not provided.
print(my_list.pop(1)) Output: 'o‘
print(my_list) Output: ['r', 'b', 'l', 'e', 'm']
print(my_list.pop())
Output: 'm‘
print(my_list)
Output: ['r', 'b', 'l', 'e']
● clear() - clear all elements of an entire list
my_list.clear()
print(my_list)
Output: []
More List Operations :
● a = list(range(5)) # [0,1,2,3,4]
● [Link]() # [4,3,2,1,0]
● [Link]() # [0,1,2,3,4] sorts in ascending order
● my_list = [3, 8, 1, 6, 0, 8, 4]
print(my_list.index(8)) #returns the first matching index position of
the specified item.
Output: 1
● print(my_list.count(8)) #returns the no. of occurrence of the item.
Output : 2
❖ TUPLE :
● A tuple in Python is similar to a list.
● The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas, in a list, elements
can be changed.
● A tuple is a collection which is ordered and unchangeable.
● A tuple is created by placing all the items (elements) inside
parentheses (), separated by commas.
● The parentheses are optional, however, it is a good practice to use
them.
● A tuple can have any number of items and they may be of different
types (integer, float, list, string, etc.).
● Empty tuple : ● Tuple with mixed data types :
my_tuple = (1, "Hello", 3.4)
my_tuple = ()
print(my_tuple)
print(my_tuple) Output: (1, "Hello", 3.4)
Output: () ● Nested tuple :
my_tuple = (“mouse”, [8, 4, 6], (1,
● Tuple having integers : 2, 3))
print(my_tuple)
my_tuple = (1, 2, 3)
Output: ("mouse", [8, 4, 6], (1,
print(my_tuple) 2, 3))
Output: (1, 2, 3)
➢ How to access tuple elements?
1. Indexing
● Use the index operator [] to access an item in a tuple where the index
starts from 0.
● A tuple having 6 elements will have indices from 0 to 5.
● Trying to access an element outside of tuple will raise an TypeError.
IndexError. The index must be an [Link] can’t use float or other
types,this will result into.
● Nested tuples are accessed using nested indexing.
my_tuple = ('p','e','r','m','i','t')
● print(my_tuple[0]) Output : 'p'
● print(my_tuple[5]) Output : 't‘
● print(my_tuple[6]) Output : IndexError: list index out of range .
● my_tuple[2.0] Output : TypeError: list indices must be integers,
not float.
● n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) #nested tuple
print(n_tuple[0][3]) # nested index
Output : ‘s’
● n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) #nested tuple
print(n_tuple[0][3]) # nested index
Output : ‘s’
print(n_tuple[1][1])
Output : 4
2. Negative Indexing
● The index of -1 refers to the last item, -2 to the second last item and so
on.
● Same as that of list.
3. Slicing
● We can access a range of items in a tuple by using the slicing operator
colon ":".
● This is also similar to list.
➢ Changing a Tuple
● Unlike lists, tuples are immutable.
● This means that elements of a tuple cannot be changed once it has been
assigned.
● But, if the element is itself a mutable data type like list, its nested items can
be changed.
● We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, [6, 5])
● my_tuple[1] = 9
Output :-TypeError: 'tuple' object does not support item assignment
● my_tuple[3][0] = 9 #However, item of mutable element can be changed
print(my_tuple) Output: (4, 2, 3, [9, 5])
● my_tuple = ('p','r','o','g','r','a','m','i','z') #Tuples can be reassigned
print(my_tuple)
Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
● Concatenation – use + operator to combine two tuples
● We can also repeat the elements in a tuple for a given number of times
using the * operator
Eg:
print((1, 2, 3) + (4, 5, 6)) # Concatenation
Output : (1, 2, 3, 4, 5, 6)
print(("Repeat") * 3)
Output : ('Repeat', 'Repeat', 'Repeat')
❖ SET :
● A set is a collection which is unordered and unindexed.
● In python, sets are written with curly brackets.
Eg:
set1={“apple”,”banana”,”cherry”}
print(set1)
Output:{‘cherry,’apple’,’banana’}
● Sets are unordered,so you cannot be sure in which order of the items
will appear.
➢ How to access elements of a set?
● We cannot access items in a set by referring to an index, since sets are
unordered and the items has no index.
● But you can loop through the set items using a for loop.
Eg:
set1={“apple”,”banana”,”cherry”)
for x in set1:
print(x)
➢ How to change elements in a set?
Once a set is created, you cannot change its items, but you
can add new items.
➢ How to add elements in a set?
● To add one element to a set use the add() method.
● To add more than one element to a set use the update()
method.
my_set={1,3}
● my_set.add(2) #adding element 2 in my_set
print(my_set) Output:{1,2,3}
● my_set.update([2,3,4]) #adding list using update
print(my_set) Output:{1,2,3,4}
● my_set.update([4,5],{1,6,8}) #adding list and set
print(my_set) output:{1,2,3,4,5,6,8}
●my_set1={“sads”,”wdww”,”bghd”}
my_set1.update([“cdf”,”wds”])
print(my_set1) output:{‘bghd’,wds’,’cdf’,’wdww’,’sads’}
➢ How to get the length of a set?
To determine how many items a set has,use the len() method.
● set1={“xyz”,”abc”}
print(len(set1)) Output:2
➢ How to remove an element from a set?
To remove an element in a set,use the remove(),or the discard() method.
● The difference between the two is that,while using discard() if the item does
not exist in the set,it remains unchanged.
● But remove() will raise an error in such condition.
set1={1,3,4,5,6}
● [Link](4)
print(set1) Output:{1,3,5,6}
● [Link](2)
print(set1) Output:Error 2 not in the set
Similarly we can remove and return an item using pop() method.
● s={1,2,3)
print([Link]()) Output:2
➢ Set be unordered,there is no way of determining which item will be
[Link] is completely arbitrary .
➢ We can also remove all items from a set using clear() .
Eg ,
s={1,2,3,4,5}
[Link]()
print(s)
Output:set()
❖ DICTIONARY :
● Dictionary is an ordered collection of items.
● While other compound data types have only value as an element, a
dictionary has a key: value pair.
● Dictionaries are optimized to retrieve values when the key is known.
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
print(thisdict)
output:{‘brand’:’Ford’,’model’:’mustang’,’year’:1964}
➢ How to create a dictionary?
● Creating a dictionary is as simple as placing items inside curly braces
{} separated by comma.
● An item has a key and the corresponding value expressed as a pair,
key: value.
● While values can be of any data type and can repeat, keys must be of
immutable type ( string ,number or tuple with immutable elements)
and must be unique.
my_dict = {'name':'Jack', 'age': 26}
● update value
my_dict['age'] = 27
print(my_dict) Output: {'name':'Jack', 'age': 27}
● add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output: { 'name': 'Jack', ‘age': 27, ’address': 'Downtown'}
➢ How to delete or remove elements from a dictionary?
● We can remove a particular item in a dictionary by using the method
pop().
● This method removes as item with the provided key and returns the value.
● The method, popitem() can be used to remove and return the last item
(key, value) from the dictionary.
● All the items can be removed at once using the clear() method.
● We can also use the del keyword to remove individual items or the entire
dictionary itself.
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
● print([Link](4)) # remove a particular item
Output: 16
● print(squares) Output: {1: 1, 2: 4, 3: 9, 5: 25}
●print([Link]()) # removes the last item
Output: (5, 25)
● print(squares) Output: {1:1, 2: 4, 3: 9}
● del squares[1] # delete a particular item
● print(squares) Output: {2: 4, 3: 9}
● [Link]() # remove all items
print(squares)
Output: {}
● del squares # delete the dictionary itself
❏ FUNCTION
● A function is a block of code which only runs when it is called.
● You can pass data, known as parameters, into a function.
● A function can return data as a result.
➢ Creating a Function:
In Python a function is defined using the def keyword .
def my_function():
print("Hello from a function")
➢ Calling a Function:
To call a function, use the function name followed by parenthesis
Eg;
def my_function():
print("Hello from a function")
my_function()
Output: Hello from a function
❖ ARGUMENTS AND PARAMETERS
● Information can be passed into functions as arguments.
● Arguments are specified after the function name, inside the parentheses.
● You can add as many arguments as you want, just separate them with a
comma.
● Arguments are often shortened to args in Python documentations.
● The terms parameter and argument can be used for the same thing:
information that are passed into a function.
● From a function's perspective a parameter is the variable listed inside the
parentheses in the function definition.
● An argument is the value that are sent to the function when it is called.
● The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name,
Eg: def my_function(fname):
print(fname + " Tom")
my_function("Emil") Output:
Emil Tom
my_function("Tobi") Tobi Tom
my_function("Linus") Linus Tom
❖ Types of Arguments
The arguments can be divided into 4 categories,
● Number of Arguments
● Arbitrary Arguments, *args
● Keyword Arguments
● Arbitrary Keyword Arguments, **kwargs
➢ Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
Eg: def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Tom")
Output:Emil Tom
➢ Arbitrary Arguments, *args
● If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
● This way the function will receive a tuple of arguments, and can access the
items accordingly.
● Arbitrary Arguments are often shortened to *args in Python documentations.
Eg: def my_function(* kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Output:The youngest child is Linus
➢ Keyword Arguments
● You can also send arguments with the key = value syntax.
● This way the order of the arguments does not matter.
eg: def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Output: The youngest child is Linus
➢ Arbitrary Keyword Arguments, **kwargs
● If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the function
definition.
● This way the function will receive a dictionary of arguments, and can access
the items accordingly.
Eg: def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobi", lname = "Tom")
Output:His last name is Tom
❖ Return Values :
To let a function return a value, use the return statement:
Eg: def my_function(x):
return 5 * x
print(my_function(3)) Output:
15
print(my_function(5)) 25
45
print(my_function(9)
❖ Recursion:
● Python accepts function recursion, which means a defined
function can call itself.
● Recursion is a common mathematical and programming
concept. It means that a function calls itself.
● This has the benefit of meaning that you can loop through
data to reach a result.
Eg:
def number(n): Output:
10
if n==0: #base condition 9
return 8
7
else:
6
print(n) 5
number(n-1) #function call 4
3
number(10) 2
1
❏ ANONYMOUS FUNCTION(LAMBDA FUNCTION)
In Python, 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.
Hence, anonymous functions are also called lambda functions.
Syntax of Lambda Function in python:
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.
Eg: double = lambda x: x * 2
print(double(5))
Output: 10
● In the 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 identifier
double.
● We use lambda functions when we require a nameless
function for a short period of time.
● Lambda functions are used along with built-in functions like ,
○ filter()
○ map()
○ reduce()
❖ filter()
● The filter() function in Python takes in a function and a list as arguments.
● The function is called with all the items in the list and a new list is
returned which contains items for which the function evaluates to True.
Eg: my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output: [4, 6, 8, 12]
❖ map()
● The map() function in Python takes in a function and a list.
● The function is called with all the items in the list and a new list is
returned which contains items returned by that function for each item.
eg:my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Output: [2, 10, 8, 12, 16, 22, 6, 24]
❖ reduce()
● The reduce() function in Python takes in a function and a list as
argument.
● The function is called with a lambda function and a list and a new
reduced result is returned.
● This performs a repetitive operation over the pairs of the list.
● This is a part of functools module.
Eg: from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
Output:193
print (sum)
❏ MODULES IN PYTHON
● Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a
file is called a module.
● Definitions from a module can be imported into other
modules.
● A module is a file containing Python definitions and
statements. The file name is the module name with the suffix
.py appended.
➢ Standard Modules:
● Python's standard library is very extensive, offering a
wide range of functionalities.
● Python 3's standard modules such as the statistic module,
the math module and the random module.
➢ Statistics Module:
This module provides functions for calculating mathematical statistics
of numeric (Real-valued) data. Some of the most commonly used
functions of the module are:
● mean(): Arithmetic mean ('average') of data.
import statistics
A = [5,10,6,21,5,17,14,8,3,9]
mean = [Link](A)
print('The mean of A is ', mean)
Output: The mean of A is 9.8
● median(): Median (middle ● median_low(): Low median of the
value) of data. data is the lower of two middle values
when the number of data elements is
import statistics even, else it is the middle value.
B = [1,7,13,24,35,37,42,44,53,55] import statistics
median = [Link](B) B = [1,7,13,24,35,37,42,44,53,55]
low_median =
print('Median of B is:', median) statistics.median_low(B)
print('Low Median of B is:',
Output: Median of B is: 36.0 low_median)
Output: Low Median of B is: 35
● median_high(): High median of ● mode(): Mode (most common
the data is the larger of two middle value) of discrete data.
values when the number of data
elements is even, else it is the import statistics
middle value. C = [1,1,2,2,2,2,4,4]
most_common_item =
import statistics [Link](C)
B = [1,7,13,24,35,37,42,44,53,55] print('The most common item of C
high_median = is:', most_common_item)
statistics.median_high(B) Output:
print('High Median of B is:', The most common item of C is: 2
high_median)
Output:
High Median of B is: 37
● variance(): Return the sample variance of data, an iterable of at
least two real-valued numbers. Variance measures the spread of
data. A low variance indicates that all the data is clustered around
the mean and a high variance indicates that the data is spread out.
import statistics
A = [5,10,6,21,13,17,14,8,3,9]
variance = [Link](A)
print('The variance of A is:', variance)
Output: The variance of A is: 31.822222222222226
● stdev() : Return the sample standard deviation (the square root of the
sample variance).
import statistics
A = [5,10,6,21,13,17,14,8,3,9]
std = [Link](A)
print('The std of A is:', std)
Output: The std of A is: 5.641118880348315
➢ Math Module:
This module provides access to the mathematical functions defined by
the C standard. Some of the most commonly used functions of the
module are:
● sqrt(x): Return the square root of x.
import math
x = 81
print('The square root of', x, 'is', [Link](x))
Output: The square root of 81 is 9.0
● fabs(x): Returns the absolute ● ceil(x): Return the ceiling of x,
value of x . the smallest integer greater than or
equal to x.
import math
x = -5 import math
print('The fabs of', x, 'is', x = 5.6
[Link](x)) print('The ceil of', x, 'is',
[Link](x))
Output: The fabs of -5 is 5
Output: The ceil of 5.6 is 6
● floor(x): Return the floor of ● factorial(x): Return x factorial.
x, the largest integer less than
or equal to x. import math
x=6
import math print('The factorial of', x, 'is:',
x = 5.6 [Link](x))
print('The floor of', x, 'is',
[Link](x)) Output: The factorial of 6 is:
720
Output: The floor of 5.6 is
5
● pow(x,y): Return x raised to ● exp(x): Return e raised to the power
the power y. x,
where e = 2.718281… is the base of
import math natural logarithms.
base = 2;
import math
x = 4; x=2
print(base, '^', x, '=', print('e ^', x,'=', [Link](x))
[Link](base,x))
Output:
Output: 2 ^ 4 = 16.0 e ^ 2 = 7.38905609893065
● log(x, base): With one argument, return the natural logarithm of x
(to base e). With two arguments, return the logarithm of x to the
given base.
import math
base = 2;
x = 16;
print('log of', x, 'to the base of', base, '=', [Link](x, base))
Output: log of 16 to the base of 2 = 4.0
● pi: This is actually the ● e: This is also the mathematical
mathematical constant constant
pi = 3.141592…, to available e = 2.718281…, to available precision.
precision.
import math
print('e value:', math.e)
import math
print('Pi value:', [Link]) Output:
Output: e value: 2.718281828459045
Pi value: 3.141592653589793
● radians(x): Convert angle x ● degrees(x): Convert angle x from
from degrees to radians. radians to degrees.
import math import math
print('Radians of 90 degrees:', print('Degrees of pi/2:',
[Link](90)) [Link]([Link]/2))
Output:
Radians of 90 degrees:
Output: Degrees of pi/2: 90.0
1.5707963267948966
➢ Random Modules:
This module implements pseudo-random number generators for various
distributions. Some of the most commonly used functions of the module
are:
● randint(a, b): Return a random integer x, which belongs to the range
[a,b].
import random
result = [Link](1, 11)
print('The random integer number in range [1,11] is:', result)
Output: The random integer number in range [1,11] is: 10
● shuffle():Shuffle the sequence x in place.
import random
X=list(range(1,11))
[Link](X)
print(‘Shuffled list:’,X)
Output:Shuffled list:[6,9,2,8,5,10,7,3,4,1]
● [Link](): Returns a randomly selected element from the
range created by the start, stop and step arguments. The value of start is 0
by default.
import random
● [Link](1,10) Output:2
● [Link](1,10,2) Output:5
● [Link](0,101,10) Output :80
➢ datetime module :
● The datetime module supplies classes for manipulating dates and times in
both simple and complex ways.
● choice(seq): Return a random element from the non-empty sequence seq.
import random
coin_side = [Link](['H','T'])
print('Flip a coin simulation using choice function. Result:', coin_side)
Output: Flip a coin simulation using choice function. Result: T
● While date and time arithmetic is supported, the focus of the
implementation is on efficient member extraction for output formatting
and manipulation.
● The module also supports objects that are timezone aware.
import datetime
x = [Link]()
print(x)
Output:2020-03-19 21:23:18.801745
● To create a date, we can use the datetime() class (constructor) of
the datetime module.
● The datetime() class requires three parameters to create a date:
year, month, day.
import datetime
x = [Link](2020, 5, 17)
print(x)
Output:2020-05-17 00:00:00
❏ PACKAGES IN PYTHON
● Python has packages for directories and modules for files. As a
directory can contain sub-directories and files, a Python package
can have sub-packages and modules.
● A directory must contain a file named __init__.py in order for
Python to consider it as a package.
● This file can be left empty but we generally place the
initialization code for that package in this file.
➢ Importing module from a package:
We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above
example, it is done as follows.
import [Link]
Now if this module contains a function named select_difficulty(), we
must use the full name to reference it.
[Link].select_difficulty(2)
If this construct seems lengthy, we can import the module without the
package prefix as follows.
from [Link] import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable)
form a module within a package would be as follows.
from [Link] import select_difficulty
Now we can directly call this function. select_difficulty(2)
THANK YOU…