Uploaded by chintu.pareek.pareek

Python Basic Fundamentals

advertisement
Chapter- 01
(An Introduction)
What is Python?
Rossum, and released in 1991.
It is used for:




web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?





Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Why Python?





Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed
as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python Syntax compared to other programming languages



Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.
Example
print("Hello, World!")
Python Quick start
Python is an interpreted programming language, this means that as a developer
you write Python (.py) files in a text editor and then put those files into the
python interpreter to be executed.
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
Where "helloworld.py" is the name of your python file.
Let's write our first Python file, called helloworld.py, which can be done in any
text editor.
helloworld.py
print("Hello, World!")
Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:
exit()
Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by writing
directly in the Command Line:
>>>
Hello, World!
print("Hello,
World!")
Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:
C:\Users\Your Name>python myfile.py
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Tokens: The set of elements which we use to create and execute the programs,
known as Tokens or Lexical Units. In the Token we have set of elements-
1. Keyword:
-
The predefine word in the library of python known as
keyword, we just use them without any logical and conceptual concept.
Ex: - import, if, else, elif, for, while,
do while, def, list…..
2. Python Variables / Identifiers:
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x
y = "Hello, World!"
= 5
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a
comment:
Example
Comments in Python:
#This
print("Hello, World!")
is
a
comment.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x
y
print(x)
print(y)
= 5
= "John"
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:




A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
Example
Legal variable names:
myvar
my_var
_my_var
myVar
MYVAR
myvar2 = "John"
=
=
=
=
=
"John"
"John"
"John"
"John"
"John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
x,
print(x)
print(y)
print(z)
y,
z
= "Orange", "Banana", "Cherry"
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x
print(x)
print(y)
print(z)
=
y
=
z
= "Orange"
3. Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Text Type:
Str
Numeric Types:
int, float, complex
Sequence Types:
list, tuple, range
Mapping Type:
Dict
Set Types:
set, frozenset
Boolean Type:
Bool
Binary Types:
bytes, bytearray, memoryview
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you extract
the values into variables. This is called unpacking.
Example
Unpack a list:
fruits
x,
=
y,
z
["apple", "banana", "cherry"]
=
fruits
print(x)
print(y)
print(z)
Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example
x
print("Python is " + x)
= "awesome"
You can also use the + character to add a variable to another variable:
Example
x
y
z
print(z)
= "Python
is
=
x
+
"
= "awesome"
y
Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x
def myfunc():
print("Python
= "awesome"
is
" +
x)
myfunc()
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and
can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x
= "fantastic"
myfunc()
print("Python is " + x)
Getting the Data Type
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x
print(type(x))
= 5
Python Numbers
There are three numeric types in Python:



int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x
y
z = 1j
= 1
= 2.8
#
#
# complex
Specify a Variable Type
int
float
There may be times when you want to specify a type on to a variable. This can
be done with casting. Python is an object-orientated language, and as such it
uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:



int() - constructs an integer number from an integer literal, a float literal
(by removing all decimals), or a string literal (providing the string
represents a whole number)
float() - constructs a float number from an integer literal, a float literal or
a string literal (providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
Example
Integers:
x
= int(1)
#
y
= int(2.8) #
z = int("3") # z will be 3
x
y
will
will
be
be
1
2
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
X
Y
Z
= STR(3)
#
= INT(3)
#
= FLOAT(3) # Z WILL BE 3.0
X
WILL
Y
WILL
BE
BE
'3'
3
Get the Type
You can get the data type of a variable with the type() function.
Example
x
y
print(type(x))
print(type(y))
Chapter 2
= 5
= "John"
Python if Statement Syntax
if test expression:
statement(s)
Here, the program evaluates the
only if the test expression is
If the test expression is
and will execute statement(s)
True .
False ,
In Python, the body of the
test expression
the statement(s) is not executed.
if
statement is indicated by the indentation. The
body starts with an indentation and the first unindented line marks the end.
Example: Python if Statement
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
When you run the program, the output will be:
3 is a positive number
This is always printed
This is also always printed.
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The
of
if
if..else
statement evaluates
test expression
only when the test condition is
If the condition is
False ,
and will execute the body
True .
the body of
else
is executed. Indentation is used to
separate the blocks.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
Positive or Zero
Example of if...elif...else
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Python Nested if Example
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
Here,
val
is the variable that takes the value of the item inside the sequence on
each iteration.
Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
The range() function
We can generate a sequence of numbers using
range()
function.
range(10)
will
generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as
range(start, stop,step_size) .
step_size defaults to 1 if not provided.
The
range
object is "lazy" in a sense because it doesn't generate every number
that it "contains" when we create it. However, it is not an iterator since it
supports
in , len
and
__getitem__
operations.
This function does not store all the values in memory; it would be inefficient. So
it remembers the start, stop, step size and generates the next number on the
go.
To force this function to output all the items, we can use the function
The following example will clarify this.
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Output
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list() .
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
We can use the
range()
function in
for
loops to iterate through a sequence of
numbers. It can be combined with the
len()
function to iterate through a
sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
for loop with else
A
for
loop can have an optional
else
block as well. The
else
part is executed if
the items in the sequence used in for loop exhausts.
The
break
keyword can be used to stop a for loop. In such cases, the else part
is ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the
else
and prints
No items
left.
This
the
for...else
else
statement can be used
block only when the
break
with the
break
keyword to run
keyword was not executed. Let's take an
example:
# program to display student's marks from record
student_name = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
Output
No entry with that name found.
What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate
beforehand.
Syntax of while Loop in Python
while test_expression:
Body of while
In the while loop, test expression is checked first. The body of the loop is
entered only if the
test_expression
evaluates to
True .
After one iteration, the test
expression
the
is
test_expression
checked
evaluates to
again.
This
process
continues
until
False .
In Python, the body of the while loop is determined through indentation.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as
as
True . None
and
0
are interpreted
False .
Example: Python while Loop
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
# update counter
# print the sum
print("The sum is", sum)
When you run the program, the output will be:
Enter n: 10
The sum is 55
While loop with else
Same as with for loops, while loops can also have an optional
The
else
else
block.
part is executed if the condition in the while loop evaluates to
False .
The while loop can be terminated with a break statement. In such cases,
the
else
part is ignored. Hence, a while loop's
and the condition is false.
Here is an example to illustrate this.
else
part runs if no break occurs
'''Example to illustrate
the use of else statement
with the while loop'''
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Output
Inside
Inside
Inside
Inside
loop
loop
loop
else
Example: Python break
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
Output
s
t
r
The end
Example: Python continue
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
What is pass statement in Python?
In Python programming, the
between a comment and a
pass
pass
ignores a comment entirely,
statement is a null statement. The difference
statement in Python is that while the interpreter
pass
is not ignored.
However, nothing happens when the pass is executed. It results in no
operation (NOP).
Syntax of pass
pass
Python Functions
What is a function in Python?
In Python, a function is a group of related statements that performs a specific
task.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Furthermore, it avoids repetition and makes the code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following components.
1. Keyword
def
that marks the start of the function header.
2. A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
7. An optional
return
statement to return a value from the function.
Example of a function
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
How to call a function in python?
Once we have defined a function, we can call it from another function, program
or even the Python prompt. To call a function we simply type the function name
with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
The return statement
The
return
statement is used to exit a function and go back to the place from
where it was called.
Syntax of return
return [expression_list]
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output
2
4
Scope and Lifetime of variables
Scope of a variable is the portion of a program where the variable is
recognized. Parameters and variables defined inside a function are not visible
from outside the function. Hence, they have a local scope.
The lifetime of a variable is the period throughout which the variable exits in the
memory. The lifetime of variables inside a function is as long as the function
executes.
They are destroyed once we return from the function. Hence, a function does
not remember the value of a variable from its previous calls.
Here is an example to illustrate the scope of a variable inside a function.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10
Value outside function: 20
Predefine Functions:
Python abs()
The abs() method returns the absolute value of the given number. If the
number is a complex number, abs() returns its magnitude.
Example 1: Get absolute value of a number
# random integer
integer = -20
print('Absolute value of -20 is:', abs(integer))
#random floating number
floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))
Output
Absolute value of -20 is: 20
Absolute value of -30.33 is: 30.33
2.
Python any()
The any() function returns True if any element of an iterable is True. If not,
any() returns False.
Value Returned by the any() function
The
any()

