0% found this document useful (0 votes)
3 views424 pages

Python Programming (7)

Uploaded by

amruthargowda009
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views424 pages

Python Programming (7)

Uploaded by

amruthargowda009
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Welcome to Python!

Content

• What Is Python?
• Python Features
• Python Applications
• Downloading & Installing Python
• Running Python
What Is Python?
• Python is a general purpose, high-level, interpreted
programming language.

• Developed by Guido van Rossum in the


late 1980s at the National Research
Institute for Mathematics and Computer
Science in the Netherlands.

• Python is one of the most popular and widely used


programming language used for set of tasks including
console based, GUI based, web programming and data
analysis.
Python Features
• Easy to Learn and Use
Python is easy to learn and use compared with other
programming languages. It is developer-friendly and high level
programming language.
• Interpreted Language
Python is an interpreted language because no need of
compilation. This makes debugging easy and thus suitable for
beginners.
• Cross-platform Language
Python can run equally on different platforms such as
Windows, Linux and Unix etc. So, we can say that Python is a
portable language.
Python Features Cont…

• Free and Open Source


The Python interpreter is developed under an open-source
license, making it free to install, use, and distribute.
• Object-Oriented Language
Python supports object oriented language and concepts of
classes and objects come into existence.
• GUI Programming Support
Graphical user interfaces can be developed using Python.
• Python is an integrated
• It can be easily integrated with languages like C, C++, and JAVA etc.
• Python provides native support for C and has extremely robust
solutions for integrating with other languages like C++, Java, Rust,
and Go.
Python Applications
Downloading & Installing Python
• To start programming with python, we have to install
python software. There are two major Python versions,
those are Python 2 and Python 3. Python 2 and 3 are
quite different.

• In this tutorial we are going to use Python 3, because it


more semantically correct and supports newer features.

• In this tutorial we are going to learn about installation of


Python3 on Windows and Linux (Ubuntu).
Downloading & Installing Python Cont…
Python3 installation procedure in Windows :
1. To install Python3 in windows, we have to download Python3
software pack from official website of Python Software
Foundation. Go to [Link]
Downloading & Installing Python Cont…
2. Download the latest version of python(now latest version:
python 3.8.3) for windows.
3. After the successful completion of download, we need to
run [Link] file.
Downloading & Installing Python Cont…
4. First we need to check Add Python 3.8 to PATH, And then
click on Install Now.
5. The Python setup will take 2 to 3 minutes of time, After
successful installation the following window will be displayed
Running Python
• After successful installation of python software we can able
interpret or execute python script / program.

Python provides us the two ways to run a python script:


1. Using Interactive interpreter prompt
2. Using a script file

1. Using Interactive interpreter prompt:


• Python provides us the feature to execute the python
statement one by one at the interactive prompt.
• It is preferable in the case where we are concerned about the
output of each line of our python program.
Running Python cont…
• To open the interactive mode, open the terminal (or command
prompt) and type python (python3 in case if you have python2
and python3 both installed on your system).

Through Command Prompt :


Running Python cont…
• In windows, search for python IDLE in all programs and then
click on python IDLE, then the python interpreter prompt will
open.
• Through python IDLE:
Running Python cont…
2. Using Script File :
• Interpreter prompt is good to run the individual statements of
the code. However if we want to execute multiple python
statements at a time instead of executing one by one, then we
can use script file.

• We need to write our script into a file which can be executed


later. For this purpose, open an editor like notepad, create a
file named [Link] (python used .py extension) and write
the python script in it.
Output:
• Example: "[Link]“
print("Hello !")
print("Welcome to Python Programming")
Identifiers :
An identifier is a name given to a variable,function,class.
Eg: a = 20
It is a valid Python statement.
Here 'a' is an identifier.
Rules to define identifiers in Python:
1. The only allowed characters in Python are
Alphabet symbols(either lower case or upper case)
Digits(0 to 9)
Underscore symbol(_).
Ex: total_1234 = 22 # Valid
2. An Identifier can be begin with an alphabet and underscoret(A-Z and a-z
and_)
Ex: _abc_abc_ = 22 # Valid
3. Identifier cannot starts with digit but is allowed everywhere else.
Ex: plus1=10 #valid
1plus=10 # In valid
SyntaxError: invalid syntax

[Link] cannot use spaces and special symbols like ! @ # $ % etc….


as identifiers.
Ex: cash$ = 10 # '$'is a special character invalid identifier
SyntaxError: invalid syntax

4. Identifiers are case sensitive. Of course Python language itself is case


sensitive language.
Ex: total=10
TOTAL=999
print(total) o/p : 10
print(TOTAL) o/p : 999
[Link] cannot be used as identifiers.
Ex: x = 10 # Valid
if = 33 # In valid if is a keyword in Python
SyntaxError: invalid syntax
5. Identifiers can be of any length.
Ex : Abcedwrtyyhfdg123_=10
Q. Which of the following are valid Python identifiers?
123total = 22
total1234 = 22
java2share = 'Java‘
ca$h = 33
_abc_abc_ = 22
def = 44
for = 3
_p = 33
Keywords:
1. In Python some words are reserved to represent some
meaning or functionality. Such type of words are called
Reserved words or keywords.
2. There are 33 reserved words available in Python.
List of keywords in python:
and as not
assert finally or
break for pass
class from nonlocal
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
False True None
2. All 33 keywords contains only alphabets symbols.
3. Except the following 3 reserved words, all contain only
lowercase alphabet symbols.
True
False
None

4. True and False are Boolean values , For Boolean values,


compulsory you need to use capital letter 'T' in True and
capital letter 'F' in False.
Ex: a = True # Valid

A=true # In valid
NameError: name 'true' is not defined
Statements and Expressions:
A statement is an instruction or statement is a unit of code that can be executed by
python interpreter.
Eg: z = 1 // this iExamples: Y=x + 17 >>> x=10 >>> z=x+20 >>> z 30 s an assignment
statement
Expression:
An expression is a combination of values, variables, and operators which are evaluated
to make a new value b.
>>> 20 # A single value
>>> z # A single variable
>>> z=10 # A statement
But expression is a combination of variable, operator and value which is evaluated by
using assignment operator in script mode.
Examples: Y=x + 17
>>> x=10 >>> z=x+20 >>> z o/p : 30
When the expression is used in interactive mode, is evaluated by the interpreter and
the result is displayed instantly.
Eg:
>>> 8+2
10
Variables:
Variables are nothing but reserved memory locations to store
values. That means when you create a variable some space is
reserved in memory.
• One of the most powerful features of a programming language
is the ability to manipulate variables.
• A variable is a name that refers to a value. An assignment
statement creates new variables and gives them values:

• The general format for assigning values is as follows.


• Variable name = expression
• The equal sign (=) also known as simple assignment operator
is used to assign values to variables.
• In general format, the operand to the left of the = operator is
the name of the variable and operator to the right of the =
operator is the expression which can be a value.
Eg:1. >>>name=‘python’
>>> number=100
>>> miles=1000.0
>>> name
Python
>>> number
100
>>> miles
1000
• This example makes three assignment statements.
• Integer type assigned to a variable number, float type assigned
to a variable miles ,string type value is assigned to a variable
name and print the value assigned to these variables.
2. In python not only the value of variable may change during program
execution but also the type of data that is assigned.
In Python, We don't need to specify the type of variable because
Python is a loosely typed language.
>>>Century=100
>>> Century = “hundred”
>>> Century
‘hundred’
3. Python allows you to assign value to several variables
simultaneously.
1. >>> a=b=c=1 [Link] multiple values to multiple variables
2.>>> a
1 a,b,c=5,50, 15
3.>>> b >>> a 5
1 >>>b 50
4.>>> c >>>c 15
1
Operators in Python
• The operator can be defined as a symbol which is responsible
for a particular operation between two operands.
• Python provides a variety of operators described as follows.
• Arithmetic operators :
• + (addition) eg: a=20; b=10 then a + b=30
• - (subtraction) eg: a=20; b=10 then a - b=10
• *(multiplication) eg: a=20; b=10 then a * b=200
• / (divide) eg: a=20; b=10 then a / b=2
• %( reminder) eg: a=20; b=10 then a % b=0
• // (floor division) eg: a=24; b=7 then a // b=3
• ** (exponent) eg: a=2; b=3 then a ** b=8
Operators in Python
• Assignment operators :
• = (Assigns to)
• += (Assignment after Addition)
• -= (Assignment after Subtraction)
• *= (Assignment after Multiplication)
• /= (Assignment after Division)
• %= (Assignment after Modulus)
• **= (Assignment after Exponent)
• //= (Assignment after floor division)
• Comparison operators :
• == (Equal to)
• != (Not equal to)
• <= (Less than or equal)
• >= (Greater than or equal)
• < (Less than)
• > (Greater than)
• Logical operators :
• and (logical and)
• or (logical or)
• not (logical not)
• Bitwise operators :
• & (binary and)
• | (binary or)
• ^ (binary xor)
• ~ (negation)
• << (left shift)
• >> (right shift)
• Membership operators :
• in (True, If the value is present in the data structure)
• not in (True, If the value is not present in the data structure)
• Identity operators :
• is (Returns true if both variables are the same object)
• is not (Returns true if both variables are not the same object)
Precedence and Associativity
Comments in Python
• In general, Comments are used in a programming language
to describe the program or to hide the some part of code
from the interpreter.

• Comments in Python can be used to explain any program


code. It can also be used to hide the code as well.

• Comment is not a part of the program, but it enhances the


interactivity of the program and makes the program
readable.

Python supports two types of comments:


• Single Line Comment
• Multi Line Comment
Comments in Python
• Single Line Comment:
In case user wants to specify a single line comment, then comment must start
with ‘#’
Example:
# This is single line comment
print "Hello Python"
Output:
Hello Python

• Multi Line Comment:


Multi lined comment can be given inside triple quotes.
Example:
'''This is
Multiline
Comment'''
print "Hello Python"
Output:
Hello Python
• Data types:

• Data types specify the type of data like numbers and characters to be stored
and manipulated with in a program. Basic data type of python are
• Numbers
• Boolean
• Strings
• None

Numbers:
• Integers, floating point numbers and complex numbers fall under python
numbers category. They are defined as int, float and complex class in
python.

1. integer:
• Int, or integer, is a whole number, positive or negative, without decimals,
of unlimited length, it is only limited by the memory available.
Example:
a=10
b=-12
c=123456789
2. float:
• Float or "floating point number" is a number, positive or negative, containing
one or more decimals.
Example:
• X=1.0
• Y=12.3
• Z= -13.4

3. complex:
• Complex numbers are written in the form , “x+yj" where x is the real part and
y is the imaginary part.
Example:
A=2+5j
B=-3+4j
C=-6j

Boolean:
Booleans are essential when you start using conditional statements.
Python Boolean type is one of the built-in data types provided by Python,
which represents one of the two values i.e. True or False. The boolean
values, True and False treated as reserved words.
String:
• 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.
• In the case of string handling, the operator + is used to concatenate
two strings as the operation "hello"+" python" returns "hello
python".
Example:
EX : S1=‘Welcome’ #using single quotes
S1 Output: ‘Welcome’
print(S1) Output: Welcome
Ex: S2=“To” #using double quotes
S2 Output: 'to'
print(S2) Output: to
Ex: S3=‘’’Python’’’ #using triple quotes
S3 Output: "'python'"
print(S3) Output: 'python‘
Ex: Name1= ‘Hello’
Name2=‘python’
Name1 + Name2 Output: ‘Hellopython’
print(Name1 + Name2) Output: Hellopython
Example:
a=10
b=“Python"
c = 10.5
d=2.14j
e=True
print("Data type of Variable a :",type(a))
print("Data type of Variable b :",type(b))
print("Data type of Variable c :",type(c))
print("Data type of Variable d :",type(d))
print(“Data type of Variable e :”,type(e))

Output:
• Data type of Variable a : <class 'int'>
• Data type of Variable b : <class 'str'>
• Data type of Variable c : <class 'float'>
• Data type of Variable d : <class 'complex'>
• Data type of Variable e : <class 'bool'>
Indentation:
• In Python it is a requirement and not a matter of style to indent the
program. This makes the code cleaner and easier to understand and
read.
• If a code block has to be deeply nested, then the nested statements
need to be indented further to the right.
• Block 2 and Block 3 are nested under Block 1. 4 white spaces are
used for indentation and are preferred over tabs.
• Incorrect indentation will result in IndentationError.

Block 1
Block 2
Block 3
Block 2, Continuation
Block 1, Continuation
• Reading Input :
• Input() function is used to gather data from the user.
• Syntax : variable_name = input([prompt])
• Where prompt is a string written inside parenthesis.
• The prompt gives an indication to the user of the value that needs
to be entered through the keyboard.
• When user presses Enter key, the program resumes and input
function returns what the user typed as a string.
• Even if the user inputs a number, it is treated as a string and the
variable_name is assigned the value of string.
1. >>> person = input(“what is your name?”)
2. What is your name? John
3. >>>person
4. ‘John’
Print Output
• Print() function allows a program to display text onto the console.
• Print function prints everything as strings.
>>>print(“Hello World”)
Hello World
There are two major string formats which are used inside the print() function to display
the contents on to the console.
1. [Link]()
2. f-strings
[Link]() method:
• The format() method returns a new string with inserted values.
• syntax: [Link](p0,p1,p2…..k0=v0, k1=v1,…)
• Where p0,p1 are called as positional arguments and k0,k1 are keyword arguments
with their assigned values of v0,v1..
• Positional arguments are a list of arguments that can be accessed with an index of
argument inside curly braces like {index}. Index value starts from zero.
• Keyword arguments are a list of arguments of type keyword = value, that can be
accessed with the name of the argument inside curly braces like {keyword}.
Eg: country = input(“which country do you live in”)
print(“I live in {0}”.format(country))
• Print Output
Eg:
a = 10
b = 20
Print(“the values of a is {0} and b is {1}”.format(a,b))
Print(“the values of b is {1} and a is {0}”.format(a,b))
f-strings:
A f-string is a string literal that is prefixed with “f”. These strings
may contain replacement fields ,and are enclosed within
curly braces { }.
Eg: country = input(“which country do you live in”)
Print(f”I live in {country}”)
Type Conversion in Python:
• Python provides Explicit type conversion functions to directly convert
one data type to another. It is also called as Type Casting in Python
• Python supports following functions
1. int () : This function convert a float number or a string to an integer.
• Eg: float_to_int = int(3.5)
string_to_int = int(“1”) // number is treated as string
print(float_to_int) o/p: 3
print(string_to_int) o/p: 1 will be displayed.
2. float( ) :
• This function convert integer or a string to floating point number using the
float() function.
• Eg: int_to_float = float(8)
string_to_float = float(“1”) // number is treated as string
print(int_to_float)
print(string_to_float)
8.0
1.0 get displayed
• The str() Function : The str() function returns a string which is fairly human
readable.
Eg: int_to_string =str(8)
float_to_string = str(3.5)
Print(int_to_string) prints ‘8’
Print(float_to_string) prints ‘3.5’

• The chr() Function : This function converts an integer to a string of one


character whose ASCII is the same integer used in chr() function. The
integer value should be in the range of 0-255.
Eg: ascii_to_char = chr(100)
Print(“equivalent character for ASCII value of 100 is {ascii_to_char}”)
Output: equivalent character for ASCII value of 100 is d
An integer value corresponding to an ASCII code is converted to character
and printed.
(ASCII A-Z =65 to 90 ; a-z = 97 to 122; 0-9 = 48 to 57)
• The Complex() Function:
• complex() function is used to print a complex number with a real part and
imag*j part.
• If the first argument for the function is a string, it is interpreted as complex
number and the function is called without 2nd parameter.
• If imag is omitted, it defaults to zero
• Eg: complex_with_string = complex(“1”)
– complex_with_number = complex(5,8)

Print(f“result after using string in real part{complex_with_string}”)


– Print(f”result after using numbers in real and imaginary
part{complex_with_number}”)
– Output: result after using string in real part (1+0j)
– result after using numbers in real and imaginary part (5+8j)
The ord() function:
• The ord() function returns an integer representing Unicode
code point for the given Unicode character.
• Eg: 1. unicode_for_integer = ord('4')
print(f“ Unicode code point for integer value of 4 is
{unicode_for_integer}")
Output: Unicode code point for integer value of 4 is 52.
The hex() function:
• Convert an integer number (of any size) to a lowercase
hexadecimal string prefixed with “0x” using hex() function.
• 1. int_to_hex = hex(255)
• 2. print(int_to_hex )
• Output: 0xff
The oct() function:
• Convert an integer number (of any size) to an octal string prefixed with “0o” using
oct() function.
Eg: int_to_oct = oct(255)
print(int_to_oct)
Output: 0o377.

Dynamic and strongly typed language:


• Python is a dynamic language as the type of the variable is determined during run-
time by the interpreter.
• Python is also a strongly typed language as the interpreter keeps track of all the
variables types
• In a strongly typed language, you are simply not allowed to do anything that’s
incompatible with the type of data you are working with.
• For example, Parts of Python Programming Language
>>> 5 + 10
15
>>> 1 + "a“

Traceback (most recent call last):


• when you try to add 1, which is an integer type with "a" which is string type, then
it results in Traceback as they are not compatible.
• In Python, Traceback is printed when an error occurs.
The type() function and is operator:
The syntax for type() function is,
type(object)
The type() function returns the data type of the given object.
1. >>> type(1)
<class ‘int’>
2. >>> type(6.4)
<class ‘float’>
3. >>> type("A")
<class ‘str’>
4. >>> type(True)
<class ‘bool’>
The type() function comes in handy if you forget the type of
variable or an object during the course of writing programs.
Assignment Questions
Python Control Statements
Indentation in Python
Indentation in Python
• In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are
the part of the same block.

• For the ease of programming and to achieve simplicity, python


doesn't allow the use of curly braces or parentheses for the
block level code.

• Indentation is the most used part of the python programming


language.

• Generally, a tab space or four spaces are given to indent the


statements in python.
Conditional Statements in Python
Conditional Statements in Python
• Conditional Statements performs different computations or
actions depending on conditions.
• In python, the following are conditional statements
o if
o if –else
o if – elif –else
If statement:
• The if statement is used to test a specific condition. If the
condition is true, a block of code (if-block) will be executed.
Syntax:
if condition:
statement1
statement2
Conditional Statements in Python Cont..

Example: [Link] Output:


a = 33 python [Link]
b = 200 b is greater than a
if b > a:
done…
print ("b is greater than a")
print ("done…")

Remember:
input () function is used to get input from user.
Example:
a=input (“Enter a value”)
Conditional Statements in Python Cont..

If-else statement:
• The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
Syntax:
Output:
if condition:
python [Link]
#block of statements
Enter your age: 19
else:
You are eligible to vote!!
#another block of statements (else-block)

Example: [Link]
age = int(input("Enter your age : "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!"))
Conditional Statements in Python Cont..

If-elif-else statement:
• The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the true
condition among them.
Syntax:
if condition1:
# block of statements
elif condition2:
# block of statements
elif condition3:
# block of statements
else:
# block of statements
Conditional Statements in Python Cont..

Example: [Link]
a=int(input("Enter a value : "))
b=int(input("Enter b value : "))
c=int(input("Enter c value : "))
if (a>b) and (a>c):
print("Maximum value is :",a)
elif (b>a) and (b>c):
print("Maximum value is :",b)
else:
print("Maximum value is :",c)

Output:
python [Link]
Enter a value: 10
Enter b value: 14
Enter c value: 9
Maximum value is: 14
Loop Statements in Python
Loop Statements in Python
• Sometimes we may need to alter the flow of the program. If the
execution of a specific code may need to be repeated several
numbers of times then we can go for loop statements.
• In python, the following are loop statements
o while loop
o for loop

while loop:
• With the while loop we can execute a set of statements as long
as a condition is true. The while loop is mostly used in the case
where the number of iterations is not known in advance.
Syntax:
while expression:
Statement(s)
Loop Statements in Python Cont..

Example: [Link] Output:


i=1; python [Link]
while i<=3: 1
print(i); 2
i=i+1; 3

Using else with while loop


• Python enables us to use the while loop with the else block
also. The else block is executed when the condition given in
the while statement becomes false.
Example: [Link] Output:
i=1; python [Link]
while i<=3: 1
print(i); 2
i=i+1; 3
else:
while loop terminated
print("while loop terminated")
Loop Statements in Python Cont..

for loop:
• The for loop in Python is used to iterate the statements or a
part of the program several times. It is frequently used to
traverse the data structures like list, tuple, or dictionary.

Syntax:
for iterating_var in sequence:
statement(s)

Example: [Link] Output:


i=1 python [Link]
n=int(input("Enter n value : ")) Enter n value: 5
for i in range(i,n+1): 12345
print(i,end = ' ')
Loop Statements in Python Cont..

Using else with for loop


• Python allows us to use the else statement with the for loop
which can be executed only when all the iterations are
exhausted.
• Here, we must notice that if the loop contains any of the
break statement then the else statement will not be executed.
Example: [Link]
for i in range(1,5):
print(i,end=' ')
else:
print("for loop completely exhausted");

Output:
python [Link]
1234
for loop completely exhausted
Jump Statements in Python
Jump Statements in Python
• Jump statements in python are used to alter the flow of a loop
like you want to skip a part of a loop or terminate a loop.
• In python, the following are jump statements
o break
o continue
break:
• The break is a keyword in python which is used to bring the
program control out of the loop.
• The break statement breaks the loops one by one, i.e., in the
case of nested loops, it breaks the inner loop first and then
proceeds to outer loops.
• The break is commonly used in the cases where we need to
break the loop for a given condition.
Syntax: break
Jump Statements in Python Cont..

Example: [Link]
i = 1 Output:
while i < 6: python [Link]
print(i)
1
if i == 3:
break 2
i += 1 3

continue:
• The continue statement in python is used to bring the program
control to the beginning of the loop.
• The continue statement skips the remaining lines of code inside
the loop and start with the next iteration.
• It is mainly used for a particular condition inside the loop so
that we can skip some specific code for a particular condition.
Syntax: continue
Jump Statements in Python Cont..

Example: [Link]
str =input("Enter any String : ")
for i in str:
if i == 'h':
continue;
print(i,end=" ");

Output:
python [Link]
Enter any String : python
pyton
Functions
• Function:
• Block of statements are grouped together and is given a name which can be used to invoke (call) it
from other parts of the program.
• Functions can be either Built-in functions or User-defined functions
• Built-In Functions:
Function name Syntax Explanation
abs() abs(x), where x is an integer or abs() function returns the
floating point number absolute value of a number
min() Min(arg_1,arg_2….arg_n) Returns the smallest of 2 or
Where arg_1, arg_2…arg_n are more arguments
arguments
max() Max(arg_1,arg_2….arg_n) Where Returns the maximum of 2 or
arg_1, arg_2…arg_n are arguments more arguments

Divmod() Divmod(a,b) where a and b are Returns a pair of numbers


numbers representing numerator which are quotient and
and denominator remainder. (a//b, a%b)
Pow() Pow(x,y) where x and y are Pow(x,y) is equivalent to x**y
numbers
Len() Len(s) where s may be string, byte, Len() function returns the
list, tuple, range, dictionary or a set length of the number of items
in an object
• Commonly Used Modules
Modules are reusable libraries of code having .py extension. Python has many built in modules as
part of the standard library.
• Syntax: import module_name
• Math module contains mathematical functions which can be used by the programmer.
• Syntax: module_name.function_name()
• Eg:
• >>>import math
• >>>print([Link](5.4))
• 6
• >>>print([Link](4))
• 2.0
• >>>print([Link])
• 3.141592653
• >>>print([Link](1))
• 0.54030
• >>>[Link](6)
• 720
• >>>[Link](2,3)
• 8
• Built-in function dir() returns a sorted list of strings containing the names of functions, classes
and variables as defined in the module.
• >>>dir(math)
• Help: help() The argument to the help() is a string, which is looked up as the name of a module,
function, class, method, keyword or documentation topic.
• Eg:
• >>> help([Link])

• Random module: This is used to generate random numbers.


• >>>import random
• >>>print([Link]())
• 0.2551914
• >>>print([Link](5,10))
• 9
• Random() function generates a random floating point number between 0 and 1.
• Syntax: [Link](start,stop) # generates a integer number between start and stop arguments

• 3rd party modules or libraries can be installed and managed using python’s package manager pip.
Arrow is a popular library used to create, manipulate format and convert date, time and timestamp.

• The Syntax for pip is


• Pip install module_name
• >>>import arrow
• >>>a=[Link]()
• >>>[Link]() # current date and time is displayed using now function.
• <Arrow[date and time]>
• Function definition and calling the function
• Def function_name(parameter_1, parameter_2, …………….parameter_n):
– Statement(s)
• Def – keyword
• Function_name = user defined
• Colon should be present at the end
• Indentation should be provided to the statement following the function_name.
• 1. The function Name: The rules are same as variables. We can use letters, numbers or an
underscore but it cannot start with a number.
• Keyword cannot be used as a function name.
• 2. List of parameters to the function are enclosed in parentheses and separated by commas.
Some functions do not have any parameters at all.
• 3. Colon is required at the end of function header.
• 4. Block of statements that define the body of function start at the next line of function header
and they must have the same indentation level.
• Syntax: function_name(argument_1, argument_2……argument_n)
• There must be one to one correspondence between the formal parameters in the function
definition and the actual arguments of the calling function.
• When a function is called, the control flows from the calling function to the called function.
Once the block of statements in the function definition is executed, the control flows back to
the calling function and proceeds to the next statement.
• Before executing the code in the source program, the python interpreter automatically
defines a few special variables.
• Python interpreter sets the special built-in _name_ variable to have a string value of “_main_”.
• After setting up these special variables, python interpreter reads the program to execute the
code found in it. All the code is at indentation level 0 gets executed.
• The special variable, _name_ with “_main”_ is the entry point of your program. All the
functions should be invoked within main() function.
• Eg:

• def function_definition_with_no_argument():
• print(“This is a function definition with no arguments”)
• def function_definition_with_one_argument(message):
• print(“This is a function definition with {message}”)

• def main():
• function_definition_with_no_argument()
• function_definition_with_one_argument(“one argument”)

• If_name_==“_main_”:
• main()
• OUTPUT:
• This is a function definition with no arguments
• This is a function definition with one argument
Output:
• The return Statement and void Function
• This is used to return value to the calling function so that it is
stored in a variable.
• Syntax: return[expression_list]
• In Python, we can define functions without a return
statement. Such functions are called void functions.
• A function call return only a single value but that value can
be a list or tuple.
• Eg:
• #Program to return multiple values from return statement separated by
comma
Example 1

def world_war():
alliance_world_war = input("which alliance won world war 2?")
world_war_end_year = input("when did world war 2 end?")
return alliance_world_war, world_war_end_year

def main():
alliance, war_end_year = world_war()
print(f"The war was won by {alliance} and the war ended in {war_end_year}")

if __name__=="__main__":
main()
Example 2

Output:
Sum = 10
Diff = 2
• Scope and Lifetime of Variables

• There are two scopes: global and local.


• Global variables have global scope. A variable defined inside a function is called a local variable.
Local variable is created and destroyed every time the function is executed. It cannot be accessed
outside the function.
• Global variables can be accessed inside a function if there will be no local variables with the same
name.
test_var = 10
def outer_func():
test_var = 60

def inner_func():
test_var = 100
print("local var inner func is ", test_var)

inner_func()
print("local var outer func is", test_var)

outer_func()
print("global var value is", test_var)

• Output:
• local var inner func is 100
• local var outer func is 60
• global var value is 10
Nested Function:
A nested function (inner function) can inherit the arguments and variables of
its outer function. The inner function can use the arguments and variables
of the outer function while the outer function cannot use the arguments
and variables of the inner function.
The inner function definition is invoked by calling it from within the outer
function definition.
Example:
Without return function

Output:
power= 8
multiplication= 20
With return function
def multiplication(a,b):
c=a*b
def power(d,e):
f=d**e
return f
result=power(2,3)
return c,result
def main():
mul,pow =multiplication(4,5)
print("mul=",mul)
print("pow=",pow)
if __name__=="__main__":
main()
Output:
mul= 20
pow= 8
Default Parameters:
Any calling function must provide arguments for all required parameters in the
function definition but can omit the arguments for default parameters. If no
argument is sent for that parameter, the default values is used.

def work_area(prompt, domain=“Data Analytics”):


print(f”{prompt} {domain}”)

Def main():
work_area(“ Sam works here in ”)
work_area(“Alice has interest in”, “Internet of Things”)

If__name__==“__main__”:
main()

Output:
Sam works here in Data Analytics
Alice has interest in Internet of Things
Example : 2
def message(msg1,msg2="Good Morning"):
print(msg1,msg2)

def main():
message("hello")
message("hello","world")

if __name__=="__main__":
main()

Output:
hello Good Morning
hello world
Keyword Arguments:
Whenever you call a function with some values as its arguments, these values get
assigned to the parameters in the function definition according to their position.

In calling function, you can specify the argument name and their value in the form of
Kwarg = value. In calling function, keyword arguments must follow positional arguments.

No parameter in the function definition may receive a value more than once.
OR
Keyword arguments mean whenever we pass the arguments(or value) by their
parameter names at the time of calling the function in Python in which if you
change the position of arguments then there will be no change in the
output.
On using keyword arguments you will get the correct output because
the order of argument doesn’t matter provided the logic of your code is
correct. But in the case of positional arguments, you will get more than one
output on changing the order of the arguments.
Example 1: Keyword Argument
def nameAge(name, age):
print("Hi, I am", name)
print("My Age is", age)

nameAge(name = "SriRam", age = 20)

nameAge(age = "20", name = "SriRam")

Output:
Hi, I am SriRam
My Age is 20
Hi, I am SriRam
My Age is 20
Positional arguments
Positional arguments are arguments that need to be included in the proper position or
order. The first positional argument always needs to be listed first when the function is
called. The second positional argument needs to be listed second and the third
positional argument listed third, etc.
Example 1:
def nameAge(name, age):
print("Hi I‘ am", name)
print("My age is", age)
#you will get correct output because argument is given in order
nameAge("SriRam", 20)
#you will get Incorrect output because argument is not in order
nameAge(20, "SriRam")
Output:
Hi I‘ am SriRam
My age is 20
Hi I 'am 20
My age is SriRam
*args and **kwargs
They are used as parameters in function definitions.
*args and **kwargs allows you to pass a variable number of arguments to
the calling function.
User might not know the number of arguments in advance that will be
passed to the calling function.

*args : Allows you to pass a non-key worded variable length argument list
to the calling function.
**kwargs as parameter in function allows you to pass key worded variable
length dictionary argument list to the calling function.
*args should come after all the positional paramters and **kwargs must
come right at the end.
*args and **kwargs
• In Python, we can pass a variable number of arguments to a function using
special symbols. There are two special symbols:
• *args (Non Keyword Arguments)
• **kwargs (Keyword Arguments)
We use *args and **kwargs as an argument when we are unsure about
the number of arguments to pass in the functions.

Python *args
Python has *args which allow us to pass the variable number of non keyword
arguments to function.
In the function, we should use an asterisk * before the parameter name to
pass variable length arguments. The arguments are passed as a tuple and these
passed arguments make tuple inside the function with same name as the
parameter excluding asterisk *
Example 1 : *args
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:" ,sum)

adder(3,5)
adder(4,5,6,7)
adder(1,2,3,4,5,6)
Output:
Sum: 8
Sum: 22
Sum: 21
Python **kwargs
Python passes variable length non keyword argument to function
using *args but we cannot use this to pass keyword argument. For this
problem Python has got a solution called **kwargs
it allows us to pass the variable length of keyword arguments to the
function.
In the function, we use the double asterisk ** before the parameter
name to denote this type of argument. The arguments are passed as a
dictionary and these arguments make a dictionary inside function with
name same as the parameter excluding double asterisk **

Dictionaries - Dictionaries are used to store data values in


key:value pairs. A dictionary is a collection which is ordered*,
changeable and do not allow duplicates.
Example 1 : **kwargs
def intro(**data):
print("\n Data type of argument:", type(data))

for key, value in [Link]():


print("{} is {}".format(key,value))

intro(Firstname="Sri", Lastname="Ram", Age=22, Phone=1234567891)

intro(Firstname="Sita", Lastname="Ram", Age=25, Phone=987654218,


Email="sitaram@[Link]", State="Karnataka", Country="India")
Output:
Data type of argument: <class 'dict'>
Firstname is Sri
Lastname is Ram
Age is 22
Phone is 1234567891

Data type of argument: <class 'dict'>


Firstname is Sita
Lastname is Ram
Age is 25
Phone is 987654218
Email is sitaram@[Link]
State is Karnataka
Country is India
Command Line Arguments:
A python program can accept any number of arguments from the command line. Command line
arguments is a methodology in which user will give inputs to the program through the
console using commands.

You need to import sys module to access command line arguments. All the command line
arguments can be printed as a list of string by executing [Link].

Example:
import sys
def main():
print(f"[Link] prints all the arguments at the command line including file name {[Link]}")
print(f"len([Link]) prints the total number of command line arguments including file name
{len([Link])}")
print("you can use for loop to traverse through [Link]")
for arg in [Link]:
print(arg)
if __name__=="__main__":
main()
Output
• C:\Users\Admin>python
C:/Users/Admin/AppData/Local/Programs/Python/Python311/[Link] lion tiger mouse
• len([Link]) prints the total number of command line arguments including file name 4
• C:/Users/Admin/AppData/Local/Programs/Python/Python311/[Link]
• lion
• tiger
• mouse
How to Execute command line argument program
1. Write the program
2. Save the program with .py extension
3. Open command prompt
4. Change the path to where program is being saved
5. Py followed by [Link] ([Link]) and followed by
number of Arguments (arg1 arg2 arg3…..)
Example 1
import sys
print([Link])
print(len([Link]))
for i in range (0,len([Link])):
print("Argument -:",i,":",[Link][i])
#Sum of all the elements from the command line
import sys
sum=0
for i in range (1,len([Link])):
sum+=int([Link][i])
print("result=",sum)
Strings
Creating and Sorting Strings:

Strings consist of one or more characters surrounded by matching quotation marks.


Strings are surrounded by either
• Single or double quotation marks.
• A string enclosed in double quotation marks can contain single quotation marks and vice
versa.
• If you have a string spanning multiple lines, than it can be included within triple quotes.
• You can find the type of a variable by passing it as an argument to type() function.
• Python strings are of str data type.

1. The str() Function:


• Str() function returns a string and the syntax for str() function is str(object).
• It returns a string version of the object.
• >>> str(10)
• ‘10’
• >>>create_string=str()
• >>>type(create_string)
• <class ‘str’>
• Here integer 10 is converted to string. The create_string is an empty string of type str.
2. Basic String Operations:
In Python, strings can also be concatenated using + sign and * operator is used to create a repeated
sequence of strings

>>>string_1 =“face”
>>>string_2 =“book”
>>>string_1+string_2
‘facebook’
When two strings are concatenated, there is no white space between them. If you need a white space
between the 2 strings, include a space after the first string or before the second string within the
quotes.
>>>singer = 50+”cent” gives an error as 50 is of integer type and cent is of string type.
>>>singer =str(50) + “cent”
>>>singer
‘50cent’
>>>repeated_str =“wow” * 5
>>>repeated_str
‘wowwowwowwowwow’
You can check the presence of a string in another string using in and not in membership operators
>>>fruit_str=“apple is a fruit”
>>>fruit_sub_str=‘apple’
>>>fruit_sub_str in fruit_string
True
>>> another_fruit_str=“orange”
>>>another_fruit_str not in fruit_str
True
3. String Comparison:
>, <, <=,>=,==, != can be used to compare two strings resulting in True or False. Python compares
the strings using ASCII value of the characters.
>>>”january” == “jane”
False
>>>”january” != “jane”
True
>>>”january” > “jane” # the ASCII value of u is more than e
True
>>>”january” < “jane”
False
>>>”january” >= “jane”
True
>>>”january” <= “jane”
False Built in functions Descriptions
>>>”filled”>”” Len() This function calculates the number
True of characters in a string
4. Built In Functions
using Strings Max() This function returns a character
There are built in functions for having highest ASCII value
which a string can be passed
Min() This function returns a character
as an argument.
having lowest ASCII value
Eg:
>>>max(“axel”)
‘x’
>>>min(“brad”)
‘a’
5. Accessing Characters in String by Index Number:
Each character in the string occupies a position in the string. Each of the string’s character
corresponds to an index number. First character is at index 0.
Syntax: string_name[index]
b e y o u r s e l f
index 0 1 2 3 4 5 6 7 8 9 10

>>>word_phrase=“be yourself”
>>>word_phrase[0]
‘b’
>>>word_phase[1]
e
>>>word_phase[2]
‘’
>>>word_phase[3]
y
The individual characters in a string can be accessed using negative indexing. If there is a long string
and you want to access end characters in a string, then you can count backwards from the end of
the string starting from the index of -1

>>>word_phrase[-1]
‘f’
>>>word_phrase[-2] b e y o u r s e l f
‘l’
index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
6. String Slicing and Joining

The syntax for string slicing is,


String_name[start:end[:step]]
You can access a sequence of characters by specifying a range of index numbers separated by a colon.
The string slicing starts from the beginning and extending up to but not including end. After slicing
substring is created.
>>>drink =“green tea”
>>>drink[0:3]
‘gre’
>>>drink[:5]
‘green’
>>>drink[6:]
g r e e n t e a
‘tea’ 0 1 2 3 4 5 6 7 8
>>>drink[:]
‘green tea’
>>>drink[6:20]
‘tea’
A substring is a sequence of characters contained in a string.
If start index and end index are omitted, then the entire string is displayed
If the start index is equal to or higher than end index, result is an empty string.
Slicing can be done using negative integer numbers.

>>>drink[-3:-1] g r e e n t e a
‘te’
-9 -8 -7 -6 -5 -4 -3 -2 -1
>>>drink[6:-1]
‘te’ We can combine the positive and negative indexing numbers

7. Specifying steps in Slice Operation:


Steps refers to the number of characters that can be skipped after the start indexing character in
the string. Default value of step is one.
>>>newspaper=“new York times”
>>>newspaper[0:13:4]
‘ny e’
>>>newspaper[::4]
‘ny e’
Starts with index 0 and till n and will print every 4th character.

8. Joining Strings using Join() Method


8. Joining Strings using Join() Method:
Strings can be joined with join() string. Join() method syntax is,
String_name.join(sequence)
If sequence is a string, then join() function inserts string_name between each item of list
sequence and returns the concatenated string.
>>>date_of_birth=[“17”,”09”,”1950”]
>>>”:”.join(date_of_birth)
‘17:09:1950’
>>>numbers=‘123’
>>>characters = ‘amy’
>>>password = [Link](characters)
>>>password
‘a123m123y’
The string value of ‘123’ is inserted between a and m and again between m and y and is assigned
to password string variable.

9. Split Strings using split() Method:


The syntax is
string_name.split([separator [, maxsplit]])
If the seperator is not specified, then whitespace is considered as the delimiter string.
Eg:
>>>shoes = “ Nike Puma Adidas Bata Liberty”
>>>[Link]()
>>>icecream=“vanilla, black current, strawberry, chocolate”
>>>[Link](“,”)
The string icrecream is split with the seperator as ,. If seperator is not specified, whitespace is
used by default.
10. Strings are immutable:
The characters in a string cannot be changed once it is assigned to string variable.
>>>stringVar = “Hello”
>>>stringVar[0] = “c” // this line gives an typeerror saying str object does not support item
assignment
11. String Traversing:
Each of the characters in a string can be traversed using the for loop.
Eg:
def main():
stringVar = “KLESNC”
index = 0
for each_character in stringVar:
print(f”Character ‘{each_character}’ has an index value of {index}”)
index+=1
Strings are immutable
12: String Methods
All the methods supported by string can be found using the dir command.
>>>dir(str)
COPY METHODS from TEXT Book
what is the difference between isdigit() and isnumeric() python
isdigit():
• The isdigit() method returns ‘True’ if all characters in the string are digits, and the
string is not empty.
• It does not consider other numeric characters such as superscripts and subscripts.
• It is specific to ASCII digits (0-9).
>>>text = "12345"
>>>result = [Link]()
>>>print(result) # Output: True
isnumeric():
The isnumeric() method returns ‘True’ if all characters in the string are numeric
characters, including digits, superscripts, subscripts, and more.
It is a more general method compared to isdigit()
>>>text = "12345“
>>>result = [Link]()
>>>print(result) # Output: True
• In summary, isdigit() is more restrictive and checks only for
ASCII digits, while isnumeric() is more inclusive and
considers a broader range of numeric characters.
Depending on your use case, you might choose one over the
other. If you specifically want to check for digit characters
(0-9), isdigit() is often more appropriate. If you want to
check for a broader set of numeric characters, including
superscripts and subscripts, then isnumeric() may be more
suitable.
13. Formatting Strings:
The strings can be formatted in the below ways:
a) %-formatting : Only str, int and doubles can be formatted. All other types are not supported
or converted to one of these types before formatting. Also it does not work with multiple
values.
b) Eg:
• >>>TestVar = ‘KLESNC’
• >>>’College : %s’ % TestVar
• ‘College : KLESNC’
works well when single value is passed. But if the variable TestVar were ever to be a tuple.,
the same code would fail.
• >>>TestVar = (‘KLESNC’, 560010)
• >>>’College : %s’ % TestVar
TypeError: not all arguments converted during string formatting.
b) [Link]:
This was added to address some of these problems with %-formatting.
Eg:
>>>value = 5 * 10
>>>’The value is {value}.’ .format(value = value)
‘The value is 50.’
>>> ‘The value is { }’ .format(value)
‘The value is 50.’
c) f-strings provide a concise, readable way to include the value of Python expressions inside
strings.
eg:
>>>f’The value is {value}’.
‘The value is 50.’
String Methods
String Methods in Python
• Python provides various in-built functions & methods that are
used for string handling. Those are

• lower() • find()
• upper() •index()
• replace() • isalnum()
• join() • isdigit()
• split() • isnumeric()
• islower()
• isupper()
String Methods in Python Cont..
☞ lower ():
• In python, lower() method returns all characters of given string in
lowercase.
Syntax:
[Link]()
Example: [Link] Output:
str1="PyTHOn" python [Link]
print([Link]()) python
☞ upper ():
• In python, upper() method returns all characters of given string in uppercase.
Syntax:
[Link]()
Example: [Link] Output:
str="PyTHOn" python [Link]
print([Link]()) PYTHON
String Methods in Python Cont..
☞ replace()
• In python, replace() method replaces the old sequence of
characters with the new sequence.
Syntax: [Link](old, new[, count])
Example: [Link]
str = "Java is Object-Oriented and Java"
str2 = [Link]("Java","Python")
print("Old String: \n",str)
print("New String: \n",str2)
str3 = [Link]("Java","Python",1)
print("\n Old String: \n",str)
print("New String: \n",str3)
Output: python [Link]
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Python
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Java
String Methods in Python Cont..
☞ split():
• In python, split() method splits the string into a comma separated list.
The string splits according to the space if the delimiter is not provided.
Syntax: [Link]([sep="delimiter"])
Example: [Link]
str1 = “Java is a programming language"
str2 = [Link]()
print(str1);print(str2)
str1 = “Java,is,a,programming,language"
str2 = [Link](sep=',')
print(str1);print(str2)

Output: python [Link]


Java is a programming language
['Java', 'is', 'a', 'programming', 'language']
Java, is, a, programming, language
['Java', 'is', 'a', 'programming', 'language']
String Methods in Python Cont..
☞ find():
• In python, find() method finds substring in the given string and returns
index of the first match. It returns -1 if substring does not match.
Syntax: [Link](sub[, start[,end]])
Example: [Link]
str1 = "python is a programming language"
str2 = [Link]("is")
str3 = [Link]("java")
str4 = [Link]("p",5)
str5 = [Link]("i",5,25)
print(str2,str3,str4,str5)

Output:
python [Link]
7 -1 12 7
String Methods in Python Cont..
☞ index():
• In python, index() method is same as the find() method except it returns
error on failure. This method returns index of first occurred substring
and an error if there is no match found.
Syntax: str. index(sub[, start[,end]])
Example: [Link]
str1 = "python is a programming language"
str2 = [Link]("is")
print(str2)
str3 = [Link]("p",5)
print(str3)
str4 = [Link]("i",5,25) Output:
print(str4) python [Link]
str5 = [Link]("java") 7
print(str5) 12
7
Substring not found
String Methods in Python Cont..
☞ isalnum():
• In python, isalnum() method checks whether the all characters of the
string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric. It does not allow special chars even spaces.
Syntax: [Link]()
Example: [Link]
str1 = "python"
str2 = "python123" Output:
str3 = "12345" python [Link]
str4 = "python@123" True
str5 = "python 123" True
print(str1. isalnum()) True
print(str2. isalnum()) False
print(str3. isalnum()) False
print(str4. isalnum())
print(str5. isalnum())
String Methods in Python Cont..
☞ isdigit():
• In python, isdigit() method returns True if all the characters in the string
are digits. It returns False if no character is digit in the string.
Syntax: [Link]()
Example: [Link]
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV" Output:
str5 = "/u00B23" # 23 python [Link]
str6 = "/u00BD" # 1/2 True
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]())
String Methods in Python Cont..
☞ isnumeric():
• In python, isnumeric() method checks whether all the characters of the
string are numeric characters or not. It returns True if all the characters
are numeric, otherwise returns False.
Syntax: str. isnumeric()
Example: [Link]
str1 = "12345"
str2 = "python123"
str3 = "123-45-78" Output:
str4 = "IIIV" python [Link]
str5 = "/u00B23" # 23 True
str6 = "/u00BD" # 1/2
False
print([Link]())
False
print([Link]())
print([Link]()) False
print([Link]()) True
print([Link]()) True
print([Link]())
String Methods in Python Cont..
☞ islower():
• In python, islower() method returns True if all characters in the string
are in lowercase. It returns False if not in lowercase.
Syntax: [Link]()
Example: [Link]
str1 = "python"
str2="PytHOn"
str3="python3.7.3"
print([Link]())
print([Link]())
Output:
print([Link]())
python [Link]
True
False
True
String Methods in Python Cont..
☞ isupper():
• In python string isupper() method returns True if all characters in the
string are in uppercase. It returns False if not in uppercase.
Syntax: [Link]()
Example: [Link]
str1 = "PYTHON"
str2="PytHOn"
str3="PYTHON 3.7.3"
print([Link]())
print([Link]())
Output:
print([Link]())
python [Link]
True
False
True
List Creation
List in Python
• In python, a list can be defined as a collection of values or
items.
• The items in the list are separated with the comma (,) and
enclosed with the square brackets [ ].
Syntax:
list_name= [ item1, item2,item3…. ]
Example: “[Link]”
L1 = [] Output:
L2 = [123,"python", 3.7] python [Link]
L3 = [1, 2, 3, 4, 5, 6] []
L4 = ["C","Java","Python"] [123, 'python', 3.7]
print(L1) [1, 2, 3, 4, 5, 6]
print(L2) ['C','Java','Python']
print(L3)
print(L4)
List Operators
List Operators in Python
It is known as concatenation operator used to concatenate two
+ lists.
It is known as repetition operator. It concatenates the multiple
* copies of the same list.
It is known as slice operator. It is used to access the list item
[] from list.
It is known as range slice operator. It is used to access the range
[:] of list items from list.
It is known as membership operator. It returns if a particular
in item is present in the specified list.