True
if at least one element of an iterable is true

False


3. p
function returns a boolean value:
if all elements are false or if an iterable is empty
l = [1, 3, 4, 0]
print(any(l))
ython bin()
The bin() method converts and returns the binary equivalent string of a given
integer. If the parameter isn't an integer, it has to implement __index__()
method to return an integer.
number = 5
print('The binary equivalent of 5 is:', bin(number))
Output
The binary equivalent of 5 is: 0b101
4.
Python chr()
The chr() method returns a character (a string) from an integer (represents
unicode code point of the character).
Example 1: How chr() works?
print(chr(97))
print(chr(65))
print(chr(1200))
Output
a
A
Ұ
Python dir()
The dir() method tries to return a list of valid attributes of the object.
number = [1, 2, 3]
print(dir(number))
print('\nReturn Value from empty dir()')
print(dir())
Python format()
The built-in format() method returns a formatted representation of the given
value controlled by the format specifier.
The format specifier could be in the format:
[[fill]align][sign][#][0][width][,][.precision][type]
where, the options are
fill
::=
any character
align
::=
"<" | ">" | "=" | "^"
sign
::=
"+" | "-" | " "
width
::=
integer
precision
::=
integer
type
::=
"b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o"
# d, f and b are type
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
Output
123
123.456790
1100
Python input()
The input() method reads a line from input, converts into a string and returns it.
Example 1: How input() works in Python?
# get input from user
inputString = input()
print('The inputted string is:', inputString)
Output
Python is interesting.
The inputted string is: Python is interesting
Example 2: Get input from user with a prompt
# get input from user
inputString = input('Enter a string:')
print('The inputted string is:', inputString)
Output
Enter a string: Python is interesting.
The inputted string is: Python is interesting
Extra Topics (Chapter 2)
Array
Arrays are used to store multiple values in one single variable:
cars = ["Ford", "Volvo", "BMW"]
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
car1
car2
car3 = "BMW"
= "Ford"
= "Volvo"
Access the Elements of an Array
You refer to an array element by referring to the index number.
x = cars[0]
Modify the value of the first array item:
cars[0] = "Toyota"
The Length of an Array
Use the len() method to return the length of an array (the number of elements in
an array).
Return the number of elements in the cars array:
x = len(cars)
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Print each item in the cars array:
for x in cars:
print(x)
Array Methods
append()
Adds an element at the end of the list
clear()
Removes all the elements from the list
copy()
Returns a copy of the list
count()
Returns the number of elements with the specified value
extend()
Add the elements of a list (or any iterable), to the end of the current list
index()
Returns the index of the first element with the specified value
insert()
Adds an element at the specified position
pop()
Removes the element at the specified position
remove()
Removes the first item with the specified value
reverse()
Reverses the order of the list
sort()
Sorts the list
1. Append
The append() method appends an element to the end of the list.
Add a list to a list:
a
=
["apple", "banana", "cherry"]
b
=
["Ford", "BMW", "Volvo"]
a.append(b)
2. Pop()
You can use the pop() method to remove an element from the
array.
cars.pop(1)
3. Remove()
You can also use the remove() method to remove an element from
the array.
cars.remove("Volvo")
4. Count()
The count() method returns the number of elements with the
specified value.
points
=
[1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
Ex: for i in range(1,6):
for j in range(1,i):
print("*",end=' ')
print()
*
**
***
****
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is
similar to lists since the value of the items stored in the list can be changed, whereas the
tuple is immutable, and the value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use. A tuple can
be defined as follows.
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
print(type(T1))
print(type(T2))
print(type(T3))
Creating a tuple with single element is slightly different. We will need to put
comma after the element to declare the tuple.
1. tup1 = ("JavaTpoint")
2. print(type(tup1))
3. #Creating a tuple with single element
4. tup2 = ("JavaTpoint",)
5. print(type(tup2))
Tuple indexing and slicing
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts
from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python also allows
us to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Consider the following example:
1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access
an element outside of tuple that raised an IndexError.
1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])
Negative Indexing
The tuple element can also access by using negative indexing. The index of -1 denotes
the rightmost element and -2 to the second last item and so on.
The elements from left to right are traversed using the negative indexing. Consider the
following example:
1. tuple1 = (1, 2, 3, 4, 5)
2. print(tuple1[-1])
3. print(tuple1[-4])
4. print(tuple1[-3:-1])
5. print(tuple1[:-1])
6. print(tuple1[-2:])
Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are
immutable. To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.
1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. print(tuple1)
Basic Tuple operations
The operators like concatenation (+), repetition (*), Membership (in) works in the same
way as they work with the list. Consider the following table for more detail.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.
Python Tuple inbuilt functions
SN
Function
Description
1
cmp(tuple1,
It compares two tuples and returns true if tuple1 is greater than tuple2
tuple2)
otherwise false.
2
len(tuple)
It calculates the length of the tuple.
3
max(tuple)
It returns the maximum element of the tuple
4
min(tuple)
It returns the minimum element of the tuple.
5
tuple(seq)
It converts the specified sequence to the tuple.
List:
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python
consists of six data-types that are capable to store the sequences, but the most common
and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the
list are separated with the comma (,) and enclosed with the square brackets [].
A list can be defined as a collection of values or items of different types. The items in the
list are separated with the comma (,) and enclosed with the square brackets [].
A list can be define as below
L=list()
L=[ ]
1. L1 = ["John", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
Characteristics of Lists
The list has the following characteristics:
o
The lists are ordered.
o
The element of the list can access by index.
o
The lists are the mutable type.
o
The lists are mutable types.
o
A list can store the number of various elements.
Let's check the first statement that lists are the ordered.
1. a = [1,2,"Peter",4.50,"Ricky",5,6]
2. b = [1,2,5,"Peter",4.50,"Ricky",6]
3. a ==b
OUTPUT : False
Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.
1. a = [1, 2,"Peter", 4.50,"Ricky",5, 6]
2. b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
3. a == b
Output : True
1. list_varible(start:stop:step)
o
The start denotes the starting index position of the list.
o
The stop denotes the last index position of the list.
o
The step is used to skip the nth element within a start:stop
Consider the following example:
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default the index value is 0 so its starts from the 0th element and go for index -1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
Updating List values
Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.
Python also provides append() and insert() methods, which can be used to add
values to the list.
Consider the following example to update the values inside the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. list.update(7)
[1,2,3,4,5,67]
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)
7. # Adding multiple-element
8. list[1:3] = [89, 78]
9. print(list)
10. # It will add value at the end of the list
11. list[-1] = 25
12. print(list)
The list elements can also be deleted by using the del keyword. Python also provides us
the remove() method if we do not know which element is to be deleted from the list.
Python List Built-in functions
Python provides the following built-in functions, which can be used with the lists.
append(x)
Adds an item (x) to the end of the list. This is equivalent
to a[len(a):] = [x].
extend(iterable)
Extends the list by appending all the items from the iterable.
This allows you to join two lists together. This method is
equivalent to a[len(a):] = iterable.
insert(i, x)
Inserts an item at a given position. The first argument is the
index of the element before which to insert. For
example, a.insert(0, x) inserts at the front of the list.
remove(x)
Removes the first item from the list that has a value of x.
Returns an error if there is no such item.
pop([i])
Removes the item at the given position in the list, and returns
it. If no index is specified, pop() removes and returns the last
item in the list.
clear()
Removes all items from the list. Equivalent to del a[:]
count(x)
Returns the number of times x appears in the list.
reverse()
Reverses the elements of the list in place.
copy()
Returns a shallow copy of the list. Equivalent to a[:].
Example: 1- Write the program to remove the duplicate element of the list.
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Example:2- Write a program to find the sum of the element in the list.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Example: 3- Write the program to find the lists consist of at least one common element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y: ---- if x in list2:
print("The common element is:",x)
Example 4 : Reverse the list
list=[11,12,13,14]
len=len(list)
i=len-1
while i>=0:
print(list[i])
i=i-1
EX:5 – Copy the data from list 1 to list2 in reverse
list=[11,12,13,14]
list2=[]
len=len(list)
i=len-1
while i>=0:
list2.append(list[i])
i=i-1
print(list2)
EX6 : Find out the duplicate value from list with it’s repetation?
Access outside package/Directory:In the python we have pre-define libraries known as classes/packages.
In these classes we have some predefine methods, to use these methods we have call these libraries
in our program.
To call these libraries use “import”
Python Date and time
Python provides the datetime module work with real dates and times. In real-world
applications, we need to work with the date and time. Python enables us to schedule our
Python script to run at a particular timing.
In Python, the date is not a data type, but we can work with the date objects by
importing the module named with datetime, time, and calendar.
In this section of the tutorial, we will discuss how to work with the date and time objects
in Python.
The datetime classes are classified in the six main classes.
Time Library:
1) time.time():- Return the global time.
2) time.localtime():- Return the time based on system location.
3) Getting
formatted time
The time can be formatted by using the asctime() function of the time module. It returns
the formatted time for the time tuple being passed.
EX:_
import time;
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
OUTPUT 
Local current time : time.struct_time(tm_year=2021, tm_mon=12, tm_mday=21, tm_hour=18,
tm_min=6, tm_sec=28, tm_wday=1, tm_yday=355, tm_isdst=0)
EX:import time;
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
2. Calendar Library:-
It will provide methods related to date and calendar.
1) month():
-month(Year, month ) :- Return the calendar of the specify month.
import calendar;
cal = calendar.month(2021, 12)
print ("Here is the calendar:")
print (cal)
Printing the calendar of whole year
The prcal() method of calendar module is used to print the calendar of the entire year.
The year of which the calendar is to be printed must be passed into this method.
Example
import calendar
#printing the calendar of the year 2019
s = calendar.prcal(2020)
Python sleep time
The sleep() method of time module is used to stop the execution of the script for a given
amount of time. The output will be delayed for the number of seconds provided as the
float.
Consider the following example.
import time
for i in range(0,5):
print(i)
#Each element will be printed after 1 second
time.sleep(1)
FUNCTIONS:Design function that accept N arguments?
# Function definition is here
* We can use it when we want to call the function with N number or arguments.
def printinfo( arg1, *vartuple ):
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
EX:- Function use the list?
list=[1,22,33,44]
def show(l):
for i in l:
print(i)
show(list)
EX:- Count repeat of a number in the list
list=[1,22,33,44,55,22]
ln=len(list)
sno=int(input("Enter the search no"))
def recount(l,no):
ln=len(l)
c=0
i=0
while(i<ln):
if l[i]==sno:
c=c+1
i=i+1
print(c)
recount(list,sno)
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is
the data type in Python, which can simulate the real-life data arrangement where some
specific value exists for some particular key. It is the mutable data-structure. The
dictionary is defined into element Keys and values.
o
Keys must be a single element
o
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object,
i.e., Numbers, string, or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to define
the dictionary is given below.
Syntax:
1. Dict = {"Name": "Tom", "Age": 22}
In the above dictionary Dict, The keys Name and Age are the string that is an immutable
object.
Let's see an example to create a dictionary and print its content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Python provides the built-in function dict() method which is also used to create
dictionary. The empty curly braces {} is used to create empty dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the
indexing.
However, the values can be accessed in the dictionary by using the keys as keys are
unique in the dictionary.
The dictionary values can be accessed in the following way.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
%s operator
The % symbol is used in Python with a large variety of data types and
configurations. It is used as an argument specifier and string formatter. %s
specifically is used to perform concatenation of strings together. It allows us to
format a value inside a string. It is used to incorporate another string within a
string. It automatically provides type conversion from value to string.
he %s operator is put where the string is to be specified. The number of values
you want to append to a string should be equivalent to the number specified in
parentheses after the % operator at the end of the string value. Following code
illustrates the usage of %s symbol :
# declaring a string variable
N name = "Geek"
# append a string within a string
print("Hey, %s!" % name)
%d operator
The %d operator is used as a placeholder to specify integer values,
decimals or numbers. It allows us to print numbers within strings or
other values. The %d operator is put where the integer is to be
specified. Floating-point numbers are converted automatically to
decimal values.
#declaring numeric variables
num = 2021
#concatenating numeric value within string
print("%d is here!!" % num)
Adding dictionary values
The dictionary is a mutable data type, and its values can be updated by using the specific
keys. The value can be updated along with key Dict[key] = value. The update() method
is also used to update an existing value.
Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.
Let's see an example to update the dictionary values.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Deleting elements using del keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Using pop() method
The pop() method accepts the key as an argument and remove the associated value.
Consider the following example.
# Creating a Dictionary
Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
EX# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x)
EX#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x])
EX#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.values():
print(x)
EX# for loop to print the items of the dictionary by using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.items():
print(x)
Built-in Dictionary methods
The built-in python dictionary methods along with the description are given below.
SN
Method
Description
1
dic.clear()
It is used to delete all the items of the dictionary.
2
dict.copy()
It returns a shallow copy of the dictionary.
3
dict.fromkeys(iterable,
None, /)
value
=
Create a new dictionary from the iterable with the values
equal to value.
4
dict.get(key, default = "None")
It is used to get the value specified for the passed key.
5
dict.has_key(key)
It returns true if the dictionary contains the specified key.
6
dict.items()
It returns all the key-value pairs as a tuple.
7
dict.keys()
It returns all the keys of the dictionary.
8
dict.setdefault(key,default= "None")
It is used to set the key to the default value if the key is not
specified in the dictionary
9
dict.update(dict2)
It updates the dictionary by adding the key-value pair of
dict2 to this dictionary.
10
dict.values()
11
len()
12
popItem()
13
pop()
14
count()
15
index()
It returns all the values of the dictionary.
Python Matrix
Introduction
A matrix is a rectangular 2-dimensional array which stores the data in rows and columns.
The matrix can store any data type such as number, strings, expressions, etc. We must be
familiar with the basic concepts of matrix before using it. The data is arranged in
horizontal called rows, and vertical arrangements are columns.
Working of Matrices
The below matrix is 2x2, which means it has two rows and two columns.
1. [[2,4],
2. [5,6]]
Creating a Matrix in Python
We can create matrix in Python using the nested list. All elements are enclosed with the
square brackets ([]) and separated by the comma. Let's see the following examples.
matrix = [[ 'Arun', 25, 90, 74],
["Sachin", 410, 87.50, 130]
[56, "Abhinay", 253, 471]
o
We have created a 3x3 matrix using the nested list.
o
The first row contains ['Arun', 25, 90, 74] in the list form.
o
The second row contains ['Sachin', 410, 87.50, 130] in the list form.
o
The third row contains [56, "Abhinay", 253, 471] in the list form.
o
We notice that our matrix consists of numbers as well as a string value.
Read the Matrix Data
In the following example, we will read each row of the defined matrix.
Example matrix = [[ 'Arun', 25, 90, 74],
['Sachin', 410, 87.50, 130],
[56, 'Abhinay', 253, 471]]
print("The matrix is: ", matrix)
Output:
The matrix is: [['Arun', 25, 90, 74], ['Sachin', 410, 87.5, 130], [56, 'Abhinay', 253, 471]]
Read the Last Element from each row
In the following example, we will read the last element of the each row using the Python
program
Example matrix = [[ 'Arun', 25, 90, 74],
['Sachin', 410, 87.50, 130],
[56, 'Abhinay', 253, 471]]
matrix_length = len(matrix)
#To read the last element from each row.
for i in range(matrix_length):
print(matrix[i][-
x])
Adding two Matrices9
We will add the two matrices and using the nested for loop through the given matrices.
Example mat1 = [[10, 13, 44],
[11, 2, 3],
[5, 3, 1]]
mat2 = [[7, 16, -6],
[9, 20, -4],
[-1, 3 , 27]]
mat3 = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(mat1)
#To Add mat1 and mat2 matrices
for i in range(len(mat1)):
for k in range(len(mat2)):
mat3[i][k] = mat1[i][k] + mat2[i][k]
#To Print the matrix
print("The sum of Matrix mat1 and mat2 = ", mat3)
Creating Matrix Using Numpy Library
The Numpy
library helps us to work with the array. To work with the Numpy, we need to install the Numpy using the
following command.
1. pip install Numpy
After a successful installation, we have to import it into our program.
1. import numpy as np
import numpy as np
mat1 = np.array([[10, -5, 15], [30, -6, 91], [2, 8, 7]])
print("The matrix is: ")
print(mat1)
Matrix Addition
We will create two matrices using the numpy.array() function and add them using the +
operator. Let's understand the following example.
Example import numpy as np
mat1 = np.array([[7, 8, 9], [3, -1, 17], [15, 10, 21]])
mat2 = np.array([[9, -18, 27], [11, 22, 33], [13, -26, 39]])
mat3 = mat1 + mat2
print("The matrix addition is: ") 9
print(mat3)
Matrix Multiplication
We will use the mumpy.dot() method to multiply both matrices. It is a dot multiplication
of the matrix mat1 and mat2 and handles the 2D array and performs multiplication. Let's
understand the following example.
Example import numpy as np
mat1 = np.array([[4, 6], [5, 10]])
mat2 = np.array([[3, -1], [11, 22]])
mat3 = mat1.dot(mat2)
print("The matrix is:")
print(mat3)
Module
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: When
using
a
function
syntax: module_name.function_name.
from
a
module,
use
the
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Save this code in the file mymodule.py
person1
"name": "John",
"age": 36,
"country": "Norway"
}
=
{
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a
print(a)
=
mymodule.person1["age"]
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Create an alias for mymodule called mx:
import mymodule as mx
a
print(a)
=
mx.person1["age"]
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
List all the defined names belonging to the platform module:
import platform
x
print(x)
= dir(platform)
Note: The dir() function can be used on all modules, also the ones you create
yourself.
Import From Module
You can choose to import only parts from a module, by using the from keyword.
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello,
" +
person1 =
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
name)
{
Note: When importing using the from keyword, do not use the module name when
referring
to
elements
in
the
module.
Example: person1["age"], not mymodule.person1["age"]
Class and Object
Python is an object oriented programming language. Almost everything in Python
is an object, with its properties and methods.
Create a Class
To create a class, use the keyword class:
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
Create Object
Now we can use the class named MyClass to create objects:
Create an object named p1, and print the value of x:
p1
print(p1.x)
=
MyClass()
The __init__() Function
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
To understand the meaning of classes we have to understand the built-in
__init__() function.
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
Create a class named Person, use the __init__() function to assign values for
name and age:
class Person:
def __init__(self,
self.name
name,
=
self.age
p1
=
=
age):
name
age
Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being
used to create a new object.
Modify Object Properties
You can modify properties on objects like this:
Set the age of p1 to 40:
p1.age = 40
Delete Object Properties
You can delete properties on objects by using the del keyword:
Delete the age property from the p1 object:
del p1.age
Delete Objects
You can delete objects by using the del keyword:
Delete the p1 object:
del p1
Python: Passing Dictionary as Arguments to Function
def func(d):
for key in d:
print("key:", key, "Value:", d[key])
# Driver's code
D = {'a':1, 'b':2, 'c':3}
func(D)
Declaring an object
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
The self

Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python
provides it.
 If we have a method that takes no arguments, we still have one argument.
 This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is
automatically converted by Python into MyClass.method(myobject, arg1, arg2) –
this is all the special self is about.
__init__ method
The __init__ method is similar to constructors in C++ and Java. Constructors are
used to initialize the object’s state. Like methods, a constructor also contains a
collection of statements(i.e. instructions) that are executed at the time of Object
creation. It runs as soon as an object of a class is instantiated. The method is
useful to do any initialization you want to do with your object.
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Class and Instance Variables
Instance variables are for data, unique to each instance and class variables are
for attributes and methods shared by all instances of the class. Instance
variables are variables whose value is assigned inside a constructor or method
with self whereas class variables are variables whose value is assigned in the
class.
Defining instance variables using a constructor.
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
# Class variables can be accessed using class
# name also
print("\nAccessing class variable using class name")
print(Dog.animal)
Output
Rodger details:
Rodger is a dog
Breed:
Pug
Color:
brown
Defining instance variables using the normal method.
# Python3 program to show that we can create
# instance variables inside methods
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed):
# Instance Variable
self.breed = breed
# Adds an instance variable
def setColor(self, color):
self.color = color
# Retrieves instance variable
def getColor(self):
return self.color
# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())
Function Polymorphism
Basic Example:print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
Using Class
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
Ex: class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Bark")
cat1 = Cat("Kitty", 2.5)
dog1 = Dog("Fluffy", 4)
for animal in (cat1, dog1):
animal.make_sound()
animal.info()
animal.make_sound()
Inheritance:The concept where we can create a new class with help of existing class is called Inheritance.
Base Class:- The class which is previously design is called base/parent class.
Derive Class:- The class design with the help of base class is called derive class.
Syntax:- # define a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
Example 1: Python Inheritance
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
labrador.name = "Rohu"
labrador.eat()
# call subclass method
labrador.display()
The super() Method in Python Inheritance
Previously we saw that the same method in the subclass overrides the method
in the superclass.
However, if we need to access the superclass method from the subclass, we
use the
super()
method. For example
,
class Animal:
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# override eat() method
def eat(self):
# call the eat() method of the superclass using super()
super().eat()
print("I like to eat bones")
# create an object of the subclass
labrador = Dog()
labrador.eat()
Multiple Inheritance
A class can be derived from more than one superclass in Python. This is called
multiple inheritance.
For example, A class
Bat
is derived from superclasses
Mammal
and
WingedAnimal .
It makes sense because bat is a mammal as well as a winged animal.
Syntax :
class SuperClass1:
# features of SuperClass1
class SuperClass2:
# features of SuperClass2
class MultiDerived(SuperClass1, SuperClass2):
# features of SuperClass1 + SuperClass2 + MultiDerived class
Example: Python Multiple Inheritance
class Mammal:
def mammal_info(self):
print("Mammals can give direct birth.")
class WingedAnimal:
def winged_animal_info(self):
print("Winged animals can flap.")
class Bat(Mammal, WingedAnimal):
pass
# create an object of Bat class
b1 = Bat()
b1.mammal_info()
b1.winged_animal_info()
Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}. Python also provides the set() method, which can be used to create the set
by the passed sequence.
Example 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Example 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
It can contain any type of element such as integer, float, tuple etc. But mutable elements
(list, dictionary, set) can't be a member of set. Consider the following example.
# Creating a set which have immutable elements
set1 = {1,2,3, "Hello", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Hello",4]}
print(type(set2))
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
`
Example: 1 - Using add() method
Adding items to the set
Python provides the add() method and update() method which can be used to add
some particular item to the set. The add() method is used to add a single element
whereas the update() method is used to add multiple elements to the set
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Removing items from the set
Python provides the discard() method and remove() method which can be used to
remove the items from the set. The difference between these function, using discard()
function if the item does not exist in the set then the set remain unchanged whereas
remove() method will through an error.
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
Python provides also the remove() method to remove the item from the set. Consider
the following example to remove the items using remove() method.
Example-2 Using remove() function
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
We can also use the pop() method to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which element
will be popped from set.
Consider the following example to remove the item from the set using pop() method.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)
Difference between discard() and remove()
Despite the fact that discard() and remove() method both perform the same task, There
is one main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the Python
will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the Python will raise an error.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving items through discard() method...");
Months.discard("Feb"); #will not give an error although the key feb is not available in the set
print("\nprinting the modified set...")
print(Months)
print("\nRemoving items through remove() method...");
Months.remove("Jan") #will give an error as the key jan is not available in the set.
print("\nPrinting the modified set...")
print(Months)
Union of two Sets
The union of two sets is calculated by using the pipe (|) operator. The union of the two
sets contains all the items that are present in both the sets.
Consider the following example to calculate the union of two sets.
Example 1: using union | operator
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Python also provides the union() method which can also be used to calculate the union
of two sets. Consider the following example.
Example 2: using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
Intersection of two sets
The intersection of two sets can be performed by the and & operator or
the intersection() function. The intersection of the two sets is given as the set of the
elements that common in both sets.
Consider the following example.
Example 1: Using & operator
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Output:
{'Monday', 'Tuesday'}
Example 2: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
Output:
{'Martin', 'David'}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
Output:
{1,2,5}
The intersection_update() method
The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it
modifies the original set by removing the unwanted items, on the other hand, the
intersection() method returns a new set.
Consider the following example.
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
SET
When a set is defined this way, each <obj> becomes a distinct element of the
set, even if it is an iterable. This behavior is similar to that of the .append() list
method.
Thus, the sets shown above can also be defined like this:
>>> x = {'q', 'u', 'u', 'x'}
>>> x
{'x', 'q', 'u'}
A set can be empty. However, recall that Python interprets empty curly braces
({}) as an empty dictionary, so the only way to define an empty set is with
the set() function:
{}
>>>
>>> x = set()

>> type(x)
<class 'set'>
>>> x
set()
>>> x = {}
>>> type(x)
<class 'dict'>
Set Size and Membership
The len() function returns tthe number of elements in a set, and the in and not
in operators can be used to test for membership:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> len(x)
3
>>> 'bar' in x
True
>>> 'qux' in x
False
union can be performed with the | operator:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1 | x2
{'baz', 'quux', 'qux', 'bar', 'foo'}
Set union can also be obtained with the .union() method. The method is
invoked on one of the sets, and the other is passed as an argument:
>>>
>>> x1.union(x2)
{'baz', 'quux', 'qux', 'bar', 'foo'}
More than two sets may be specified with either the operator or the method:
>>>
>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>> a.union(b, c, d)
{1, 2, 3, 4, 5, 6, 7}
>>> a | b | c | d
{1, 2, 3, 4, 5, 6, 7}
Intersection
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.intersection(x2)
{'baz'}
>>> x1 & x2
{'baz'}
You can specify multiple sets with the intersection method and operator, just
like you can with set union:
>>>
>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>> a.intersection(b, c, d)
{4}
>>> a & b & c & d
{4}
Compute the symmetric difference between sets.
and x1 ^ x2 return the set of all elements in
either x1 or x2, but not both:
x1.symmetric_difference(x2)
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.symmetric_difference(x2)
{'foo', 'qux', 'quux', 'bar'}
>>> x1 ^ x2
{'foo', 'qux', 'quux', 'bar'}
Other Methods For Modifying Sets
x.add(<elem>)
Adds an element to a set.
x.add(<elem>)
>>>
adds <elem>, which must be a single immutable object, to x:
>>> x = {'foo', 'bar', 'baz'}
>>> x.add('qux')
>>> x
{'bar', 'baz', 'foo', 'qux'}
x.remove(<elem>)
Removes an element from a set.
x.remove(<elem>)
removes <elem> from x. Python raises an exception if <elem> is
not in x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.remove('baz')
>>> x
{'bar', 'foo'}
>>> x.remove('qux')
x.discard(<elem>)
Removes an element from a set.
also removes <elem> from x. However, if <elem> is not in x, this
method quietly does nothing instead of raising an exception:
x.discard(<elem>)
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.discard('baz')
>>> x
{'bar', 'foo'}
>>> x.discard('qux')
>>> x
{'bar', 'foo'}
x.pop()
removes and returns an arbitrarily chosen element from x. If x is
empty, x.pop() raises an exception:
x.pop()
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.pop()
'bar'
>>> x
{'baz', 'foo'}
>>> x.pop()
'baz'
>>> x
{'foo'}
>>> x.pop()
'foo'
>>> x
set()
x.clear()
x.clear()
removes all elements from x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x
{'foo', 'bar', 'baz'}
>>>
>>> x.clear()
>>> x
set()
Frozen Sets
Python provides another built-in type called a frozenset, which is in all respects
exactly like a set, except that a frozenset is immutable. You can perform nonmodifying operations on a frozenset:
>>>
>>> x = frozenset(['foo', 'bar', 'baz'])
>>> x
frozenset({'foo', 'baz', 'bar'})
>>> len(x)
3
>>> x & {'baz', 'qux', 'quux'}
frozenset({'baz'})
>>> x = frozenset(['foo', 'bar', 'baz'])
>>> x.add('qux')
Traceback (most recent call last):
File "<pyshell#127>", line 1, in <module>
x.add('qux')
AttributeError: 'frozenset' object has no attribute 'add'
File Handling
Python too supports file handling and allows users to handle files i.e., to read
and write files, along with many other file handling options, to operate on files.
The concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but like other concepts of
Python, this concept here is also easy and short. Python treats files differently as
text or binary and this is important. Each line of code includes a sequence of
characters and they form a text file. Each line of a file is terminated with a
special character, called the EOL or End of Line characters like comma {,} or
newline character. I
Working of open() function
Before performing any operation on the file like reading or writing, first, we have
to open that file. For this, we should use Python’s inbuilt function open() but at
the time of opening, we have to specify the mode, which represents the purpose
of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some
data then it will be overridden but if the file is not present then it creates the
file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
EX:
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
Working of read() mode
There is more than one way to read a file in Python. If you need to extract a
string that contains all characters in the file then we can use file.read(). The full
code would work like this:
# Python code to illustrate read() mode
file = open("file.txt", "r")
print (file.read())
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))
Creating a file using write() mode
Let’s see how to create a file and how to write mode works, so in order to
manipulate the file, write the following in your Python environment:
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Working of append() mode
Let us see how the append mode works:
# Python code to illustrate append() mode
file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()
Use of With
# Python code to illustrate with()
with open("file.txt") as file:
data = file.read()
# do something with data
Using write along with the with() function
We can also use the write function along with the with() function:
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")
Example: Implementing all the functions in file handling
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def append_file(filename, text):
try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)
def rename_file(filename, new_filename):
try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
# write data in a text file.
file = open("myfile.txt","w")
L = ["This is Lagos \n","This is Python \n","This is Fcc \n"]
#i assigned ["This is Lagos \n","This is Python \n","This is Fcc \n"]
#to variable L
What is a CSV?
CSV (Comma Separated Values) is a simple file format used to store tabular
data, such as a spreadsheet or database. A CSV file stores tabular data
(numbers and text) in plain text. Each line of the file is a data record. Each
record consists of one or more fields, separated by commas. The use of the
comma as a field separator is the source of the name for this file format.
Run this program with the aapl.csv file in the same directory.

Let us try to understand this piece of code.
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)

Here, we first open the CSV file in READ mode. The file object is named
as csvfile. The file object is converted to csv.reader object. We save the
csv.reader object as csvreader.
fields = csvreader.next()

csvreader is an iterable object. Hence, .next() method returns the current row
and advances the iterator to the next row. Since the first row of our csv file
contains the headers (or field names), we save them in a list called fields.
for row in csvreader:
rows.append(row)

Now, we iterate through the remaining rows using a for loop. Each row is
appended to a list called rows. If you try to print each row, one can find that a
row is nothing but a list containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))

csvreader.line_num is nothing but a counter which returns the number of
rows that have been iterated.
Example : Writing to a CSV file
import csv
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
# name of csv file
filename = "university_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)

USing csv.reader(): At first, the CSV fil e is opened using the open() method
in ‘r’ mode(specifies read mode while opening a file) which returns the file
object then it is read by using the reader() method of CSV module that returns
the reader object that iterates throughout the lines in the specified CSV
document.
Note: The ‘with’ keyword is used along with the open() method as it simplifies
exception handling and automatically closes the CSV file.
import csv
# opening the CSV file
with open('Giants.csv', mode ='r')as file:
# reading the CSV file
csvFile = csv.reader(file)
# displaying the contents of the CSV file
for lines in csvFile:
print(lines)
#The \n is placed to indicate End of Line
file.write("Hello There \n")
file.writelines(L)
file.close()
# use the close() to change file access modes
file = open("myfile.txt","r+")
print("Output of the Read function is ")
print(file.read())
print()
# The seek(n) takes the file handle to the nth
# byte from the start.
file.seek(0)
print( "The output of the Readline function is ")
print(file.readline())
print()
file.seek(0)
# To show difference between read and readline
print("Output of Read(12) function is ")
print(file.read(12))
print()
file.seek(0)
print("Output of Readline(8) function is ")
print(file.readline(8))
file.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file.readlines())
print()
file.close()
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")
Required for pychar
1. Install “metplotlib” - Interpriter
2. Install “numpy”
Then we are able to run programEx1.
#!/usr/bin/python
import matplotlib.pyplot as plt
radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]
plt.plot(radius, area)
plt.show()
Ex2.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('y-axis')
plt.xlabel('x-axis')
plt.show()
Ex 3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1000, 20)
y1 = x ** 2 + 500 * x
y2 = x ** 2
plt.plot(x, y1)
plt.plot(x, y2)
plt.show()
Python - Exceptions Handling
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the tryand except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
These exceptions can be handled using the try statement:
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable
x
except:
print("Something else went wrong")
is
not
defined")
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something
else:
print("Nothing went wrong")
went
wrong")
Finally
The finally block, if specified, will be executed regardless if the try block raises
an error or not.
Example
try:
print(x)
except:
print("Something
finally:
print("The 'try except' is finished")
went
wrong")
Example
Try to open and write to a file that is not writable:
try:
f
= open("demofile.txt")
try:
f.write("Lorum
except:
print("Something
went
wrong
when
writing
finally:
f.close()
except:
print("Something went wrong when opening the file")
Raise an exception
Ipsum")
to
the
file")
As a Python developer you can choose to throw an exception if a condition
occurs.
To throw (or raise) an exception, use the raise keyword.
Example
Raise an error and stop the program if x is lower than 0:
x
=
-1
if x
raise Exception("Sorry, no numbers below zero")
< 0:
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
x
= "hello"
if not type(x)
raise TypeError("Only integers are allowed")
Written content in the file successfully
Now replace mode from ‘W’ to ‘r’
try:
a=int(input("Enter the number"))
b=int(input("Enter the number"))
c=a/b
except Exception:
print("Divive by zero")
else:
print(c)
is int:
import
import
from
import
numpy
pandas
pandas
import
matplotlib.pyplot
data
=
[23,
plt.bar([1,2,3,4,5],
plt.show()
import
import
from
import
45,
numpy
pandas
pandas
import
matplotlib.pyplot
data
=
[23,
plt.bar(range(len(data)),
plt.show()
45,
as
as
Series,
as
56,
as
as
Series,
as
56,
data,
np
pd
DataFrame
plt
78,
213]
data)
np
pd
DataFrame
plt
78,
213]
color='red')
Programs
Python program to swap two elements in a list
1. Python | Ways to find length of list
2. Maximum of two numbers in Python
3. Minimum of two numbers in Python
4. Python program to Find the size of a Tuple
5. Python – Maximum and Minimum K elements in Tuple
6. Python – Sum of tuple elements
7. Python – Row-wise element Addition in Tuple Matrix
8. Create a list of tuples from given list having number and its cube in each
tuple
9. Program to print half Diamond star pattern
10.
Programs for printing pyramid patterns in Python
11.
Program to print the diamond shape
12.
Python | Print an Inverted Star Pattern
13.
Python Program to print digit pattern
Panda
Pandas is an open-source library that is made mainly for working with
relational or labeled data both easily and intuitively. It provides various data
structures and operations for manipulating numerical data and time series.
This library is built on top of the NumPy library. Pandas is fast and it has high
performance & productivity for users.
Pandas generally provide two data structures for manipulating data, They are:


Series
DataFrame
Series: Pandas Series is a one-dimensional labeled array capable of holding
data of any type (integer, string, float, python objects, etc.). The axis labels are
collectively called indexes. Pandas Series is nothing but a column in an excel
sheet. Labels need not be unique but must be a hashable type.
Creating a Series
In the real world, a Pandas Series will be created by loading the datasets from
existing storage, storage can be SQL Database, CSV file, an Excel file. Pandas
Series can be created from the lists, dictionary, and from a scalar value etc.
import pandas as pd
import numpy as np
# Creating empty series
ser = pd.Series()
print(ser)
# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
print(ser)
Series([], dtype: float64)
0
g
1
e
2
e
3
k
4
s
dtype: object
Creating a DataFrame:
In the real world, a Pandas DataFrame will be created by loading the datasets
from existing storage, storage can be SQL Database, CSV file, an Excel file.
Pandas DataFrame can be created from the lists, dictionary, and from a list of
dictionaries, etc.
import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
Output:
Empty DataFrame
Columns: []
Index: []
0
0
Geeks
1
For
2
Geeks
3
is
4
portal
5
for
6
Geeks
Python Exercise.
1. Write a Python program to sum all the items
2. Write a Python program to multiply all the items in a list
3. Write a Python program to get the largest number from a list
4. Write a Python program to get the smallest number from a list
5. Write a Python program to count the number of strings where the string length is 2
or more and the first and last character are same from a given list of strings
6. Write a Python program to remove duplicates from a list
7. Write a Python program to check a list is empty or not
8. Write a Python program to clone or copy a list
9. Write a Python program to find the list of words that are longer than n from a given
list of words
10 Write a Python program to get variable unique identification number or string
11. Write a Python program to find common items from two lists
12 Write a Python program to split a list based on first character of word
13. Write a Python program to select the odd number of a list
14 Write a Python Program to count unique values inside a list
Basic Example
# importing the required module
import matplotlib.pyplot as plt
#
x
#
y
x axis values
= [1,2,3]
corresponding y axis values
= [2,4,1]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('My first graph!')
# function to show the plot
plt.show()
Example 1: Plotting a single vector using quiver() method in matplotlib module.
import numpy as np
import matplotlib.pyplot as plt
# Vector origin location
X = [0]
Y = [0]
# Directional vectors
U = [2]
V = [1]
# Creating plot
plt.quiver(X, Y, U, V, color='b', units='xy', scale=1)
plt.title('Single Vector')
# x-lim and y-lim
plt.xlim(-2, 5)
plt.ylim(-2, 2.5)
# Show plot with grid
plt.grid()
plt.show()
Time Series Plot or Line plot with Pandas
import pandas as pd
# Create a list of data to be represented in x-axis
days = [ 'Saturday' , 'Sunday' , 'Monday' , 'Tuesday' ,
'Wednesday' , 'Thursday' , 'Friday' ]
# Create a list of data to be
# represented in y-axis
calories = [ 1670 , 2011 , 1853 , 2557 ,
1390 , 2118 , 2063 ]
# Create a dataframe using the two lists
df_days_calories = pd.DataFrame(
{ 'day' : days , 'calories' : calories })
df_days_calories
# use plot() method on the dataframe
df_days_calories.plot( 'day' , 'calories' )
Example :-
import pandas as pd
# Create a list of data to
# be represented in x-axis
subjects = [ 'Math' , 'English' , 'History' ,
'Chem' , 'Geo' , 'Physics' , 'Bio' , 'CS' ]
# Create a list of data to be
# represented in y-axis
stress = [ 9 , 3 , 5 , 1 , 8 , 5 , 10 , 2 ]
# Create second list of data
# to be represented in y-axis
grades = [ 15 , 10 , 7 , 8 , 11 , 8 , 17 , 20 ]
# Create a dataframe using the three lists
df = pd.DataFrame(list(zip( stress , grades )),
index = subjects ,
columns = [ 'Stress' , 'Grades' ])
df
# variables given in the dataframe
df.plot()
Ex1
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()
Panda DataFrame
Example:import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
Locate Row
print(df.loc[0])
Named Indexes
With the index argument, you can name your own indexes.
Example
Add a list of names to give each row a name:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = pd.DataFrame(data, index = ["day1", "day2", "day3"])
print(df)
Locate Named Indexes
Use the named index in the loc attribute to return the specified row(s).
Example
Return "day2":
#refer to the named index:
print(df.loc["day2"])
Load Files Into a DataFrame
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Matplotlib Plotting
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8]
and [3, 10] to the plot function.
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints)
plt.show()
Plotting Without Line
To plot only the markers, you can use shortcut string notation parameter 'o',
which means 'rings'.
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()
Multiple Points
You can plot as many points as you like, just make sure you have the same
number of points in both axis.
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()
Default X-Points
If we do not specify the points on the x-axis, they will get the default values 0,
1, 2, 3 (etc., depending on the length of the y-points.
So, if we take the same example as above, and leave out the x-points, the
diagram will look like this:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()
The x-points in the example above are [0, 1, 2, 3, 4, 5].
Matplotlib Markers
Markers
You can use the keyword argument marker to emphasize each point with a
specified marker:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o')
plt.show()
Marker Reference
You can choose any of these markers:
Marker
Description
'o'
Circle
'*'
Star
'.'
Point
','
Pixel
'x'
X
'X'
X (filled)
'+'
Plus
'P'
Plus (filled)
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the
x- and y-axis.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Creating Scatter Plots
With Pyplot, you can use the scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of
the same length, one for the values of the x-axis, and one for values on the yaxis:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
How to Use the ColorMap
You can specify the colormap with the keyword argument cmap with the value of
the colormap, in this case 'viridis' which is one of the built-in colormaps
available in Matplotlib.
In addition you have to create an array with values (from 0 to 100), one value
for each point in the scatter plot:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.show()
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
Bar Color
The bar() and barh() take the keyword argument color to set the color of the
bars:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x, y, color = "red")
plt.show()
Panda
What is a Series?
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)
Labels
If nothing else is specified, the values are labeled with their index number. First
value has index 0, second value has index 1 etc.
This label can be used to access a specified value.
print(myvar[0])
Create Labels
With the index argument, you can name your own labels.
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)
Key/Value Objects as Series
You can also use a key/value object, like a dictionary, when creating a Series.
import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = pd.Series(calories)
print(myvar)
To select only some of the items in the dictionary, use the index argument and
specify only the items you want to include in the Series.
import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = pd.Series(calories, index = ["day1", "day2"])
print(myvar)
DataFrames
Data sets in Pandas are usually multi-dimensional tables, called DataFrames.
Series is like a column, a DataFrame is the whole table.
Create a DataFrame from two Series:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
myvar = pd.DataFrame(data)
print(myvar)
Locate Row
As you can see from the result above, the DataFrame is like a table with rows
and columns.
Pandas use the loc attribute to return one or more specified row(s)
#refer to the row index:
print(df.loc[0])
Return row 0 and 1:
print(df.loc[[0, 1]])
Load Files Into a DataFrame
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
max_rows
The number of rows returned is defined in Pandas option settings.
You can check your system's maximum rows with
the pd.options.display.max_rows statement.
import pandas as pd
print(pd.options.display.max_rows)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
gasPrice = pd.read_csv('gas_prices.csv')
plt.plot(gasPrice.Year, gasPrice.Canada)
plt.suptitle('Gas Price Comparison')
plt.title('Canada', fontdict={'fontsize':15,'fontweight':'bold'})
plt.xlabel('Year')
plt.ylabel('Price in USD')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
gasPrice = pd.read_csv('gas_prices.csv')
plt.plot(gasPrice.Year, gasPrice.Canada)
plt.suptitle('Gas Price Comparison')
plt.title('Canada', fontdict={'fontsize':15,'fontweight':'bold'})
plt.xlabel('Year')
plt.ylabel('Price in USD')
plt.xticks([1990,1992,1994,1996,1998,2000,2002,2004,2006,2008])
plt.yticks([1,1.5,2,2.5,3,3.5,4])
1. . Write Python program to sort words in a sentence in
decreasing order of their length. Display the sorted words along
with their length.
2. Write Pythonic code to create a function called most_frequent
that takes a string and prints the letters in decreasing order of
frequency. Use dictionaries.
3. Write Python Program to simulate a Bank Account with support
for depositMoney, withdrawMoney and showBalance
Operations. (using Class)
4. Program to demonstrate the Overriding of the Base Class
method in the Derived Class.
5. Write a Python function generatefibo(n) where n is the limit, using a
generator function Fibonacci (max) (where max is the limit n) that produces
the Fibonacci series.
6. Write a statement in Python to open a text file STORY.TXT so that new
contents can be added at the end of it.
7. Write AddCustomer(Customer) and DeleteCustomer(Customer) methods in
Python to add a new Customer and delete a Customer from a List
Download