It is also a membership operator and It returns true if a


not in particular list item is not present in the list.
List Operators in Python cont…

Example: “[Link]”
num=[1,2,3,4,5]
lang=['python','c','java','php']
print(num + lang) #concatenates two lists
print(num * 2) #concatenates same list 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd index.
print('cpp' in lang) # prints False
print(6 not in num) # prints True

Output: python [Link]


[1, 2, 3, 4, 5, 'python', 'c', 'java', 'php']
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
java
['c', 'java', 'php']
False
True
List Indexing
List Indexing in Python
• Like string sequence, the indexing of the python lists starts from 0,
i.e. the first element of the list is stored at the 0th index, the second
element of the list is stored at the 1st index, and so on.
• The elements of the list can be accessed by using the slice operator
[].
• The syntax for accessing an item in a list is,
• list_name[index]
Example:
mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry’]

• mylist[0]=”banana” mylist[1:3]=[”apple”,”mango”]
• mylist[2]=”mango”
List Indexing in Python cont…

• Unlike other languages, python provides us the flexibility to use


the negative indexing also. The negative indices are counted
from the right.
• The last element (right most) of the list has the index -1, its
adjacent left element is present at the index -2 and so on until
the left most element is encountered.
Example: mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry’]

• mylist[-1]=”berry” mylist[-4:-2]=[“apple”,mango”]
• mylist[-3]=”mango” mvlist[ -3 : ]=[“mango”,”tomato”,’berry’]
Slicing in list
• Slicing of lists is allowed in Python wherein a part of the list
can be extracted by
• specifying index range along with the colon (:) operator which
itself is a list.
• The syntax for list slicing is,

• List slicing returns a part of the list from the start index value
to stop index value which includes the start index value but
excludes the stop index value. Step specifies the increment
value to slice by and it is optional.
• 1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango",
"banana"]
• 2. >>> fruits[1:3]
• ['pineapple', 'blueberries']
• 3. >>> fruits[:3]
• ['grapefruit', 'pineapple', 'blueberries']
• 4. >>> fruits[2:]
• ['blueberries', 'mango', 'banana']
• 5. >>> fruits[1:4:2]
• ['pineapple', 'mango']
• 6. >>> fruits[:]
• ['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana']
• 7. >>> fruits[::2]
• ['grapefruit', 'blueberries', 'banana']
• 8. >>> fruits[::-1]
• ['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
• 9. >>> fruits[-3:-1]
• ['blueberries', 'mango']
How to update or change elements to a list?
• Python allows us to modify the list items by using the slice and
assignment operator.
• We can use assignment operator ( = ) to change an item or a
range of items.
Example: “[Link]”
num=[1,2,3,4,5]
print(num) Output:
num[2]=30 python [Link]
print(num) [1, 2, 3, 4, 5]
num[1:3]=[25,36] [1, 2, 30, 4, 5]
print(num) [1, 25, 36, 4, 5]
num[4]="Python" [1, 25, 36, 4, 'Python']
print(num) [1, 25, 36, 4, ‘python’]
List1=num1
Print(list1)
Built –in functions used on lists
List Functions & Methods in Python
• Python provides various in-built functions .Those are

• len()
• any()
• all()
• sum()
• sorted()
☞ len():
• In Python, len() function is used to find the length of list,i.e it
returns the number of items in the list..
Syntax: len(list)
Example: [Link] Output:
num=[1,2,3,4,5,6] python [Link]
print("length of list :",len(num)) length of list : 6
• ☞ any():
• The any() function returns True if any of the Boolean
values in the list is True.
• Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary,
tuple, list, set, etc.
• Ex:
• any([1, 1, 0, 0, 1, 0])
• True
• any(0,0,0,0)
• False
• list2=[1,0,2]
• any(list2)
• True
• ☞ all():
• The all() function returns True if all the Boolean values in the
list are True, else returns False.
• Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary, tuple, list,
set, etc.
• Ex:
• >>> all([1, 1, 1, 1])
• True
• >>> all([1,0,2])
• False
• >>> all([1,2,3,4,5,])
• True
List Functions in Python Cont..

☞ sum ():
• In python, sum() function returns sum of all values in the list. List
values must in number type.
Syntax: sum(list)

Example: [Link]
list1=[1,2,3,4,5,6]
print("Sum of list items :",sum(list1))

Output:
python [Link]
Sum of list items : 21
List Functions in Python Cont..

☞ sorted ():
• The sorted() function returns a modified copy of the list while
leaving the original list untouched.
Syntax: sorted(list)

Example: [Link]

num=[23,5,78,9]
print(sorted(num))
[5, 9, 23, 78]
print(num)
[23, 5, 78, 9]
List Methods
List Functions & Methods in Python
• Python provides various methods which can be used with list.

• Those are

• count() • extend
• index() •append()
• max()
• insert() • remove()
• min()
• pop() • sort()
• list()
• clear() • reverse()
List Methods in Python Cont..

☞ max ():
• In Python, max() function is used to find maximum value in the list.
Syntax: max(list)
Example: [Link]
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp']
print("Max of list1 :",max(list1))
print("Max of list2 :",max(list2))

Output:
python [Link]
Max of list1 : 6
Max of list2 : python
List Methods in Python Cont..

☞ min ():
• In Python, min() function is used to find minimum value in the list.
Syntax: min(list)

Example: [Link]
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp']
print("Min of list1 :",min(list1))
print("Min of list2 :",min(list2))

Output:
python [Link]
Min of list1 : 1
Min of list2 : c
List Methods in Python Cont..

☞ list ():
• In python, list() is used to convert given sequence (string or tuple)
into list.
Syntax: list(sequence)

Example: [Link]
str="python"
list1=list(str)
print(list1)

Output:
python [Link]
['p', 'y', 't', 'h', 'o', 'n']
List Methods in Python Cont..
☞ append ():
The append() method adds a single item to the end of the list. This
method does not return new list and it just modifies the original.
Syntax: [Link](item)
where item may be number, string, list and etc.
Example: num=[1,2,3,4,5]
lang=['python','java']
[Link](6) Output:
print(num) python [Link]
[Link]("cpp") [1, 2, 3, 4, 5, 6]
print(lang)
['python', 'java', 'cpp']
list=[1,2,3,4]
[1, 2, 3, 4, [6, 7]]
[Link]([6,7])
print(list)
List Methods in Python Cont..

☞ remove ():
• In python, remove() method removes item from the list. It removes
first occurrence of item if list contains duplicate items. It throws an
“value error” if the item is not present in the list.
Syntax: [Link](item)
Example: [Link]
list1=[1,2,3,4,5]
list2=['A','B','C','B','D'] Output:
[Link](2) python [Link]
print(list1)
[Link]("B") [1, 3, 4, 5]
print(list2) ['A', 'C', 'B', 'D']
[Link]("E")
print(list2) ValueError: x not in list
List Methods in Python Cont..

☞ sort ():
• In python, sort() method sorts the list elements into descending or
ascending order. By default, list sorts the elements into ascending
order. It takes an optional parameter 'reverse' which sorts the list
into descending order. This method modifies the original list.
Syntax: [Link]()
Example: [Link]
list1=[6,8,2,4,10]
Output:
[Link]()
print("\n After Sorting:\n") python [Link]
print(list1) After Sorting:
print("Descending Order:\n") [2, 4, 6, 8 , 10]
[Link](reverse=True) Descending Order:
print(list1) [10, 8, 6, 4 , 2]
List Methods in Python Cont..

☞ reverse ():
• In python, reverse() method reverses elements of the list. i.e. the
last index value of the list will be present at 0th index. This method
modifies the original list and it does not return a new list.
Syntax: [Link]()
Example: [Link]
list1=[6,8,2,4,10]
[Link]()
print("\n After reverse:\n")
print(list1)
Output:
python [Link]
After reverse:
[10, 4, 2, 8 , 6]
List Methods in Python Cont..

☞ count():
• In python, count() method returns the number of times an element
appears in the list. If the element is not present in the list, it
returns 0.
Syntax: [Link](item)

Example: [Link]
num=[1,2,3,4,3,2,2,1,4,5,8]
cnt=[Link](2)
print("Count of 2 is:",cnt)
cnt=[Link](10)
print("Count of 10 is:",cnt) Output:
python [Link]
Count of 2 is: 3
Count of 10 is: 0
List Methods in Python Cont..

☞ index():
• In python, index () method returns index of the passed element. If
the element is not present, it raises a ValueError.
• If list contains duplicate elements, it returns index of first
occurred element.
• This method takes two more optional parameters start and end
which are used to search index within a limit.
Syntax: list. index(item [, start[, end]])
Example: [Link] Output:
list1=['p','y','t','o','n','p'] python [Link]
print([Link]('t')) 2
Print([Link]('p')) 0
Print([Link]('p',3,10)) 5
Print([Link]('z')) ) Value Error
List Methods in Python Cont..

☞ insert():
• In python, the insert() method inserts the item at the given index,
shifting items to the right.
Syntax: [Link](index,item)

Example: [Link]
num=[10,20,30,40,50]
[Link](4,60)
print(num)
[Link](7,70) Output:
print(num)
python [Link]
[10, 20, 30, 40, 60, 50]
[10, 20, 30, 40, 60, 50, 70]
List Methods in Python Cont..

☞ pop():
• In python, pop() element removes an element present at specified
index from the list.
Syntax: [Link](index)

Example: [Link]
num=[10,20,30,40,50]
[Link]()
print(num)
[Link](2)
Output:
print(num)
[Link](7) python [Link]
print(num) [10, 20, 30, 40]
[10, 20, 40]
IndexError: Out of range
List Methods in Python Cont..

☞ clear():
• In python, clear() method removes all the elements from the list.
It clears the list completely and returns nothing.
Syntax: [Link]()

Example: [Link]
num=[10,20,30,40,50]
[Link]()
print(num)
Output:
python [Link]
[]
List Methods in Python Cont..

☞ Extend():
The extend() method adds the items in list2 to the end of the list.
Syntax: [Link](list2)

Example: [Link]
list=[1,3,2]
list1=[0,5,6]
[Link](list1)
print(list) Output:
[1, 3, 2, 0, 5, 6]
Iterating a List
• A list can be iterated by using a for - in loop. A simple list
containing four strings can be iterated as follows..

Example: “[Link]”

lang=['python','c','java','php‘]
print("The list items are \n")
for i in lang:
print(i)
Output:
python [Link]
The list items are
python
c
java
php
How to delete or remove elements from a list?

• Python allows us to delete one or more items in a list by using


the del keyword.
• .The difference between del statement and pop() function is
that the del statement does not return any value while the
pop() function returns a value.
• The del statement can also be used to remove slices from a list
or clear the entire list.
How to delete or remove elements from a list?

Example:
“[Link]”

num = [1,2,3,4,5]
print(num)
del num[1]
print(num)
del num[1:3] Output:
print(num) python [Link]
del num[:] [1, 2, 3, 4, 5]
[1, 3, 4, 5]
[1, 5]
[]
Nested list
• A list inside another list is called a nested list and you can get
the behavior of nested lists in Python by storing lists within the
elements of another list.
• You can traverse through the items of nested lists using the for
loop.
• The syntax for nested lists is
Ex: nested_list=[[item1,item2,item3],
[item4,item5,item6],
[item7,item8,item9]]
nested_list[0]= [item1,item2,item3]
nested_list[1]= [item4,item5,item6]
nested_list[2]= [item7,item8,item9]
nested_list[0][1]=[item2]
• list=[]
• list1=[1,2,3]
• list2=[4,5,6]
• list3=[7,8,9]
• [Link](list1)
• [Link](list2)
• [Link](list3)
• list
• [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• list[0]
• [1, 2, 3]
• list[1]
• [4, 5, 6]
• list[2]
• [7, 8, 9]
• list[0][1]
• 2
• list[1][2]
• 6
• list[2][1]
• 8
Dictionaries
A dictionary is mutable and is another container type that can store any
number of Python objects, including other container types.
• Dictionaries consist of pairs (called items) of keys and their corresponding
values.
• Python dictionaries are also known as associative arrays or hash tables.
•dict={"v":"violet","o":"orange","b":"blue","y":"yellow"}

Creating Dictionary:
 It is a collection of an unordered set of key:value pairs which are enclosed
in curly braces. The key value pairs are seperated by commas.
 Eg: Alice: 2341
 The words to the left of colon are called as keys and the words to the right
of the colon are called as values.
 The dictionary is indexed by keys. Dictionary keys are case sensitive.
 Syntax: dictionary_name ={key_1:value_1, key_2:value_2,
key_3:value_3….key_n:value_n}
Ex:
dict={"v":"violet","o":"orange","b":"blue","y":"yellow"}
print(dict)

output:
{'v': 'violet', 'o': 'orange', 'b': 'blue', 'y': 'yellow'}

Mixed Dictionary:
The keys and their associated values can be of different types.
Ex:
mixed_dict={"A":65,"a":97,66:"B",98:"b" ,0:48}
print(mixed_dict)

output:
{'A': 65, 'a': 97, 66: 'B', 98: 'b', 0: 48}
How to Create Empty Dictionary:
Empty dictionary can be created with a pair of curly braces without any key
value pairs.
Syntax: dictionary_name={}
Ex:
dict1={}
print(dict1)
{}
By using dict() function:

• The built-in dict() function is used to create dictionary. The syntax for dict()
function when the optional keyword arguments used is,
• If no keyword argument is given, an empty dictionary is created. If
keyword arguments are given, the keyword arguments and their values of
the form kwarg = value are added to the dictionary as key:value pairs.
For example,
numbers=dict()
print(numbers)

output:
{}
By passing Keyword arguments in dict() functions:
Syntax: dict([**kwarg])
Ex:
dict1=dict(one=1,two=2,three=3)
print(dict1)

Output:
{'one': 1, 'two': 2, 'three': 3}
Acessing and modifying key: value pairs in Dictionaries:
Syntax for accessing the value for a key in dictionary is,
dictionary_name[key].
Ex:
dict1={“one”: 1, “two”: 2, “three”: 3}
dict1["one"]
Output:
1
modifying the value of existing key or adding a new key:
• The syntax for modifying the value of an existing key or for
adding a new key:value pair to a dictionary is,
• dictionary_name[key] = value
Ex:
Adding key:value pair to dict:
dict1={'one': 1, 'two': 2, 'three': 3}
dict1["four"]=4
print(dict1)
Output:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}

Modifying Existing key value:

dict1["one"]=2
print(dict1)
Output:
{'one': 2, 'two': 2, 'three': 3, 'four': 4}
Built-in Functions :
• Built-in Functions in dictionaries are:
• len()
• any()
• all()
• Sorted()
len():
Returns the number of items (key:value pairs) in dictionary
Ex:
dict1={'one': 2, 'two': 2, 'three': 3, 'four': 4}
len(dict1)
Output:
4
any() function:
The any() function returns True if any item in an iterable are true,
otherwise it returns False. If the iterable object is empty, the any() function
will return False.
Ex:
>>>dict1={'one': 2, 'two': 2, 'three': 3, 'four': 4}
any(dict1)
Output:
True

>>>dict3={1:12,"False":13}
>>>any(dict3)
Output: True

>>>dict3={0:13, 0:6}
>>>any(dict3)
Output: False
all() function:
Returns true value if all the keys in the dictionary are True else
returns false
Ex:
dict1={'one': 2, 'two': 2, 'three': 3, 'four': 4}
all(dict1)
Output:
True

dict2={0:"A",1:"B",2:"C"}
all(dict2)
Output:
False
sorted() function:
Returns a list of items, which are sorted based on dictionary keys
Ex:
dict={"one":1,"two":2,"three":3,"four":4}
sorted(dict) # sorted in ascending order.
['four', 'one', 'three', 'two']

>>>sorted(dict,reverse=True) # sorted in descending order.


['two', 'three', 'one', 'four']
sorted([Link]()) #sorted dictionary values in ascending order
[1, 2, 3, 4]
sorted([Link](),reverse=True)
[4, 3, 2, 1]
sorted([Link]()) #sorted dictionary key:value pair in ascending order
[('four', 4), ('one', 1), ('three', 3), ('two', 2)]
• Populating Dictionaries with key: value Pairs
• One of the common ways of populating dictionaries is to start
with an empty dictionary { }, then use the update () method to
assign a value to the key using assignment operator.
• If the key does not exist, then the key:value pairs will be
created automatically and added to the dictionary.
For example,
dict={}
[Link]({"one":1})
print(dict)
{'one': 1}
[Link]({"two":2,"three":3,"four":4})
print(dict)
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
Traversing of Dictionary:

• A for loop can be used to iterate over keys or values or


key:value pairs in dictionaries.
• If you iterate over a dictionary using a for loop, then, by
default, you will iterate over the keys.
• If you want to iterate over the values, use values() method
and for iterating over the key:value pairs, specify the
dictionary’s items() method explicitly.
For example:
dict1={"one":1,"two":2,"three":3,"four":4}
print("keys in the dictionary") Output:
for key in [Link](): keys in the dictionary
print(key) one
print("values in the dictionary") two
for value in [Link](): three
print(value) four
print("key and values in the dictionary") values in the dictionary
for key,value in [Link](): 1
print(key,":",value) 2
3
4
key and values in the
dictionary
one : 1
two : 2
three : 3
four : 4
The del Statement
• To delete the key:value pair, use the del statement followed
by the name of the dictionary along with the key you want to
delete.
syntax: del dict_name[key]
animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
del animals["c"]
animals
{'r': 'raccoon', 'm': 'moose'}
Methods in Dictionary:
>>>dir(dict)
Method to create a dictionary:
get() :
The get() method returns the value associated with the specified key in the
dictionary.
If the key is not present then it returns the default value.
If default is not given, it defaults to None, so that this method never raises a KeyError.
syntax: dictionary_name.get(key [,default])
Ex:
get() function:

dict1={'one': 1, 'two': 2, 'three': 3, 'four': 4}


[Link]("one")
1

print([Link]("five"))
None

[Link]("five",5)
5
• Clear() function:
• The clear() method removes all the key:value pairs from the
dictionary.
Syntax: dictionary_name. clear()
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
print(dict1)
{}
Popitem():
It removes and returns an arbitrary tuple pair from the
dictionary. Top of the dictionary is popped out.
syntax: dictionary_name.popitem
For Example:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
('four', 4)

Pop():
It removes the key from the dictionary and returns its value.
Syntax: dictionary_name.pop(key)
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]("one")
Output:
1
Values():
It returns the view consisting of all the values in the dictionary.
syntax: dictionary_name.values()
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
dict_values([1, 2, 3, 4])

Keys():
It returns the view consisting of all the keys in the dictionary.
syntax: dictionary_name.keys()
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
dict_keys(['one', 'two', 'three', 'four'])
Items():
The items() method returns a new view of dictionary’s key and
value pairs as tuples.
Syntax: dictionary_name. items()
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]()
Output:
dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
fromKeys():
The fromkeys() method creates a new dictionary from the given
sequence of elements with a value provided by the user.
• Syntax: dictionary_name.fromkeys(seq [, value])

For ex:
dict1={"apple":4,"orange":9,"mango":6}
dict2=[Link](dict1)
dict2
{'apple': None, 'orange': None, 'mango': None}
dict3=[Link](dict1,8)
dict3
{'apple': 8, 'orange': 8, 'mango': 8}
Update() function:
This function updates the key value pairs and is automatically added to the
dictionary.
• Syntax: dictionary_name.update([other])
Ex:
dict1={"one":1,"two":2,"three":3,"four":4}
[Link]({"five":5})
print(dict1)
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

[Link]({"six":6,"seven":7})
print(dict1)
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7}
• setdefault()
• The setdefault() method returns a value for the key present in
the dictionary. If the key is not present, then insert the key
into the dictionary with a default value and return the default
value.
• If key is present, default defaults to None, so that this method
never raises a KeyError.
Syntax: dictionary_name.setdefault (key[, default])
Ex:
dict1={"apple":4,"orange":9,"mango":6}
[Link]("apple")
4
[Link]("strawberry")
dict1
{'apple': 4, 'orange': 9, 'mango': 6, 'strawberry': None}
[Link]("pear",16)
16
dict1
{'apple': 4, 'orange': 9, 'mango': 6, 'strawberry': None, 'pear': 16}
Nested dictionaries:
Syntax: dictionary_name[“dict_marks”]
The dictionairies can be defined inside other dictionary
– CANNOT be concatenated
– CANNOT be repeated
– Can be nested
e.g., d = {"first":{1:1}, "second":{2:"a"}}
Nested Dictionary
In Python, a nested dictionary is a dictionary inside a dictionary. It's a
collection of dictionaries into one single dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
Here, the nested_dict is a nested dictionary with the dictionary dictA and
dictB They are two dictionary each having own key and value.
Ex 1:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22',
'sex': 'Female'}}
Ex 2: Accessing the Elements using the [ ] syntax
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
Output: John
27
Male
Tuple in Python
Tuple Creation
Tuple in Python
• In python, a tuple is a sequence of immutable elements or items.
• Tuple is similar to list since the items stored in the list can be
changed whereas the tuple is immutable and the items stored in
the tuple cannot be changed.
• A tuple can be written as the collection of comma-separated
values enclosed with the small brackets ( ).
Syntax: var = ( value1, value2, value3,…. )
Example: “[Link]”
t1 = () Output:
t2 = (123,"python", 3.7) python [Link]
t3 = (1, 2, 3, 4, 5, 6) ()
t4 = ("C",) (123, 'python', 3.7)
print(t1) (1, 2, 3, 4, 5, 6)
print(t2) ('C',)
print(t3)
print(t4)
Tuple Indexing
Tuple Indexing in Python
• Like list sequence, the indexing of the python tuple starts from
0, i.e. the first element of the tuple is stored at the 0th index,
the second element of the tuple is stored at the 1st index, and
so on.
• The elements of the tuple can be accessed by using the slice
operator [].
Example:
mytuple=(‘banana’,’apple’,’mango’,’tomato’,’berry’)

• mytuple[0]=”banana” mytuple[1:3]=[”apple”,”mango”]
• mytuple[2]=”mango”
Tuple Indexing in Python cont…
• Unlike other languages, python provides us the flexibility to use
the negative indexing also. The negative indices are counted
from the right.
• The last element (right most) of the tuple has the index -1, its
adjacent left element is present at the index -2 and so on until
the left most element is encountered.
Example: mytuple=(‘banana’,’apple’,’mango’,’tomato’,’berry’)

• mytuple[-1]=”berry” mytuple[-4:-2]=[“apple”,mango”]
• mytuple[-3]=”mango”
Tuple Operators
Tuple Operators in Python
It is known as concatenation operator used to concatenate two
+ tuples.
It is known as repetition operator. It concatenates the multiple
* copies of the same tuple.
It is known as slice operator. It is used to access the item from
[] tuple.
It is known as range slice operator. It is used to access the range
[:] of items from tuple.
It is known as membership operator. It returns if a particular
in item is present in the specified tuple.

It is also a membership operator and It returns true if a


not in particular item is not present in the tuple.
Tuple Operators in Python cont…

Example: “[Link]”
num=(1,2,3,4,5)
lang=('python','c','java','php')
print(num + lang) #concatenates two tuples
print(num * 2) #concatenates same tuple 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd index.
print('cpp' in lang) # prints False
print(6 not in num) # prints True

Output: python [Link]


(1, 2, 3, 4, 5, 'python', 'c', 'java', 'php')
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
java
('c', 'java', 'php')
False
True
How to add or remove elements from a tuple?
• Unlike lists, the tuple items cannot be updated or deleted as
tuples are immutable.
• To delete an entire tuple, we can use the del keyword with the
tuple name.

Example: “[Link]”
tup=('python','c','java','php')
Output:
tup[3]="html" python [Link]
print(tup)
del tup[3] 'tuple' object does not
print(tup) support item assignment
del tup
'tuple' object doesn't
support item deletion
Tuples are unchangeable, meaning that you cannot change, add, or remove
items once the tuple is created.
Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable

Ex 1: Convert the tuple into a list to be able to change it:


x = ("apple", "banana", "cherry")
y = list(x) #converting tuple to list using list()
y
Output: ['apple', 'banana', 'cherry']
y[1]="kiwi“ # changing an item
y
Output: ['apple', 'kiwi', 'cherry']
x=tuple(y) # converting list to tuple using tuple()
x
Output: ('apple', 'kiwi', 'cherry')
Add Items to tuple
Since tuples are immutable, they do not have a built-in append() method.
1. Convert into a list: Just like the workaround for changing a tuple, you
can convert it into a list, add your item(s), and convert it back into a tuple.
Ex 1: Convert the tuple into a list, add "orange", and convert it back into a
tuple
tuple1 = ("apple", "banana", "cherry")
y = list(tuple1)
y
Output: ['apple', 'banana', 'cherry']
[Link]("orange")
y
Output: ['apple', 'banana', 'cherry', 'orange']
tuple1 = tuple(y)
print(tuple1)
Output: ('apple', 'banana', 'cherry', 'orange')
Traversing of tuples
• A tuple can be iterated by using a for - in loop. A simple tuple
containing four strings can be iterated as follows..

Example: “[Link]”

lang=('python','c','java','php')
print("The tuple items are \n")
for i in lang:
print(i)
Output:
python [Link]
The tuple items are
python
c
java
php
Built in functions used on tuples
Tuples Functions in Python
• Python provides various in-built functions which can be used
with tuples. Those are
• len() • tuple()
• sum() • sorted()

☞len():
• In Python, len() function is used to find the length of tuple,i.e it
returns the number of items in the tuple.
Syntax: len(tuple)

Example: [Link] Output:


num=(1,2,3,4,5,6) python [Link]
print("length of tuple :",len(num)) length of tuple : 6
Tuple Functions in Python Cont..

☞sum ():
• In python, sum() function returns sum of all values in the tuple. The
tuple values must in number type.
Syntax: sum(tuple)

Example: [Link]
t1=(1,2,3,4,5,6)
print("Sum of tuple items :",sum(t1))

Output:
python [Link]
Sum of tuple items : 21
Tuple Functions in Python Cont..
☞sorted ():
• In python, The sorted() function returns a sorted copy of the tuple
as a list while leaving the original tuple untouched.
• .Syntax: sorted(tuple)
Example: [Link]
num=(1,3,2,4,6,5)

lang=('java','c','python','cpp')

print(sorted(num))

Print(sorted(num,reverse=True)

print(sorted(lang))
Output:
[1, 2, 3, 4, 5, 6]
['c', 'cpp', 'java', 'python‘]
Tuple Functions in Pytho n Cont..

☞tuple ():
• In python, tuple() is used to convert given sequence (string or list)
into tuple.
Syntax: tuple(sequence)

Example: [Link]
str="python"
Output:
t1=tuple(str)
python [Link]
print(t1) ('p', 'y', 't', 'h', 'o', 'n‘)
num=[1,2,3,4,5,6] (1, 2, 3, 4, 5, 6)
t2=tuple(num)
print(t2)
Tuple Functions in Pytho n Cont..

☞tuple ():
• In python, tuple() is used to convert given sequence (string or list)
into tuple.
Syntax: tuple(sequence)

Example: [Link]
str="python"
Output:
t1=tuple(str)
python [Link]
print(t1) ('p', 'y', 't', 'h', 'o', 'n‘)
num=[1,2,3,4,5,6] (1, 2, 3, 4, 5, 6)
t2=tuple(num)
print(t2)
Tuple Methods in Python Cont..

☞count():
• In python, count() method returns the number of times an element
appears in the tuple. If the element is not present in the tuple, it
returns 0.
Syntax: [Link](item)

Example: [Link]
num=(1,2,3,4,3,2,2,1,4,5,8)
cnt=[Link](2)
print("Count of 2 is:",cnt)
cnt=[Link](10)
print("Count of 10 is:",cnt) Output:
python [Link]
Count of 2 is: 3
Count of 10 is: 0
Tuple Methods in Python Cont..

☞index():
• In python, index () method returns index of the passed element. If
the element is not present, it raises a ValueError.
• If tuple contains duplicate elements, it returns index of first
occurred element.
• This method takes two more optional parameters start and end
which are used to search index within a limit.
Syntax: [Link](item [, start[, end]])
Example: [Link] Output:
t1=('p','y','t','o','n','p') python [Link]
print([Link]('t')) 2
Print([Link]('p')) 0
Print([Link]('p',3,10)) 5
Print([Link]('z')) ) Value Error
Relation between Tuples and Lists
• Tuples are immutable, and usually, contain a heterogeneous
sequence of elements that are accessed via unpacking or
indexing.
• Lists are mutable, and their items are accessed via indexing.
• Items cannot be added, removed or replaced in a tuple.
• Ex:
• tuple=(10,20,30,40,50)
• tuple[0]=15
• Traceback (most recent call last):
• File "<pyshell#5>", line 1, in <module>
• tuple[0]=15
• TypeError: 'tuple' object does not support item assignment
Relation between Tuples and Lists
Convert tuple to list:
X = (10,20,30,40,50)
tuple_to_list = list(x)
print(tuple_to_list)
[10, 20, 30, 40, 50]

• If an item within a tuple is mutable, then you can change it.


Consider the presence of a list as an item in a tuple, then any
changes to the list get reflected on the overall items in the
tuple. For example,
Relation between Tuples and Lists

• lang=["c","c++","java","python"]
• tuple=(10,20,30,40,50,lang)
• Print(tuple)
• (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python'])
• [Link]("php")
• lang
• ['c', 'c++', 'java', 'python', 'php']
• tuple
• (10, 20, 30, 40, 50, ['c', 'c++', 'java', 'python', 'php'])
Relation between Tuples and dictionaries
• Tuples can be used as key:value pairs to build dictionaries. For
example,
num=(("one",1),("two",2),("three",3))
tuple_to_dict=dict(num)
print(tuple_to_dict)
{'one': 1, 'two': 2, 'three': 3}
num
(('one', 1), ('two', 2), ('three', 3))
• The tuples can be converted to dictionaries by passing the tuple
name to the dict() function. This is achieved by nesting tuples
within tuples, wherein each nested tuple item should have two
items in it .
• The first item becomes the key and second item as its value when
the tuple gets converted to a dictionary
• The method items() in a dictionary returns a list of tuples
where each tuple corresponds to a key:value pair of the
dictionary. For example,
• dict1={"y":"yellow","o":"orange","b":"blue"}
• [Link]()
• dict_items([('y', 'yellow'), ('o', 'orange'), ('b', 'blue')])
• for symbol,colour in [Link]():
• print(symbol," ",colour)
Output:
• y yellow
• o orange
• b blue
• Tuple packing and unpacking:
The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
t=12345,54321,'hello!'
t
(12345, 54321, 'hello!')
The values 12345, 54321 and 'hello!' are packed together into a tuple.
The reverse operation of tuple packing is also possible. For example,
tuple unpacking
x,y,z=t
x
12345
y
54321
z
'hello!‘
Tuple unpacking requires that there are as many variables on the left side of the
equals sign as there are items in the tuple.
Note that multiple assignments are really just a combination of tuple packing and
unpacking.
t = 12345,54321,'hello'
t
(12345, 54321, 'hello')
# The values 12345, 54321 and ‘hello’ are packed together
into a tuple
# The reverse operation (tuple unpacking) of tuple packing is
also possible.
x, y, z=t
x
12345
y
54321
z
'hello'
• Populating tuples with items:
• You can populate tuples with items using += operator and also by
converting list items to tuple items.
• Example: Ex: 2
tuple_items=() x=()
tuple_items+=(10,) y=x+(10,)
tuple_items+=(20,30,) y
(10,)
print(tuple_items) y=y+(20,30)
(10, 20, 30) y
(10, 20, 30)
• converting list to tuple :
list_items=[]
list_items.append(50)
list_items.append(60)
list_items
[50, 60]
tuple1=tuple(list_items)
print(tuple1)
(50, 60)
• Using zip() Function
• The zip() function makes a sequence that aggregates elements from each
of the iterables (can be zero or more). The syntax for zip() function is,
• zip(*iterables)
• An iterable can be a list, string, or dictionary.
• It returns a sequence of tuples, where the i-th tuple contains the i-th
element from each of the iterables.

For Example,
x=[1,2,3]
y=[4,5,6]
zipped=zip(x,y)
list(zipped)
[(1, 4), (2, 5), (3, 6)]
Here zip() function is used to zip two iterables of list type
To loop over two or more sequences at the same time, the
entries can be paired with the zip() function. For
example,
symbol=("y","o","b","r")
colour=("yellow","orange","blue","red")
for symbol,colour in zip(symbol,colour):
print(symbol," ",colour)
Output:
y yellow
o orange
b blue
r red
Since zip() function returns a tuple, you can use a for loop
with multiple iterating variables to print tuple items.
• SETS:
• A set is an unordered collection with no dupli- cate items.
• Sets also support mathematical operations, such as union,
intersection, difference, and symmetric difference.
• Curly braces { } or the set() function can be used to create sets with
a comma-separated list of items inside curly brackets { }.
• To create an empty set you have to use set() and not { } as the
later creates an empty dictionary.
Set operations:
Example:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
Output: {'pear', 'orange', 'banana', 'apple'}
>>> 'orange' in basket
Output: True
>>> 'crabgrass' in basket
Output: False
Difference:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}

a-b
{'r', 's', 'd', 'b'}
It Displays letters present in a, but not in b, are printed.

Union:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}

a|b
{'b', 'z', 'c', 'a', 'r', 'd', 'm', 'l', 's'}
Letters present in set a and set b are printed.
Intersection:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}

a&b
{'c', 'a'}
Letters present in both set a and set b are printed

Symmetric Difference:
a={'b', 'c', 'a', 'r', 'd', 's'}
b={'z', 'c', 'a', 'm', 'l'}

a^b
{'z', 'b', 'r', 'd', 'm', 'l', 's'}
Letters present in set a or set b, but not both are printed.
Length function():
>>>basket={'apple','orange','apple','pear','apple','banana'}
>>>print(basket)
>>>{'pear', 'apple', 'orange', 'banana'}
>>>len(basket)
4
Total number of items in the set basket is found using the len()
function

Sorted function():
>>>sorted(basket)
['apple', 'banana', 'orange', 'pear']
>>>sorted(basket, reverse=True)
['pear', 'orange', 'banana', 'apple']
The sorted() function returns a new sorted list from items in the
set .
Set Methods:

You can get a list of all the methods associated with the set by passing the set
function to dir().

dir(set)
[' and ', ' class ', ' class_getitem ', ' contains ', ' delattr ',
' dir ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ',
' getstate ', ' 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',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove',
'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
Set Methods:
 Add():
 The add() method adds an item to the set set_name.
 Syntax: set_name.clear()
basket={"orange","Apple","strawberry","orange" }
basket
{'orange', 'Apple', 'strawberry'}
[Link]("pear")
basket
{'orange', 'Apple', 'strawberry', 'pear'}
Set Methods:
 Difference():
• The difference() method returns a new set with items in the set set_name that
are not in the others sets.
• Syntax : set_name.difference(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.difference(flowers)
{'orchid', 'daisies'}

 intersection():
• The intersection() method returns a new set with items common to the set
set_name and all others sets.
• Syntax: set_name. Intersection(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.intersection(flowers)
{'roses', 'tulips'}
 Symmetric Difference: Set Methods:
 The method symmetric difference() returns a new set with items in either
the set or other but not both.
• Syntax : set_name. symmetric_difference(other)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers. symmetric_difference (flowers)
{'orchid', 'lilies', 'daisies', 'sunflowers'}

 Union:
• The method union() returns a new set with items from
• the set set_name and all others sets.
• Syntax: set_name.union(*others)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.union(flowers)
{'orchid', 'lilies', 'tulips', 'daisies', 'roses', 'sunflowers'}
Set Methods:
 isdisjoint:

• The isdisjoint() method returns True if the set set_name has no items in
common with other set. Sets are disjoint if and only if their intersection is
the empty set.
• Syntax : set_name.isdisjoint(other)
Ex:
flowers={"roses","tulips","lilies","sunflowers"}
american_flowers={"roses","orchid","tulips","daisies"}
american_flowers.isdisjoint(flowers)
False

a= {'b', 'c', 'a', 'd'}


b={'f', 'g', 'h', 'e'}
[Link](b)
True
Set Methods:
 issubset:
• The issubset() method returns True if every item in the set set _name is in other set.
• Syntax : set_name.issubset(other)
Ex: x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = [Link](y)
print(z)
Output: True
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = [Link](x)
print(z)
Output: False

c={"a","b","c","d"}
d={"a","b","c","d"}
[Link](d)
True
Set Methods:
 Issuperset():
• The issuperset() method returns True if every element in other set is in the
set set_name.
• Syntax : set_name.issuperset(other)
Ex: x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = [Link](y)
print(z)
Output: True
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = [Link](x)
print(z)
Output: False
Set Methods:
 Pop():
• The method pop() removes and returns an arbitrary item from
the set set_name. It raises KeyError if the set is empty.
• Syntax : set_name.pop()
Ex:
d={'b', 'c', 'a', 'd'}
item=[Link]()
print(item)
b
print(d)
{'c', 'a', 'd'}
Pop()
The pop() method for sets in Python does not necessarily remove the last
element. Sets in Python are unordered collections, which means the order of
elements is not guaranteed. When you use pop() on a set, it removes and
returns an arbitrary element from the set. It doesn't specifically target the last
element.
If you need to remove a specific element from the set, you should use the
remove()

x={'q','w','e','r','t','y'}
y=[Link]()
print(y) #returns the poped value
Output: w
print(x)
Output: {'q', 'e', 't', 'r', 'y'}
remove()
The “remove()” method for sets in Python removes the specified element
from the set. However, unlike the ‘pop()’ method, it doesn't return the
removed element; it returns ‘None’ Therefore, when you print the result of
‘[Link](‘r ’)’ , it will print ‘None’.

Ex: x={'q','w','e','r','t','y'}
y=[Link]('r')
print(y) #doesn’t return removed value instead gives “None”
Output: None
print(x)
Output: {'w', 'q', 'e', 't', 'y'} # “r” has been removed from the set
OR
x={'q','w','e','r','t','y'}
[Link]('r')
print(x)
{'w', 'q', 'e', 't', 'y'}
Set Methods:
 remove():
• The method remove() removes an item from the set set_name. It raises
KeyError if the item is not contained in the set.
• Syntax : set_name.remove(item)
• Ex:
• c={"a","b","c","d"}

[Link]("a")
print(c)
{'b', 'c', 'd'}

 update():
Update the set set_name by adding items from all others sets.
Syntax : set_name.update(*others)
Ex:
c={'b', 'c', 'd'}
d={"e","f","g"}

[Link](d)
print(c)
{'b', 'c', 'f', 'g', 'd', 'e'}
Set Methods:
 Discard():
• The discard() method removes an item from the set set_name if it is present.
Syntax: set_name.discard(item)
Ex:

d={"e","f","g"}
[Link]("e")
print(d)
{'f', 'g'}

 Clear():
• The clear() method removes all the items from the set set_name.
• Syntax: set_name.clear()
• Ex: alpha={"a","b","c","d"}
• print(alpha)
output: {'a', 'b', 'c', 'd'}
[Link]()
print(alpha)
output: set()
Difference between discard() and remove() in python sets.
The discard() method removes the specified item from the set. This method is
different from the remove() method, because the remove() method will raise an
error if the specified item does not exist, and the discard() method will not.

d={"e","f","g"}
[Link]("e")
print(d)
Output: {'g', 'f'}
d={"e","f","g"}
[Link]("h") # specified item doesn’t exist in set. discard() doesn’t raise error
print(d)
Output: {'g', 'f', 'e'}
d={"e","f","g"}
[Link]("h") #specified item doesn’t exist in set. remove() raises error
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
[Link]("h")
KeyError: 'h'
Traversing of sets

You can iterate through each item in a set using a for loop.
Ex:
alpha={"a","b","c","d"}
print(alpha)
{'a', 'b', 'c', 'd'}
for i in alpha:
print(i)
Output:
a
b
c
d
Frozenset

• A frozenset is basically the same as a set, except that it is


immutable. Once a frozenset is created, then its items cannot be
changed.
• The frozensets have the same functions as normal sets, except none
of the functions that change the contents (update, remove, pop,
etc.) are available.

methods in Frozenset:
1. >>> dir(frozenset)
[' and ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq
', ' format ', ' ge ', ' getattribute ', ' gt ', ' hash ', ' init ', '
init_ subclass ', ' iter ', ' le ', ' len ', ' lt ', ' ne ', ' new ', ' or
', ' rand ', ' reduce ', ' reduce_ex ', ' repr ', ' ror ', ' rsub
', ' rxor ', ' setattr ', ' sizeof ', ' str ', ' sub ', ' subclasshook ', '
xor ', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset',
'issuperset', 'symmetric_difference', 'union']
Frozen set is just an immutable version of a Python set object. While elements of a
set can be modified at any time, elements of the frozen set remain the same after
creation.
Sy: frozenset([iterable])
Iterable can be set, dictionary, tuple, etc.
Example 1:
mylist = ['apple', 'banana', 'cherry']
mylist[1]="strawberry“
print(mylist)
Output: ['apple', 'strawberry', 'cherry']
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)
Output: frozenset({'apple', 'cherry', 'banana'})
x[1]="strawberry"
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
x[1]="strawberry"
TypeError: 'frozenset' object does not support item assignment
Frozenset Methods
• List of methods available for frozenset .For example,
Convert set to frozenset
set1 = {"d","o","g"}
fs=frozenset({"d","o","g"})
print(fs)
Output: frozenset({'d', 'o', 'g'})
Convert list to frozenset:
list=[10,20,30]
lfs=frozenset(list)
print(lfs)
Output: frozenset({10, 20, 30})
Convert dict to frozenset
dict1={"one":1,"two":2,"three":3,"four":4}
dfs=frozenset(dict1)
print(dfs)
Output: frozenset({'four', 'one', 'three', 'two'})
• frozenset used as a key in dictionary and item in set:
item=frozenset(["g"])
dict1={"a":95,"b":96,"c":97,item:6}
print(dict1)
{'a': 95, 'b': 96, 'c': 97, frozenset({'g'}): 6}
EX:
item=frozenset(["g"])
set={"a","b","c",item}
print(set)
{frozenset({'g'}), 'a', 'c', 'b'}
Files in Python
Files in Python
 ☞ FILE HANDLING:
 It is a mechanism by which we can read data of disk
files in python program or write back data from
python program to disk files.

 So far in our python program the standard input in


coming from keyboard an output is going to monitor.
 No where data is stored permanent and entered data is
present as long as program is running BUT file
handling allows us to store data entered through python
program permanently in disk file and later on we can
read back the data.
Files in Python
Files in Python
 Python supportsTwo files:
 1. Text Files
 2. Binary Files
☞Text Files:
 Text file stores information in ASCII OR UNICODE character.
In text file everything will be stored as a character for example
if data is “computer” then it will take 8 bytes and if the data is
floating value like 11237.9876 it will take 10 bytes.
 In text file each line is terminated by special character called
EOL. In text file some translation takes place when this EOL
character is read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both.
 Ex: Examples of text files include word processing documents, log
files, and saved email messages.
Files in Python
☞ Binary files:
 It stores the information in the same format as in the memory
i.e. data is stored according to its data type so no translation
occurs.
 In binary file there is no delimiter for a new line
 Binary files are faster and easier for a program to read and
write than text files.
 Data in binary files cannot be directly read, it can be read only
through python program for the same.
 Ex: Executable files, compiled programs, SAS and SPSS
system files, spreadsheets, compressed files, and graphic
(image) files are all examples of binary files.
Files in Python
Common extensions for binary file formats:
 Images: jpg, png, gif, bmp, tiff, psd,...
 Videos: mp4, mkv, avi, mov, mpg, vob,...
 Audio: mp3, aac, wav, flac, ogg, mka, wma,...
 Documents: pdf, doc, xls, ppt, docx, odt,...
 Archive: zip, rar, 7z, tar, iso,...
 Database: mdb, accde, frm, sqlite,...
 Executable: exe, dll, so, class,...
Common extensions for text file formats:
 Web standards: html, xml, css, svg, json,...
 Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh,...
 Documents: txt, tex, markdown, asciidoc, rtf, ps,...
 Configuration: ini, cfg, rc, reg,...
 Tabular data: csv, tsv,...
Files in Python
 File Paths:
 When you access a file on an operating system, a file path is required.
The file path is a string that represents the location of a file. It’s broken
up into three major parts:
 Folder Path: The file folder location on the file system where
subsequent folders are separated by a forward slash / (Unix) or
backslash \ (Windows)
 File Name: the actual name of the file
 Extension: the end of the file path pre-pended with a period (.) used
to indicate the file type
Files in python
 C:\Users\KLEBCA-2\Desktop\Desktop Files\lesson_plan

 In Windows use backslash (\) and in Linux use forward slash (/) to
separate the components of a path.

 The backslash (or forward slash) separates one directory name from
another directory name in a path and it also divides the file name from
the path leading to it.

 Backslash (\) and forward slash (/) are reserved characters and you
cannot use them in the name for the actual file or directory.
Files in python
 [Link]
[Link]/redirect

 File and Directory names in Windows are not case sensitive while in
Linux it is case sensitive.
 For example, the directory names ORANGE, Orange, and orange are
the same inWindows but are different in Linux Operating System.
 In Windows, volume designators (drive letters) are case-insensitive. For
example, "D:\" and "d:\" refer to the same drive.
Files in python
 The reserved characters that should not be used in naming files and
directories are < (less than), > (greater than),: (colon), " (double
quote), / (forward slash), \ (backslash), | (vertical bar or pipe), ?
(question mark) and * (asterisk).

Fully Qualified path and Relative path:


files -- These contain information. Examples include be csv files, or python
files.
directories -- These contain files and directories inside of them
Your filesystem starts from a root directory, notated by a forward slash /
on Unix and by a drive letter C:/ on Windows.
Files in python
 Absolute and Relative file paths:
 Absolute file paths are notated by a leading forward slash or drive label.
 For example,
 /home/example_user/example_directory
 C:/system32/[Link].
 An absolute file path describes how to access a given file or directory,
starting from the root of the file system. A file path is also called a
pathname.
 Relative file paths are notated by a lack of a leading forward slash. For
example, example directory.
Files in python
Files in python
Examples of the relative path are given below:

 "..\[Link]" specifies a file named "[Link]"


located in the parent of the current directory fauna.
 ".\[Link]" specifies a file named "[Link]" located
in a current directory named fauna.
 "..\..\[Link]" specifies a file that is two directories
above the current directory india
 The following figure shows the structure of sample
directories and files
 A path to an entity (in this case, a file, folder, or web page) describes the
entity’s unique location within a hierarchical directory or website
structure.
 Paths can be of two types. They can either be absolute or relative.
 Absolute Path
 The absolute path (also known as the full path) of an entity
contains the complete information (from the root to the ending)
needed to locate it. The absolute path is not affected by the user’s
current working directory, and it always includes the root
directory as a starting point.
 The absolute path to the Macaroni file is
C:\Recipes\Pasta\Macaroni
 While the absolute path to the CheeseCake file is:
C:\Recipes\Cakes\CheeseCake
Note : Here, C:\ is the root directory, and C:\Recipes is the current
working directory.
 Relative Path
 The relative path of an entity contains the information needed to
locate that entity relative to the user’s current working directory.
 The relative path disregards the information needed to locate the
current working directory from the root directory and only focuses
on the route from the working directory to the entity.
 Ex: The relative paths to the Macaroni file and the CheeseCake file.
Since the relative path uses the current working directory,
the Macaroni file’s relative path is Pasta\Macaroni and the relative path
to the CheeseCake file is Cakes\CheeseCake.
 Note how we are simply studying the file paths relative to the
current working directory, C:\Recipes.
Files in python

 Creating and reading text data:


1. opening file:
• We should first open the file for read or write by specifying
the name of file and mode.
2. performing read/write:
• Once the file is opened now we can either read or write for
which file is opened using various functions available.
3. closing file:
• After performing operation we must close the file and
release the file for other application to use it.
Files in python
 Open a file:
 We have to open a file using built-in function open()
 This function returns a file object, also called a file handler that provides
methods for accessing the file.
 syntax of open() function is given below.

 file_handler = open(filename, mode)


 file_handler: File handler object returned for filename
 filename: name of the file that we want to access
 accessmode: read, write, append etc
Files in python
Opening File:
Ex:
 myfile = open(“[Link]”)
 here disk file “[Link]” is loaded in memory and its
reference is linked to “myfile” object, now python program will
access “[Link]” through “myfile” object.
 here “[Link]” is present in the same folder where .py file
is stored otherwise if disk file to work is in another folder we have
to give full path.
Files in python
Opening File:
 myfile = open(“[Link]”,”r”)
 here “r” is for read (although it is by default, other options
are “w” for write, “a” for append)

 myfile = open(“d:\\mydata\\[Link]”,”r”)
 Here we are accessing “[Link]” file stored in separate
location i.e. d:\mydata folder.
 At the time of giving path of file we must use double
backslash(\\) in place of single backslash because in python single
slash is used for escape character and it may cause problem like if
the folder name is “nitin” and we provide path as
d:\nitin\[Link] then in \nitin “\n” will become escape character
for new line, SO ALWAYS USE DOUBLE BACKSLASH IN PATH.
Files in python
Opening File:
myfile = open(“d:\\mydata\\[Link]”,”r”)
 another solution of double backslash is using “r” before
the path making the string as raw string i.e. no special meaning
attached to any character as:
 myfile = open(r“d:\mydata\[Link]”,”r”)
 In the above example “myfile” is the file object or file handle or
file pointer holding the reference of disk file.
 In python we will access and manipulate the disk file through
this file handle only.
Raw String
A raw string is created by prefixing the character r or R to the string.
In Python, a raw string ignores all types of formatting within a string
including the escape characters.
Ex 1: Without raw string
s = 'Hi\nHello'
print(s)
Output: Hi
Hello
Ex 2: With raw string
raw_s = r'Hi\nHello'
print(raw_s)
Output: Hi\nHello
Files in python
Access modes of the File:
Mode Description

“r” Opens the file in read only mode and this is the default mode.

“w” Opens the file for writing. If a file already exists, then it’ll get overwritten. If the file
does not exist, then it creates a new file.
“a” Opens the file for appending data at the end of the file automatically. If the file does
not exist it creates a new file.
“r+” Opens the file for both reading and writing
“w+” Opens the file for reading and writing. If the file does not exist it creates a new file. If
a file already exists then it will get overwritten.
“a+” Opens the file for reading and appending. If a file already exists, the data is appended.
If the file does not exist it creates a new file.
Files in python
Access modes of the File:
Mode Description

“x” Creates a new file. If the file already exists, the operation fails.

“rb” Opens the binary file in read-only mode.


“wb” Opens the file for writing the data in binary format.

“rb+” Opens the file for both reading and writing in binary format.
Files in python
Example program:
# Create a file:
fp=open("[Link]","x")

# Write Data in file:


fp=open("[Link]","w")
[Link] ('hi there, this is a first line of file.')

# Read Data from file:


fp=open("[Link]","r")
for each_row in fp:
Output:
print(each_row) hi there, this is a first line of file.
hi there, this is a first line of [Link]
# Append Data in file:
fp=open("[Link]","a")
[Link]('klebca \n')
fp=open("[Link]","r")
for each_row in fp:
print(each_row)
[Link]()
Files in python
Closing file:

 As reference of disk file is stored in file handler so to close we must call


the close() function through the file handler and release the file.
 File closing is done with close() method.
 Syntax:
 [Link]()

 Note: open function is built-in function used standalone while close()


must be called through file handle
Ex: Output:
f=open("[Link]","r+") Name of the file:
print("Name of the file:",[Link]) [Link]
[Link]() File closed
print("File closed")
Files in python
 If an exception occurs while performing some operation on the file, then the
code exits without closing the file.
 In order to overcome this problem, you should use a try-except- finally block to
handle exceptions.
 For example, Ex:
try:
f = open("files_related.txt", "w")
try:
[Link]('Hello World!')
finally:
[Link]()
except IOError:
print('oops!')

 You should not be writing to the file in the finally block, as any exceptions raised
there will not be caught by the except block.
 The except block executes if there is an exception raised by the try block.
 The finally block always executes regardless of whatever happens.
Files in python
Use of “with” statement to open and close files:

 Instead of using try-except-finally blocks to handle file opening and closing operations,
a much cleaner way of doing this in Python is using the with statement.
 You can use a with statement in Python such that you do not have to close the file
handler object.
Example: opening a file, manipulating a file and closing it with

open(“[Link]”,”w”) as f:
[Link](“Hello Python!”)

 The with statement creates a context manager and it will automatically close the file
handler object for you when you are done with it, even if an exception is raised on the
way, and thus properly managing the resources.
Files in python
Use of “with” statement to open and close files:
Ex:
file_input = input('File Name: ') File Name:
[Link]
with open(file_input, 'w') as info:
klebca
for x in range(10): klebca
[Link]('klebca \n') klebca
klebca
klebca
with open(file_input, 'r') as info: klebca
data=[Link]() klebca
klebca
print(data) klebca
klebca
Files in python
File Object Attributes
Once a file is opened , we have one file object, which contain various info related to that
file.
1. [Link] – Returns true if the file is closed, False otherwise
2. [Link] – Returns access mode with wich file was opened
3. [Link]- Name of the file

Ex:
f=open("[Link]","w")
print("Name of the file:",[Link])
print("Closed or not :",[Link])
print("Opening mode :",[Link])

Output:
Name of the file: [Link]
Closed or not : False
Opening mode : w
File Methods to Read and Write Data:
Method Syntax Description

read() File_handler.read([size]) Used to read the contents of a file up to the size and return it as a string

readline() File_handler.readline() This method is used to read a single line


readlines() File_handler.readlines() This method is used to read all the lines of a file as list items.

write() File_handler.write(string) This method will write the contents of the strings to the file.

writelines() File_handle.writelines(sequence) This method will write a sequence of strings to the file

tell() File_handler.tell() File handler’s current position within the file is measured in bytes from the
beginning of the file

seek() File_handler.seek(offset, Change the file handler’s position. Position is computed by adding offset to
from_what) reference point. Reference point is selected by the from_what argument.
File Methods to Read and Write Data:

Ex: Output:
One
f=open("[Link]","r")# opening a file Two
line1 = [Link]() # reading a line Three
print(line1) ['five\n', 'six\n', 'seven\n', 'eight\n']
line2 = [Link]() # reading a line O
print(line2) n
line3 = [Link]() # reading a line e
print(line3)
line4 = [Link]() # reading a line
print(line4)
lines=[Link]()
print(list(lines))
for ch in line1:
print(ch)
[Link]()
..
writelines():
Ex:
f = open("[Link]", “w")
[Link](["See you soon!", "Over and out."])
[Link]()
#open and read the file :
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
See you soon!Over and out.
..
writelines():
Ex:
f = open("[Link]", “w")
[Link](["See you soon!", "Over and out."])
[Link]()
#open and read the file
f = open("[Link]", "r")
print([Link]())
fseek(5,0)
print([Link]())
[Link]()
Output:
See you soon!Over and out.
ou soon!Over and out.
..
Read Binary File:
#Opening a binary File in Read Only Mode
with open(r'C:\Test\\[Link]', mode='rb') as binaryFile:
lines = [Link]()
print(lines)
We are reading all the lines in the file in the lines variable above and print all the lines read in
form of a list.
Write Binary File
#Opening a binary File in Write Mode
with open('C:\\Test\\[Link]', mode='wb') as binaryFile:
#Assiging a Binary String
lineToWrite = b'You are on Banglore.'
#Writing the binary String to File.
[Link](lineToWrite)
#Closing the File after Writing
[Link]()
The Pickle Module
 The pickle module implements binary protocols for serializing and de-serializing a Python
object structure.
 This module can take any python object and convert it to a string representation (byte
stream).
 If you have an object x and a file handler f, then it can be opened for writing as below
[Link](x,f)
 Reconstructing the object from the string representation is called as unpickling.
 If f is the file handler then the way to unpickle the object is,
 x = [Link](f) The load method reads a pickled object and reconstructs the object.
 The pickle module is used for implementing binary protocols for
serializing and de-serializing a Python object structure.
 Pickling: It is a process where a Python object hierarchy is
converted into a byte stream.
 Unpickling: It is the inverse of the Pickling process where a byte
stream is converted into an object hierarchy.
 dumps() – This function is called to serialize an object hierarchy.
 loads() – This function is called to de-serialize a data stream.
 writing operation in binary files
import pickle
l=[10,43,76,33]
x=open("yt_l.dat","wb") #mode 'wb' for writing information
[Link](l,x) #list name, file object name
print("Data Successfully written into File")
[Link]()
 Reading operation from Binary File
import pickle
x=open("yt_l.dat","rb") #mode 'rb' for reading information
y=[Link](x)
print(y)
[Link]
 Writing and Reading operations in Binary files
import pickle
l=eval(input("enter the list:"))
x=open("yt_l.dat","w+b")
[Link](l,x) #list name, file object name
print("Data Successfully written into File")
[Link](0) #to read information from begining, so the position will be zero'0'
y=[Link](x)
print(y)
[Link]()
#in the above program if you don't use seek() method it throws an error because the
cursor will be pointing at the end of the string. To read data from beginning we use
seek(0) - 0 is the position
Output: enter the list:[17,'preetha',11.5]
Data Successfully written into File
€]q (KX preethaqG@' e. (in Notepad)
#writing data into file using dump()
[17, 'preetha', 11.5]
#reading data from file using load() data will be
printed in python shell after reading
Characteristics of the CSV format
 Characteristics of the CSV format are:
 Each record is located on a separate line, delimited by a line break
(CRLF)
 A line break may or may not be present at the end of the last record in
the file.
 Optional header line may appear as the first line of the file.
 Commas are to be used to separate the fields in each record. Each line
should have the same number of fields throughout the file.
 Double quotes may or may not be used to enclose each field.
Write a program in python to read data from an external
file test_meet.csv
Step 1: open Notepad and enter the data. Save the file as test_meet.csv

Note: The file test_meet.csv has to be saved where the python shell is
available. If not it is mandatory to give Absolute path.
Reading data from CSV file
import csv
with open('test_meet.csv') as cs:
csv_reader=[Link](cs)
for line in csv_reader:
print(line)
[Link]()
Output:
Reading and Writing CSV (Comma Separated Values) Files
 [Link]() method is used to read from a CSV file.
 [Link](csvfile): csv is the module name and csvfile is the file
object. This returns a csv reader object which will iterate over lines
in the given csvfile.
 [Link](csvfile): This method returns a csv writer object
responsible for converting the user’s data into comma separated
strings on the given file like object.
 [Link](row): csvwriter is the object returned by
writer() method and writerow() method will write the row
argument to the writer() method’s file object.
 [Link](rows): writerows() method will write all the
rows argument to the writer() method’s file object.
Writing Data into CSV file
import csv
with open('test_demo.csv','w+') as cs1:
csv_writer = [Link](cs1)
csv_writer.writerow(['1009','Rahul','India'])
print("data inserted successfully")

[Link](0)
csv_reader = [Link](cs1)

for line in csv_reader:


print(line)
[Link]()

Output: data inserted successfully


['1009', 'Rahul', 'India']
To give multiple inputs
import csv

data_to_write = [['1009', 'Rahul', 'India'], ['1010', 'Ramya', 'India']]

with open('test_demo.csv', 'w+', newline='') as cs1:


csv_writer = [Link](cs1)
csv_writer.writerows(data_to_write)
print("Data inserted successfully")

# Move the file cursor back to the beginning


[Link](0)

csv_reader = [Link](cs1)

for line in csv_reader:


print(line)
Output: Data inserted successfully
['1009', 'Rahul', 'India']
['1010', 'Ramya', 'India']
Reading and Writing CSV (Comma Separated Values) Files

 Class [Link](f,fieldnames=None, restkey=None)


Creates an object that operates like a regular reader but maps
the information in each row to an OrderedDict.
Class [Link](f, fieldnames, extrasaction=‘raise’)
Introduction to Object Oriented Programming in
Python

• Object Oriented Programming is a way of


computer programming using the idea of
“objects” to represents data and methods. It
is also, an approach used for creating neat
and reusable code instead of a redundant
one.
Features of OOP

Ability to simulate real-world event much more


effectively.
 Code is reusable thus less code may have to be written
Data becomes active.
Better able to create GUI (graphical user interface)
applications.
Programmers are able to produce faster, more
accurate and better- written applications.
Difference between Object-Oriented and Procedural
Oriented Programming
Procedural-Oriented
Object-Oriented Programming (OOP)
Programming (OOP)

It is a bottom-up approach It is a top-down approach


Program is divided into objects Program is divided into functions
Makes use of Access modifiers
‘public’, private’, protected’ Doesn’t use Access modifiers

It is more secure It is less secure

Object can move freely in Data can move freely from


the member function to function
function. within programs
It supports inheritance It does not support inheritance
Ex: Java, C++, C#, Python, Ex: FORTRAN, PASCAL, COBOL,
Creating a class in python
 Class:

A class is a collection of objects or it is a blueprint of the objects defining the common

attributes and behaviour.

Syntax:

Class is defined under a “Class” Keyword and followed by a class

name and a colon.

Class computer:

Here computer is name of the class.

The statements inside a class definition will usually be function definitions. Because of these

functions are indented under a class, they are called methods. Methods are a special kind of

function that is defined within a class.


Creating a object in python
Object:

Object refers to a particular instance of a class where the object


contains variables and methods defined in the class.

Class objects support two kinds of operations: attribute references


and instantiation.

The term attribute refers to any name (variables or methods)


following a dot.

 The act of creating an object from a class is called instantiation.

 The names in a class are referenced by objects and are called


attribute references.
Creating a object in python
Object:

There are two kinds of attribute references, data attributes and

method attributes.

Variables defined within the methods are called instance variables


and are used to store data values. New instance variables are
associated with each of the objects that are created for a class. These
instance variables are also called data attributes.

Method attributes are methods inside a class and are referenced by


objects of a class.
Object:
Creating a object in python
 The syntax to access data attribute is,

object_name.data_attribute_name

The syntax to assign value to data attribute is,

object_name.data_attribute_name = value
where value can be of integer, float, string types, or another object itself. The
syntax to call method attribute is,

object_name.method_attribute_name()

The syntax for Class instantiation is,


object_name = ClassName(argument_1, argument_2, ….., argument_n)When you
create an object for a class, it is called instance of a class.
The Constructor Method:

The Constructor Method:


 init is the default constructor in python.
 init serves as a constructor for the class. Usually does some
initialization work.
 An init method can take any number of arguments However, the first
argument self in the definition of init is special.
 The constructor is a method that is called when an object is created of a
class.

Syntax:
def init (self,parameter1,parameter2……parameter):
statements(s)
The Constructor Method:

 It starts with the def keyword, like all other functions in Python.

 It is followed by the word init, which is prefixed and suffixed with


double underscores with a pair of brackets, i.e., init ().
It takes the first argument called self, the parameters for init ()
method are initialized with the arguments that you had passed
during instantiation of the class object.
The number of arguments during the instantiation of the class
object should be equivalent to the number of parameters in init ()
method.
Creating class and object in python
Ex:

class computer: # computer is the class name


def init (self,cpu,RAM): # init is default constructor with arguments.
[Link]=cpu # assign value to data attribute of object
[Link]=RAM # assign value to data attribute of object
def config(self): # Defining method of a object
print("config is:",[Link]," ",[Link])
com1=computer("i5",16) # creating a object from class instantiation.
com2=computer("intel i3",8) # creating a object from class instantiation
[Link]() # calling method attribute
[Link]() # calling method attribute
Classes with multiple objects:
• Multiple objects for a class can be created while attaching a unique copy of data
attributes and methods of the class to each of these objects.
• Ex:
class student: Output:
def init (self,n,r,m): name: jagan
[Link]=n roll no: 1
[Link]=r marks : 89
[Link]=m
def display(self):
print("name:", [Link]) name: pradeep
print("roll no: ",[Link]) roll no: 2
print("marks :",[Link]) marks : 89
print("\n")

student_1=student("jagan",1,89) name: preethi


student_2=student("pradeep",2,89) roll no: 3
student_3=student("preethi",3,89) marks : 89

student_1.display()
student_2.display()
student_3.display()
Using Object As Argument:
• An object can be passed to a calling function as an argument.
• Ex:

class track: # track is the classname


def init (self,song,artist): # it as two data attributes song,artist
[Link]=song
[Link]=artist
Output:
song is Vande Mataram
# function not method as one argument
Artist is Rabindranath Tagore
def print_track_info(vocallist):
print("song is",[Link])
print(“Artist is",[Link])

# creating a object under class call it as instantiation.


singer=track("Vande Mataram","Rabindranath Tagore")

print_track_info(singer) # function calling and passing object as a argument


Objects As Return Values:
 The Return keyword followed by an optional return value.

 The return value of a python function can be any python object.

 Every thing in python is aobject.

o Numeric values(int,float,complex,etc)
o collections/ Sequences(list,tuple,dictionary,etc)

o Others( user-defined objects,classes,functions, modules etc)

 If you don’t provide a return value, None will be used as the


return value.
 If you don’t have a return statement, None will be used.
• In python ,”everything is a object” when the objected is created some space is
allocated in heap memory.
• The id function is used to find the identity of the location of the object in
memory.
• The syntax for Id function is,
• Id(object)
• This function returns the identity of an object.
• Two objects may have the same id() value. You check whether an object is an
instance of a given class by using instance() function.

• The syntax for is instance() function is;


• Isinstance(object,classinfo)
• Returns truce if object is an subclass of another object.
Example to check Isinstance()

# Define a class
class Animal:
def __init__(self, name):
[Link] = name

# Create instances of the class


dog = Animal("Dog")
cat = Animal("Cat")
fish = Animal("Fish")

# Check if objects are instances of the Animal class


print("Is 'dog' an instance of Animal?", isinstance(dog, Animal))
print("Is 'cat' an instance of Animal?", isinstance(cat, Animal))
print("Is 'fish' an instance of Animal?", isinstance(fish, Animal))

Output: Is 'dog' an instance of Animal? True


Is 'cat' an instance of Animal? True
Is 'fish' an instance of Animal? True
Objects As Return Values:
Ex: object as a return:
class Sum:
def __init__(self, num1, num2):
self.num1 = num1
Output:
self.num2 = num2
Sum:9
[Link] = None
ID:1787802679712
def add_sum(self): Is instance of Sum class? True
[Link] = self.num1 + self.num2
return self

def main():
number = Sum(4, 5)
returned_object = number.add_sum()
print("Sum:", returned_object.result)
print("ID:", id(returned_object))
print("Is instance of Sum class?", isinstance(returned_object, Sum))

if __name__ == "__main__":
main()
Ex: Return Values from methods :
class student:
def init (self,m1,m2,m3):
self.m1=m1 #The constructor initializes instance variables (self.m1, self.m2, self.m3)
self.m2=m2
self.m3=m3

def avg(self):
return((self.m1+self.m2+self.m3)/3)

std1=student(34,56,78)
print([Link]())
std2=student(89,65,45) Output:
print([Link]()) 116.0
169.0
Class Attributes and Data attributes
Class Attributes:
Are Class variables that is shared by all objects of a class.
Data Attributes
Are instance variables unique to each object of a class.
class Dog:
kind ='Canine'

def init (self,name):


self.dog_name=name

d=Dog('Fido')
e=Dog("Buddy")
print(f"{[Link]}") Output:
Canine
print(f"{[Link]}") Canine
print(f"{d.dog_name}") Fido
print(f"{e.dog_name}") Buddy
Encapsulation
• Encapsulation -> Information hiding
• It is the process of combining variables that store data and methods that
work on those variables into a single unit called class.
• Abstraction -> Implementation hiding
• Abstraction is a process where you show only “relevant” variables that are
used to access data and “hide” implementation details of an object from the
user.
Ex:
1. class Arithmetic_op:

2. def init (self,a,b): The internal representation of an object of


3. self.a = a Real_object class 1-6 is hidden outside the
4. self.b = b class -> Encapsulation.

5. def add(self): The implementation of add() function is


6. return self.a + self.b hidden from the object. -> Abstraction

7. Real_object = Arithmetic_op(3,4)
8. print(Real_object.add()) Output:
7
Inheritance:
• Inheritance is a powerful feature in object oriented programming
• It generally means “inheriting or transfer of characteristics from
parent to child class without any modification”.
• The new class is called the derived/child class and the one from
which it is derived is called a parent/base class.

Syntax of derived class:


Class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
Single Inheritance:
• In which there is one base class and one derived class
• Single level inheritance enables a derived class to inherit
characteristics from a single parent class.

Multilevel Inheritance:
• Multi-level inheritance enables a derived class to inherit
properties from another derived class, this process is known
as multilevel inheritance.
Hierarchical Inheritance:
• In which there is single base class and multiple derived class
•Hierarchical level inheritance enables more than one derived
class to inherit properties from a parent class.
Multiple Inheritance:
• Multiple level inheritance enables one derived class to inherit
properties from more than one base class.
Syntax:
class DerivedClassName(Base_1, Base_2, Base_ 3):
<statement-1>
.
<statement-N>
Derived class DerivedClassName is inherited from
multiple base classes, Base_1, Base_2, Base_3.
Accessing the inherited variables and methods:

class person:

def init (self,fname,lname):


[Link]=fname Output:
[Link]=lname person details:
renuka T
def printname(self): student details:
print([Link],[Link]) Joshitha k

x=person("renuka",“T")
print(" person details")
[Link]()

class student(person):

def display(self):
print(" student details")

x=student(“Joshitha",”K")
[Link]()
[Link]()
Accessing the inherited variables and methods:

• Student is the derived class and person is the base class


• Derived class inherits variables and methods of base class
• init () method is also derived from base class. Derived class has access of
init () method of the base class.
• The base class has 2 data attributes firstname and lastname It has a method
printname.
• Derived class has access to the data attributes and methods of the base class.
Using Super function and overriding Base class Methods:
• In Single Inheritance, built-in super() function is used to refer to base class
without explicitly naming it.
• If derived class has init () method and needs to access the base class
init () method explicitly, then this is done using super().
• If the derived class needs no attributes from base class, then we do not need
to use super() method to invoke base class init () method
• The syntax for using super() in derived class init method definition
looks like this:
Super(). init (base_class_parameters)
Usage of Super() method:
class DerivedClassName(BaseClassName):
def init (self, derived_class_parameter(s), base_class_parameter(s))
super(). init (base_class_parameter(s))
self.derived_class_instance_variable = derived_class_parameter

• The derived class init () method contains its own parameters along with the
parameters specified in the init () method of base class.
• No need to specify self while invoking base class init () method using super().
Usage of Super() method:
• Ex: •The init () method for child class take two
parameters name and txt1.
class Parent: •With in the init () method of child derived
def init (self, txt1): class, the init () method of the person base
self. message = txt1
class is invoked using super() function.
def printmessage(self): •when you use super() function to invoke base
print([Link]) class init () method, you need to pass the
txt1 parameter as an argument to init ()
class Child(Parent): function to match the method signature.
def init (self,name,txt1): •On invoking the base class init () method,
super(). init (txt1) the txt1 value gets assigned to message data
[Link]=name attribute in the person base class.
def display(self):
print(f"{[Link]},{[Link]}")

x = Child("renuka","how are you")


Output:
[Link]()
renuka,how are you
[Link]()
how are you
Method Overriding in Python
Method overriding is an ability of any object-oriented programming language
that allows a subclass or child class to provide a specific implementation of a
method that is already provided by one of its super-classes or parent classes.
When a method in a subclass has the same name, same parameters or signature
and same return type(or sub-type) as a method in its super-class, then the
method in the subclass is said to override the method in the super-class.
Overriding of the base class methods:
Ex:
class Parent: Output:
def init (self, txt1): renuka,how are you
self.txt1 = txt1 how are you

def printmessage(self):
print(self.txt1) •When the same method exists in both
the base class and the derived class, the
class Child(Parent): method in the derived class will be
def init (self,name,txt1): executed .
super(). init (txt1) •Derived class method overrides the
[Link]=name base class method.
def printmessage(self): •You can also directly invoke the base
print(f"{[Link]},{self.txt1}") class printmessage method from within
def invoke_base_class_method(self): the derived class by using super()
super().printmessage() function.
•You need to put super().printmessage()
x = Child("renuka","how are you") under another method within the
[Link]() derived class.
x.invoke_base_class_method()
Multiple Inheritances
Python also supports a form of multiple inheritances. A derived class definition
with multiple base classes looks like this:
Syntax:
class DerivedClassName(Base_1, Base_2, Base_ 3):
<statement-1>
.
.
.
<statement-N>
Derived class DerivedClassName is inherited from multiple base classes,
Base_1, Base_2, Base_3.

MRO:
Method Resolution Order, or “MRO” in short, denotes the way Python
programming language resolves a method found in multiple base classes.
Method Resolution Ordere - MRO
• Method Resolution Order(MRO) it denotes the way a programming
language resolves a method or attribute. Python supports classes inheriting
from other classes.
• The class being inherited is called the Parent or Superclass, while the class
that inherits is called the Child or Subclass.
• In python, method resolution order defines the order in which the base
classes are searched when executing a method. First, the method or
attribute is searched within a class and then it follows the order we specified
while inheriting.
• This order is also called Linearization of a class and set of rules are called
MRO(Method Resolution Order). While inheriting from another class, the
interpreter needs a way to resolve the methods that are being called via an
instance.
Multiple Inheritances
Using Super() function in Multiple Inheritances:
Ex:

class A: Output:
def init (self): Init in C
print("Init In A") Init In A
super(). init () Init In B
Method resolution Order Is :
class B: [<class ' main .C'>, <class ' main .A'>, <class
def init (self): ' main .B'>, <class 'object'>]
print("Init In B")
super(). init ()

class C(A,B): The Order to reslove init method is,


def init (self):
print("Init in C") Class Thrid--> Class First-->Class Second-->Class object
super(). init ()

obj=C()
print(f" Method resolution Order Is :{[Link]()}")
Multiple inheritance with method overrriding:
class A:
def init (self,fname,mname): class C(A,B):
print("Init In A") def init (self,fname,mname,Lname):
super(). init (mname) print("Init in C")
super(). init (fname,mname)
[Link]=fname
[Link]=Lname
def feature1(self): def feature3(self):
print("feature1 is working") print("feature3 is working")
print(f"{[Link]},{[Link]},{[Link]}")
class B:
def init (self,mname): x=C("nitish","pradsd","k")
print("Init In B") x.feature1()
super(). init () x.feature2()
[Link]=mname x.feature3()
print(f" Method resolution Order Is :{[Link]()}")
def feature2(self):
print("feature2 is working")
Multiple inheritance with method overrriding:

Output:
Init in C
Init In A
Init In B
feature1 is working
feature2 is working
feature3 is working
nitish,pradsd,k
Method resolution Order Is :[<class ' main .C'>, <class ' main .A'>,
<class ' main .B'>, <class 'object'>]
Polymorphism:
• Poly means many and morphism means forms.
• Polymorphism is one of the tenets of Object Oriented Programming (OOP).
• Polymorphism means that you can have multiple classes where each class
implements the same variables or methods in different ways.
Let's take an example:

Example 1: Polymorphism in addition operator


• We know that the + operator is used extensively in Python programs. But, it
does not have a single usage.
• For integer data types, + operator is used to perform arithmetic addition
operation.
• Similarly, for string data types, + operator is used to perform concatenation.

There are two kinds of Polymorphism


Overloading :
Two or more methods with different signatures
Overriding:
• Replacing an inherited method with another having the same
signature
• Program to Demonstrate Polymorphism in Python
class Vehicle:
def init (self, model):
[Link] = model
def vehicle_model(self):

print(f"Vehicle Model name is def main():
{[Link]}") ducati = Bike("Ducati-Scrambler")
beetle = Car("Volkswagon- Beetle")
class Bike(Vehicle): boeing = Aeroplane()
def vehicle_model(self): for each_obj in [ducati, beetle,
print(f"Vehicle Model name is
boeing]:
{[Link]}")
try:
vehicle_info(each_obj)
class Car(Vehicle):
def vehicle_model(self): except AttributeError:
print(f"Vehicle Model name is print("Expected method not
{[Link]}") present in the object")
if name == " main ":
class Aeroplane: main()
pass
def vehicle_info(vehicle_obj):
vehicle_obj.vehicle_model()
OUTPUT
Vehicle Model name is Ducati-Scrambler
Vehicle Model name is Volkswagon-Beetle
Expected method not present in the object

Operator overloading and Magic methods:


• This is a specific case of Polymorphism.
• “Poly” means many and “morphism” means forms.
You can have multiple classes where each class
implements the same variables or
• Operator overloading is a specific case of
polymorphism, where an operator can have different
meaning when used with operands of different types.
Program for demo + operator overloading

class Complex:
def init (self, real, imaginary):
[Link] = real
[Link] = imaginary
def add (self, other):
return Complex([Link] + [Link], [Link] + [Link])
def str (self):
return (f"{[Link]} + i{[Link]}“)

complex_number_1 = Complex(4, 5)
complex_number_2 = Complex(2, 3)
complex_number_sum = complex_number_1 + complex_number_2
print(f"Addition of two complex numbers {complex_number_1} and {complex_
number_2} is {complex_number_sum}")

Output: Addition of two complex numbers 4 + i5 and 2 + i3 is 6 + i8


Explanation of the program
• complex_number_sum = complex_number_1 +
complex_number_2 will execute as
• Complex_number_1. add (complex_number_2)

• add__() method is called magic method.



• Whenever we have to print the complex_number
formatted, then str () magic method is called which is
implemented as shown in the program

• The str () method returns the values of real and
imaginary data concatenated together and imaginary
part is prefixed with i.
Program for polymorphism:
import math pi = 3.141 class square:
def init (self, length):
self.l = length
def perimeter(self):
return 4 * (self.l) def area(self):
return self.l * self.l

class Circle:
self.r = radius
def perimeter(self): return 2 * pi * self.r
def area(self):
# Initialize the classes
return pi * self.r ** 2
sqr = square(10)
c1 = Circle(4)
print("Perimeter computed for square: ", [Link]()) print("Area computed for
square: ", [Link]()) print("Perimeter computed for Circle: ", [Link]())
print("Area computed for Circle: ", [Link]())
import math
pi = 3.141
class Square:
def __init__(self, length):
self.l = length
def perimeter(self):
return 4 * self.l
def area(self):
return self.l * self.l
class Circle:
self.r = radius
def perimeter(self):
return 2 * pi * self.r
def area(self):
# Initialize the classes
return pi * self.r ** 2
# Create instances of the classes
sqr = Square(10)
c1 = Circle(4)
# Print computed values
print("Perimeter computed for square:", [Link]())
print("Area computed for square:", [Link]())
print("Perimeter computed for Circle:", [Link]())
print("Area computed for Circle:", [Link]())
•Square and Circle are the derived classes
•The derived classes have the methods perimeter() and area()
which are common to both
•But the implementation of these two methods is different in
each of the 2 classes.

• Output:
• Perimeter computed for square: 40
• Area computed for square: 100
• Perimeter computed for Circle: 25.128
• Area computed for Circle: 50.256
DATA VISUALIZATION

Generating Data
DATA VISUALIZATION
 Python is used for data-intensive work in
genetics, climate research, sports, political and
economic analysis.
 Mathematical Plotting Library is a popular tool
used to make simple plots such as line graphs
and scatter plots.
 Plotly package creates visualizations that work
well on digital devices.
 Matplotlib is installed using the command

 $ python –m pip install –user matplotlib


MATPLOTLIB
 What is Matplotlib?
 Matplotlib is a comprehensive library for creating
static, animated, and interactive visualizations in
Python.
 Matplotlib is a low level graph plotting library in
python that serves as a visualization utility.

 Matplotlib was created by John D. Hunter.

 Matplotlib is open source and we can use it


freely.
 Matplotlib is mostly written in python, a few
segments are written in C, Objective-C and
Javascript for Platform compatibility.
PLOTTING A SIMPLE LINE GRAPH

 import [Link] as plt

 squares =[1,4,9,16,25]
 fig, ax = [Link]()

 [Link](squares)

 [Link]()
PLOTTING A SIMPLE LINE GRAPH
 Pyplot is a collection of functions that make
matplotlib work like MATLAB.
 Plt is used so that we don’t type [Link]
repeatedly
 The [Link] method provides a
way to plot multiple plots on a single figure.
 Fig – indicates the entire figure or collection of plots
 ax -> represents a single plot
 Plot() function is used to plot the data in a meaningful
way
 The function [Link]() opens MATplotlib’s viewer
and displays the plot.
CORRECTING THE LINE PLOT (W.R.T X- AXIS)
 import [Link] as plt

 squares = [1,4,9,16,25]
 input_values = [1,2,3,4,5]
 fig,ax = [Link]()
 [Link](input_values, squares, linewidth = 3)

 [Link]()
CHANGING THE LABEL TYPE AND LINE
THICKNESS
import [Link] as plt

squares =[1,4,9,16,25]
input=[1,2,3,4,5]

fig,ax = [Link]()
[Link](input, squares, linewidth=3)
# Set chart title and label axes

ax.set_title("Square Numbers", fontsize=24)


ax.set_xlabel("Value", fontsize = 14)
ax.set_ylabel("Square of Value", fontsize = 14)
#set size of tick labels

ax.tick_params(axis = 'both', labelsize = 14)

[Link]()
EXPLANATION OF PROGRAM

 The linewidth parameter controls the thickness


of the line that generates the plot.
 What is the meaning of Tick_params?

 tick_params() is used to change the


appearance of ticks, tick labels, and
gridlines.
 The method tick_params() styles the tick marks.
Both x-axis and y-axis are set to labelsize of 14.
SCATTER PLOT
 A scatter plot is a diagram where each value in the
data set is represented by a dot.

 The Matplotlib module has a method for drawing


scatter plots, it needs two arrays of the same length,
one for the values of the x-axis, and one for the values
of the y-axis

 # Basic scatter plotimport [Link] as plt


 import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig, ax = [Link]()
[Link](x,y)
[Link]()
SCATTER PLOT WITH BUILT-IN SEABORN STYLE AND PLOTTING A
SERIES OF POINTS WITH SCATTER

 import [Link] as plt

 x = [1, 2, 3, 4, 5]
 y= [1, 4, 9, 16, 25]

 [Link]('seaborn-v0_8')
 fig, ax = [Link]()
 [Link](x,y,s=100)

 [Link]()
CALCULATING THE DATA AUTOMATICALLY
 import [Link] as plt

 x_values = range(1,1001)
 y_values = [x**2 for x in x_values]

 [Link]('seaborn-v0_8')
 fig, ax = [Link]()

 #[Link](x_values,y_values,s=10)

 [Link](x_values,y_values,c=y_values, cmap=[Link], s=10)

 [Link] ([0,1100,0,1100000])
Removes the
extra white
 [Link]() spaces around
 [Link]('squares_plot.png', bbox_inches='tight') the plot
RANDOM WALKS
 Using RANDOM module, python will generate a series of
random decisions each of which is left entirely to change.
 You can image a random walk as the path a confused ant
would take if it took every step in a random direction.
 Random walks have practical applications in nature,
physics, biology, chemistry, and economics.

Creating the RandomWalk() Class:


 To create a random walk, we’ll create a RandomWalk
class, which will make random decisions about which
direction the walk should take.
 The class needs three attributes: one variable to store the
number of points in the walk and two lists to store the x-
and y-coordinate values of each point in the walk.
 We’ll only need two methods for the RandomWalk class:
the __init__() method and fill_walk(), which will calculate
the points in the walk.
 RandomWalk CLASS and fill_walk method:
from random import choice
class RandomWalk:
Random_walk.py
def __init__(self,num_points=7):
self.num_points=num_points
self.x_values=[0] # All walks start at (0,0)
self.y_values=[0]

def fill_walk(self):
: # keep taking Steps until the walk reaches desired length
while len(self.x_values)<self.num_points
#decide which direction to go and how far to go in that direction.
x_direction= choice([1,-1])
x_distance=choice([0,1])
x_step=x_direction * x_distance rw_visual.py
import [Link] as plt
y_direction= choice([1,-1])
y_distance=choice([0,1]) from random_walk import
y_step=y_direction * y_distance Randomwalk

if x_step == 0 and y_step == 0: rw =Randomwalk()


continue rw.fill_walk()
x=self.x_values[-1]+x_step [Link]('classic')
y=self.y_values[-1]+y_step fig, ax = [Link]()
[Link](rw.x_values, rw.y_values,
self.x_values.append(x) s = 15)
self.y_values.append(y) [Link]()
 we start each walk at the point (0, 0).
 The main part of the fill_walk() method tells Python how to
simulate four random decisions: will the walk go right or
left? How far will it go in that direction? Will it go up or
down? How far will it go in that direction? .
 We use choice([1, -1]) to choose a value for x_direction,
which returns either 1 for right movement or −1 for left .
Next, choice([0, 1, 2, 3, 4]) tells Python how far to move in
that direction (x_distance) by randomly selecting an integer
between 0 and 4.
 A positive result for x_step means move right, a negative
result means move left, and 0 means move vertically.
 A positive result for y_step means move up, negative
means move down, and 0 means move horizontally.
 If the value of both x_step and y_step are 0, the walk
doesn’t go anywhere, so we continue the loop to ignore this
move .
GRAPH:
Multiple random walks:
 One way to use the preceding code to make multiple walks without
having to run the program several times is to wrap it in a while loop,
like this:

import [Link] as plt


from random_walk import Randomwalk
while True:
rw =Randomwalk()
rw.fill_walk()
[Link]('classic')
fig, ax = [Link]()
[Link](rw.x_values, rw.y_values, s = 15)
[Link]()

keep_running = input("Make another walk? (y/n):")


if keep_running == 'n':
break
ADDING COLOR TO THE PLOT
import [Link] as plt
from random_walk import RandomWalk
rw =RandomWalk()
rw.fill_walk()
[Link]('classic')
fig, ax = [Link]()
[Link](rw.x_values, rw.y_values, c=range(rw.num_points)
cmap =[Link], edgecolors = 'none', s = 15)
[Link]()
 we use range() to generate a list of numbers equal to the number of
points in the walk.
 the c argument, use the Reds colormap, and then pass
edgecolors='none' to get rid of the black outline around each point.
 The result is a plot of the walk that varies from light to dark blue
along a gradient
MODIFICATIONS IN THE RANDOMWALK PROGRAM

# Emphasize first and last points


 [Link](0,0,c='green',s=1500)

 [Link](rw.x_values[-1], rw.y_values[-1], c="red" ,s =


1500)

# To remove the axis lines


 ax.get_xaxis().set_visible(False)
 ax.get_yaxis().set_visible(False)

# Altering the size to fill the screen

 fig, ax = [Link](figsize=(20,15), dpi=128)


 Screen resolution is 100 pixels per inch.
MODIFICATIONS IN THE RANDOMWALK PROGRAM

# Increase the random set of data to 50,000


 rw =Randomwalk(50_000)

# Plotting the Starting and Ending Points:


 [Link](rw.x_values,rw.y_values,c='lightpink',

edgecolor='none',s=10)

[Link](0,0,c='green',edgecolor='none',s=1500)
 [Link](rw.x_values[-1], rw.y_values[-1],
c="red",edgecolor='none',s = 1500)
ROLLING DICE WITH PLOTLY:
 Python package plotly is used to produce
interactive visualizations.

 When user hovers over certain elements on the


screen, information about that element is
highlighted.

 Study of rolling dice is used in real world


applications in casinos and other gambling
scenarios as well as in games Monopoly and
many role-playing games.
ROLLING DICE WITH PLOTLY:
Installing Plotly
 Install Plotly using pip, just as you did for Matplotlib:
 $ python -m pip install --user plotly.

 The init () method takes one optional argument.


 With the Die class, when an instance of our die is created,
the number of sides will always be six if no argument is
included.

 If an argument is included, that value will set the number


of sides on the die.

 The roll() method uses the randint() function to return a


random number between 1 and the number of sides.
ROLLING DICE WITH PLOTLY:
Creating the die class:

from random import randint


class die:
""" A class representing a single die D6"""
def __init__(self,num_sides=6):
self.num_sides=num_sides
def roll(self):
return randint(1,self.num_sides) OUTPUT:

Rolling the die:


[4, 3, 1, 4, 4, 1, 5, 6, 6, 4, ]
from die import die
die=die()
results=[]
for roll_num in range(10):
result=[Link]()
[Link](result)
print(results)
ROLLING THE DICE:
import random
print("Rolling the dices...")
print("The values are....")
while True:
value =[Link](1, 6)
print(f"The number is: {value}")
roll_again = input("Roll the dices again? (y/n)")
if(roll_again =='n'): Output:
break Rolling the dices...
The values are....
Roll the dices again? (y/n)y
The number is: 5
Roll the dices again? (y/n)y
The number is: 1
Roll the dices again? (y/n)y
The number is: 5
Roll the dices again? (y/n)y
The number is: 2
Roll the dices again? (y/n)n
ROLLING DICE WITH PLOTLY:
Analyzing the Results:
 We’ll analyze the results of rolling one D6 by counting how many
times we roll each number.
The number 1 is repeated: 13
for roll_num in range(100): The number 2 is repeated: 23
dice_num= [Link]() The number 3 is repeated: 17
[Link](dice_num) The number 4 is repeated: 16
The number 5 is repeated: 17
# Analyze the results The number 6 is repeated: 14
frequencies =[ ]
for value in range (1 ,die.num_sides + 1):
repetition = [Link](value)
[Link](repetition)

for value in range (1 ,die.num_sides +1):


print(f"The number {value} is repeated: {frequencies[value-
1]}")
ANALYZING THE RESULTS:
 we create an instance of Die with the default six sides. At we roll
the die 100 times and store the results of each roll in the list
results.
 To analyze the rolls, we create the empty list frequencies to store
the number of times each value is rolled.
 count how many times each number appears in results and then
append this value to the frequencies list.
Making a Histogram:
A histogram is a bar chart showing how often certain results
occur. Here’s the code to create the histogram.
 To make a histogram, we need a bar for each of the possible
results.
 We store these in a list called x_values, which starts at 1 and
ends at the number of sides on the die
 The Layout() class returns an object that
specifies the layout and configuration of the
graph as a whole .
 Here we set the title of the graph and pass the x
and yaxis configuration dictionar ies as well.
 To generate the plot, we call the [Link]()
function .
 This function needs a dictionary containing the
data and layout objects, and it also accepts a
name for the file where the graph will be saved.
We store the out put in a file called [Link].
MAKING A HISTOGRAM:

 from plotly.graph_objs import Bar, Layout


 from plotly import offline

 # bar graph using plotly

 x_values = list(range(1,die.num_sides + 1))


 data = [Bar(x=x_values, y=frequencies)]

 x_axis_title={'title':'Result'}
 y_axis_title={'title':'Frequency of Result'}
 my_layout = Layout(title='Histogram of Dice rolling
100 times', xaxis = x_axis_title, yaxis = y_axis_title)
 [Link]({'data':data, 'layout' : my_layout})
ROLLING TWO DICE

from random import randint


from plotly.graph_objs import Bar, Layout
from plotly import offline

class Die:
def __init__(self,num_sides=6):
self.num_sides = num_sides

def roll(self):
return randint(1,self.num_sides)

def main():
die1 = Die()
die2 = Die()
results =[]
for roll_num in range(1000):
result = [Link]() + [Link]()
[Link](result)
ROLLING TWO DICE
frequencies =[]
max_result = die1.num_sides + die2.num_sides
for value in range(2,max_result + 1):
frequency = [Link](value)
[Link](frequency)

# bar graph using plotly


x_values = list(range(2,max_result + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_title={'title':'Face of Dice','dtick':1}
y_axis_title={'title':'Frequency of Dice face occurance '}
my_layout = Layout(title='Histogram of Dice rolling 1000 times', xaxis =
x_axis_title, yaxis = y_axis_title)
[Link]({'data':data, 'layout' : my_layout})

if __name__=="__main__":
main()
ROLLING DICE OF DIFFERENT SIZES
 die2 = Die(10)
SUMMARY
 Visualization of Data – Simple Line Plots using
matplotlib.
 Scatter Plots to explore random walks.

 Histogram using Plotly

 Histogram to explore the results of rolling dice of


different sizes.
DOWNLOADING DATA IN CSV FORMAT
Visualize data
 we will download a data set from an online resources and create a
working visualization of that data.
 We will access and visualize the data store in two common formats,
 CSV format
 JSON format

 We will use Python’s CSV module to process weather data.


 We will analyze the high and low temperatures over the period in two
different locations.
 Then we will use matplotlib to generate a chart based on downloaded
data.

 Download a CSV file from [Link]


Visualize data
 THE CSV FILE FORMAT:

 CSV stands for Comma Separated Values. As the name suggests, it


is a kind of file in which values are separated by commas.
 This is the weather data. We will start with a small dataset. It
is CSV formatted data Stika, Alaska.
 You can download datasets from
sitka_weather_07-2018_simple.csv.
This is how your CSV file of data will look like:
Parsing the csv File Header
 Import csv

 with open(r'C:\Users\KLEBCA-
2\Desktop\data\sitka_weather_07-2018_simple.csv','r') as
f:
 reader = [Link](f)
 header_row = next(reader)
Parsing the csv File Header

 After importing the CSV module then open the file


using open function and store the result file object in f.
 Next, we have called the reader function of the CSV module
and passed the file object f to it as an argument.
 This function creates a reader object associated with that file.
 The CSV module contains a next() function which returns the
next line in the file.
 In the preceding listing, we call next() only once so we get the
first line of the file, which contains the file headers.
 So, the header is stored in the variable header_row. The next
line, just prints the header row.
Printing Headers and their Positions

 import csv

 with open(r'C:\Users\KLEBCA-
2\Desktop\data\sitka_weather_07-2018_simple.csv','r') as f:
 reader = [Link](f)
 header_row = next(reader)

 for index, column_header in enumerate(header_row):


 print(index, column_header) Enumerate() function returns
both the index of each item and
the value of each item as you
loop through a list.
Extracting and Reading Data
We make an empty list named highs. Then, we iterate through each
row in the reader and keep appending the high temperature which
is available on index 4 to the list.
 highs=[]
 for row in reader:
 high = int(row[4]) • reader object returns each line following its
current position
 [Link](high) • Loop through all the lines in the file
• Reader object will read from 2nd line after reading
the header
 print(highs) • Read the data from index 5 (TMAX) and assign it
to high
• Append the highs list
Plotting Data in a Temperature Chart:
To visualize the temperature data, we will first create a plot of daily high temperatures using matplotlib.

import [Link] as plt


import csv
with open(r'C:\Users\KLEBCA-2\Desktop\data\sitka_weather_07-2018_simple.csv','r') as f:
reader = [Link](f)
header_row = next(reader)
# Get high temperatures from this file
highs=[]
for row in reader:
high = int(row[5])
[Link](high)
# Plot the high temperatures
fig,ax = [Link]()
[Link](highs, c='red')
# Format plot.
[Link]("Daily high temperatures", fontsize = 24)
[Link]("Temperature", fontsize = 16)
plt.tick_params(axis='both', which='major', labelsize = 16)
[Link]()
Date and Time Format Specifiers
from datetime import datetime # display hour
print([Link])
# DD/MM/YY H:M:[Link]
time_data = "25/05/1987 02:35:5.523" # display minute
print([Link])
# format the string in the given format : # display second
# day/month/year hours/minutes/seconds-micro print([Link])
# seconds # display milli second
format_data = "%d/%m/%Y %H:%M:%S.%f" print([Link])

# Using strptime with datetime we will format # display date


date = [Link](time_data, format_data) print([Link])
print([Link])
print([Link])
The datetime Module
import [Link] as plt
import csv
from datetime import datetime
with open(r'C:\Users\KLEBCA-2\Desktop\data\sitka_weather_07-2018_simple.csv','r') as f:
reader = [Link](f)
header_row = next(reader)
dates, highs=[],[]
for row in reader:
current_date = [Link](row[2],'%d-%m-%Y')
[Link](current_date)
high = int(row[5])
[Link](high)
•Strptime() function takes the date we want to
work with as its first argument, the second
fig,ax = [Link]() argument tells how the date is formatted.
[Link](dates, highs, c='red') •We are passing dates and high temperatures to
the plot for plotting the graph.
•Fig.autofmt_xdate draws the date labels
[Link]("Daily high temperatures", fontsize = 24)
diagonally to prevent them from overlapping fig.
fig.autofmt_xdate()
[Link]("Temperature", fontsize=16)
[Link]()
Output with date time
Shading an area in the chart
 fig,ax = [Link]()
 [Link](dates, highs, c='red')
 [Link](dates, lows, c='blue')
 plt.fill_between(dates,highs,lows,facecolor='blue', alpha=0.1)
 The “facecolor” argument determines the color of the shaded
region in between the highs and lows.
Plotting the Two Data Series Shading an area in the chart
import [Link] as plt

with open(r'C:\Users\KLEBCA-2\Desktop\data\sitka_weather_2018_full.csv','r') as f:
reader = [Link](f)
header_row = next(reader)
# Get dates, and high and low temperatures from this file.
dates, highs, lows = [], [], []
for row in reader:
current_date = [Link](row[2], '%d-%m-%Y')
high = int(row[6])
low = int(row[7])
[Link](current_date)
[Link](high)
[Link](low)
Plotting the Two Data Series
# Plot the high and low temperatures.
[Link]('seaborn-v0_8')
fig, ax = [Link]()
[Link](dates, highs, c='red',alpha=0.5)
[Link](dates, lows, c='green',alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='green',alpha=0.1)

# Format plot.
[Link]("Daily high and low temperatures - 2018", fontsize=14)
[Link]('', fontsize=16)
fig.autofmt_xdate()
[Link]("Temperature (F)", fontsize=14)
[Link]()
Plotting the Highest and Least temperatures in a day
Error Handling in Datasets
 Missing data can result in exceptions that crash our programs unless we handle them
properly.
 Each time we examine a row, we try to extract the date and the high and low
temperature
 .If any data is missing, Python will raise a ValueError and we handle it by printing an
error message that includes the date of the missing data
 .After printing the error, the loop will continue processing the next row.

fh = open(r'C:\Users\Admin\Desktop\Death_valley.csv', 'r')
try:
high = int(row[4])
low =int(row[5])
except ValueError:
print(f"Missing data for {current_date}")
else:
[Link](high)
[Link](current_date)
[Link](low)
Download your own data
 [Link] In Dataset box
choose Daily Summaries.
Mapping Global Data Sets : JSON Format
Downloading Earthquake Data
 In this section we'll work with data stored in JSON format. First
we'll download a data set representing all the earthquakes that
have occurred in the world during the previous month.

 Then we’ll make a map showing the location of these earthquakes


and how significant each one was.
 Because the data is stored in the JSON format, we’ll work with it
using the json module.

 Using Plotly’s beginner-friendly mapping tool for location-based


data, we’ll create visualizations that clearly show the global
distribution of earthquakes.
 Download the file eq_1_day_m1.json from at
[Link]
 This file includes data for all earthquakes with a
magnitude M1 or greater that took place in the last 24 hours.
 When we open eq_1_day_m1.json, we’ll see that it’s very dense
and hard to read:

{"type":"FeatureCollection","metadata":{"generated":15503614610
00,...
{"type":"Feature","properties":{"mag":1.2,"place":"11km NNE of
Nor...
{"type":"Feature","properties":{"mag":4.3,"place":"69km NNW of
Ayn...
{"type":"Feature","properties":{"mag":3.6,"place":"126km SSE of
Co...
 This file is formatted more for machines than it is for humans.
But we can see that the file contains some dictionaries, as well as
information that we’re interested in, such as earthquake
magnitudes and
locations.
 The json module provides a variety of tools for exploring and
working with JSON data.
 There are
i) load
ii)dump
Examining Json Data:
 import json

# Explore the structure of the data.


filename = 'data/eq_data_1_day_m1.json'
with open(filename) as f:
all_eq_data = [Link](f)

readable_file = 'data/readable_eq_data.json'
with open(readable_file, 'w') as f:
[Link](all_eq_data, f, indent=4)
 We first import the json module to load the data properly from
the file, and then store the entire set of data in all_eq_data. The
[Link]() function converts the data into a dictionary.
 Next we create a file to write this same data into a more readable
format. The [Link]() function takes a JSON data object and a
file object, and writes the data to that file.
 The indent=4 argument tells dump() to format the data using
indentation that matches the data’s structure.
Making a list of all earthquakes:

 The first part of the file includes a section with the key
"metadata". This tells us when the data file was generated and
where we can find the data online.
 It also gives us a human-readable title and the number of
earthquakes included in this file.
 In this 24-hour period, 158 earthquakes were recorded.
 This geoJSON file has a structure that’s helpful for location-based
data.
Making a list of all earthquakes:
 he following program makes a list that contains all the
information about every earthquake that occurred:

import json

# Explore the structure of the data.


filename = 'data/eq_data_1_day_m1.json'
with open(filename) as f:
all_eq_data = [Link](f)

all_eq_dicts = all_eq_data[‘metadata']

all_eq=all_eq_dicts[‘count’]
Extracting Magnitudes:
 The key "properties" contains a lot of information about each
earthquake. We’re mainly interested in the magnitude of each quake,
which is associated with the key "mag".
 The program pulls the magnitudes from each earthquake.

 mags = []
for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
[Link](mag)

print(mags[:10])

 Now we’ll pull the location data for each earthquake, and then we can
make a map of the earthquakes.
 The location data is stored under the key "geometry". Inside the
geometry dictionary is a "coordinates" key, and the first two values in
this list are the longitude and latitude.
 The following program pulls the location data:

 mags, lons, lats = [], [], []


for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
lon = eq_dict['geometry']['coordinates'][0]
lat = eq_dict['geometry']['coordinates'][1]
[Link](mag)
[Link](lon)
[Link](lat)
print(mags[:10])
print(lons[:5])
print(lats[:5])
Building a World map:
 import json
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
data = [Scattergeo(lon = lons, lat = lats)]
my_layout = Layout(title = 'Global Earthquakes')
fig = {'data': data, 'layout': my_layout}
[Link](fig, filename='global_earthquakes.html')
 We import the Scattergeo chart type and the Layout class,
and then import the offline module to render the map.
 A Scattergeo chart type allows you to overlay a scatter plot of
geo- graphic data on a map
A Different Way of Specifying Chart Data :
 data = [Scattergeo(lon=lons, lat=lats)]
 This is one of the simplest ways to define the data for a chart in
Plotly.
data = [{
'type': 'scattergeo', 'lon': lons,
'lat': lats,
}]
 In this approach all the data is structured as key-value pairs in a
dictionary.
Customizing Marker Size:
 . We want viewers to immediately see where the most
significant earthquakes occur in the world.
 To do this, we’ll change the size of markers depending on the
magni tude of each earthquake:
'marker': {
'size': [5*mag for mag in mags],
Customizing Marker Colors :
'color': mags,
'colorscale': 'Viridis',
'reversescale':True,
'colorbar' : {'title' : 'Magnitude'},
 The 'colorscale' setting tells Plotly which range of colors to use:
'Viridis' is a colorscale that ranges from dark blue to bright
yellow and works well for this data set.
 We set 'reversescale' to True, because we want to use bright
yellow for the lowest values and dark blue for the most severe
earth- quakes.
Other Colorscales :
 Plotly stores the colorscales in the colors module.
 The colorscales are defined in the dictionary PLOTLY_SCALES,
and the names of the colorscales serve as the keys in the
dictionary.
 Greys ,YlGnBu, Greens, 'Viridis',
Adding Hover Text:
 To finish this map, we’ll add some informative text that
appears when you hover over the marker representing an
earthquake.
hover_texts = []
title = eq_dict['properties']['title']
hover_texts.append(title)
'text': hover_texts,
what is an API

An application programming interface (api) is a tool


that allows computers to exchange data.
what is an API:
 In this chapter, you’ll learn how to write a self-contained
program that generates a visualization based on data that
it retrieves.
 Your program will use a web application programming
interface (API) to automatically request specific informa-
tion from a website—rather than entire pages—and
then use that information to generate a visualization.
uses of APIs:
 Social –Twitter, Facebook, etc.
 Internet – [Link], domain registration.
 Mapping – Google Maps, Bing Maps, etc.
 Search – Google, Yahoo, etc.
 APIs make information transferred across the web digestible for
a computer.
key protocols
• HTTP – communicating with web server
• OAuth – accessing secure information
Using a Web API:

 A web API is a part of a website designed to interact with


programs.
 Those programs use very specific URLs to request certain
information.
 This kind of request is called an API call.
 The requested data will be returned in aneasily processed
format, such as JSON or CSV.
 Most apps that rely on external data sources, such as apps
that integrate with social media sites, rely on API calls.
REST API:
 An API (Application Programming Interface) is a set of
rules with which your application can access the service, as
well as what data this service can return in the response.
 The API acts as a layer between your application and
external service.
 We can access the functionality of the service without
knowing its implementation complexities.
 REST API (Representational state transfer) is an API that
uses HTTP requests for communication with web services.
REST API:
REST API:
 There are four main types of actions:

 GET: retrieve information (like search results). This is the most


common type of request. Using it, we can get the data we are
interested in from those that the API is ready to share.

 POST: adds new data to the server. Using this type of request, you
can, for example, add a new item to your inventory.

 PUT: changes existing information. For example, using this type of


request, it would be possible to change the color or value of an existing
product.

 DELETE: deletes existing information


Status Codes
Status codes are returned with a response after each call to the server.
They briefly describe the result of the call.
200 – [Link] request was successful.
204 – No [Link] server successfully processed the request and
did not return any content.
301 – Moved [Link] server responds that the requested
page (endpoint) has been moved to another address and redirects to
this address.
400 – Bad [Link] server cannot process the request because the
client-side errors (incorrect request format).
401 – Unauthorized. Occurs when authentication was failed, due to
incorrect credentials or even their absence.
403 – Forbidden. Access to the specified resource is denied.
404 – Not Found. The requested resource was not found on the server.
500 – Internal Server Error. Occurs when an unknown error has
occurred on the server.
Git and GitHub
 GitHub ([Link] takes its name from Git,
GitHub, a site that allows programmers to collaborate on
coding projects.
 We’ll use GitHub’s API to request information about Python
projects on the site, and then generate an interactive
visualization of the relative popularity of these projects using
Plotly.
Requesting data using an api call to github:
 url='[Link]
nguage:python&sort=stars‘
 First part, [Link] -> directs the request to the
part of GitHub that responds to API calls
 Second part search/repositories, tells the API to conduct a
search through all repositories on GitHub.
 ? -> indicates that we are about to pass argument.
 Q -> query
 Language: python -> we want information on repositories that
have python as the primary language.
Requesting data using an api call to github:
 &sort = stars, sorts the projects by the number of stars they
have been given.
 Finally this call returns the number of python projects currently
hosted on Githubs.
 As well as information about the most popular python
repositories.
Processing an API response:
 Write a program Automatically issue an API call and process the
results by identifying the most startted python projects on
Git Hub:
Installing Requests:
$ python –m pip install –user requests
Processing an API response
 import requests
 url='[Link]
e:python&sort=stars'
 headers = {'Accept': 'application/[Link].v3+json'}
 r = [Link](url, headers = headers)
 print(f" Status code: {r.status_code}")
 response_dict =[Link]()
 print(response_dict.keys()) Output:
Status code: 200
dict_keys(['total_count',
'incomplete_results', 'items'])
Explanation to the program:

1. We import the Requests module.


2. The URL of API call is stored in url variable.
3. We need to use the github version 3 of its API (so headers are
defined for the API call)
4. Requests is used to make the call to API
Response object has attribute status_code which indicates if the
response was successful or not
API returns the information in JSON format. So we use
JSON() method to convert it into Python dictionary.
The response is stored in response_dict.
Working with Repository dictionary
 print(f"Total repositories : {response_dict['total_count']}")
Print the total number of
repositories in the github
 repo_dicts = response_dict['items']
 print(f"Repositories returned : {len(repo_dicts)}")
List of dictionaries is stored
in repo_dicts
 repo_dict = repo_dicts[0]
 print(f"\n keys: {len(repo_dict)}")
Read out the information from
 for key in sorted(repo_dict.keys()): first item in repo_dict[].
Print the keys in the first item to
 print(key) see the kind of information
included
More information about a single repository:
 print("\n selected information about first repository:")
 print(f"Name: {repo_dict['name']}")
 print(f"Owner: {repo_dict['owner']['login']}")
 print(f"Stars: {repo_dict['stargazers_count']}")
 print(f"Repository: {repo_dict['html_url']}")
 print(f"Created : {repo_dict['created_at']}")
 print(f"Updated : {repo_dict['updated_at']}")
 print(f"Description : {repo_dict['description']}")
OUTPUT
 selected information about first repository:
 Name: scikit-learn
 Owner: scikit-learn
 Stars: 53040
 Repository: [Link]
 Created : 2010-08-17T09:43:38Z
 Updated : 2023-02-23T00:41:40Z
 Description : scikit-learn: machine learning in Python
Monitoring API rate limits:

 [Link]
 Response:
 {"resources":{"core":{"limit":60,"remaining":60,"reset":16771
22209,"used":0,"resource":"core"},"graphql":{"limit":0,"remai
ning":0,"reset":1677122209,"used":0,"resource":"graphql"},"in
tegration_manifest":{"limit":5000,"remaining":5000,"reset":16
77122209,"used":0,"resource":"integration_manifest"},"search"
:{"limit":10,"remaining":10,"reset":1677118669,"used":0,"reso
urce":"search"}},"rate":{"limit":60,"remaining":60,"reset":167
7122209,"used":0,"resource":"core"}}
 Rate Limited – How many requests you can make in a certain
amount of time.
Visualizing repositories using plotly
 We will import the Bar class and offline module from plotly.
 Repo_names and stars are 2 lists created. They will contain
the repo names and the stars that each project in the
repository procured.
 Data contains the data list dictionary with x value, y value
and the type of graph (bar)
 We will define the layout for this chart using the dictionary
approach.
from plotly.graph_objs import Bar
from plotly import offline
Visualizing
repo_names,stars =[],[]
repositories using plotly
for repo_dict in repo_dicts:
repo_names.append(repo_dict['name'])
[Link](repo_dict['stargazers_count'])

data =[{
'type' :'bar',
'x': repo_names,
'y': stars,
}]

my_layout ={
'title':'Most_Starred python projects on github',
'xaxis':{'title': 'Repository'},
'yaxis':{'title': 'Stars'},
}

fig = {'data': data, 'layout': my_layout}


Refining Plotly Charts:
 We can include all styling directives as key-value pairs in the data
dictionary and my_layout dictionary
 data =[{
 'type' :'bar',
 'x': repo_names,
 'y': stars,
'marker': {
'color':'rgb(60, 100, 150)',
'line':{'width': 1.5, 'color': 'rgb(25, 25, 25)'}
},
'opacity' : 0.6, •Marker settings affect the design of the bars.
•Blue bars with outlined dark gray that are 1.5pixels
 }] wide are used.
•Opacity is set to 0.6 so that it appears soft.
Adding Custom Tooltips:
 In Plotly, you can hover the cursor over an individual bar to show the
infor- mation that the bar represents. This is commonly called a tooltip,
and in this case, it currently shows the number of stars a project has.
repo_names,stars, labels =[],[],[]
owner = repo_dict['owner']['login']
description = repo_dict['description']
label =f"{owner}<br />{description}"
[Link](label)
data =[{
'type' :'bar',
'x': repo_names,
'y': stars,
'hovertext':labels,
Adding Clickable Links to Our Graph

 Because Plotly allows you to use HTML on text elements, we


can easily add links to a chart. Let’s use the x-axis labels as a
way to let the viewer visit any project’s home page on GitHub.
We need to pull the URLs from the data and use them when
generating the x-axis labels:
repo_links,stars, labels =[],[],[] We use html anchor tag to generate
the link.
<a href=‘URL’>link text</a>
for repo_dict in repo_dicts:
repo_name= repo_dict['name']
repo_url= repo_dict['html_url']
repo_link =f"<a href='{repo_url}'>{repo_name}</a>"
repo_links.append(repo_link)
The Hacker News API:
 Let us take a quick look on how to use APIs with other sites.
import requests
import json

url = '[Link]
[Link]/v0/item/[Link]'
r = [Link](url)

response_dict = [Link]()
readable_file = 'readable_hn_data.json'
with open(readable_file, 'w') as f:
[Link](response_dict,f,indent =4)
 The keys “descendants” tells us the number of comments the article received.
 The key “kids” provides the IDs of all comments made in response to the article.
 Output:
 {
 "by": "jimktrains2",
 "descendants": 221,
 "id": 19155826,
 "kids": [
 19156572,
 19158857,
 ……..
 ],
 "score": 728,
 "time": 1550085414,
 "title": "Nasa\u2019s Mars Rover Opportunity Concludes a 15-Year Mission",
 "type": "story",
 "url": "[Link]
[Link]"
 }
Conclusion:
 How to use APIs to write programs

 We used requests package to issue an API call to Github.

 Plotly is used to create a visualization for the data that we get


response to when queried

You might also like