Python Unit-I Merged
Python Unit-I Merged
TECHNOLOGY: PUTTUR
(AUTONOMOUS)
II B.Tech. – I Sem.
• a = 50
• b =100
Object Identity
In Python, every created object identifies uniquely in Python.
The built-in id() function, is used to identify the object identifier.
Ex:
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944
Multiple Assignments
1. Assigning multiple values to multiple variables
We can assign the more than one variable
simultaneously on the same line. For example -
a, b = 5, 4
print(a,b)
Output:
54
Values are printed in the given order.
2. Assign a single value to the multiple variables
We can assign the single value to the multiple
variables on the same line. Consider the
following example.
Example
a=b=c="JavaTpoint"
print(a)
print(b)
print(c)
Output:
JavaTpoint JavaTpoint JavaTpoint
Python Keywords
• Python Keywords are special reserved words that
convey a special meaning to the
compiler/interpreter.
• Each keyword has a special meaning and a
specific operation. These keywords can't be used
as a variable. Following is the List of Python
Keywords.
• True False None and as asset
def class continue break else finally
elif del except global for if
from import raise try or return
pass nonlocal in not is lambda
• True - It represents the Boolean true, if the
given condition is true, then it returns "True".
Non-zero values are treated as true.
• False - It represents the Boolean false; if the
given condition is false, then it returns "False".
Zero value is treated as false
• None - It denotes the null value or void. An
empty list or Zero can't be treated as None.
• and - It is a logical operator. It is used to check
the multiple conditions. It returns true if both
conditions are true. Consider the following
truth table.
assert - This keyword is used as the debugging tool in Python.
It checks the correctness of the code. It raises an
AssertionError if found any error in the code and also prints
the message with an error.
Example:
a = 10
b=0
print('a is dividing by Zero')
assert b != 0
print(a / b)
Output:
a is dividing by Zero Runtime Exception: Traceback (most
recent call last): File
"/home/40545678b342ce3b70beb1224bed345f.py", line 4,
in assert b != 0, "Divide by 0 error" AssertionError: Divide
by 0 error
Python input() Function
Python input() function is used to get input from the
user. It prompts for the user input and reads a line.
After reading data, it converts it into a string and
returns that. It throws an error EOFError if EOF is
read.
Signature
input ([prompt])
Parameters
prompt: It is a string message which prompts for the
user input.
Return
It returns user input after converting into a string.
Python input() Function Example 1
Here, we are using this function get user input and
display to the user as well.
# Python input() function example
# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
Output:
Enter a value: 45 You entered: 45
Python input() Function Example 2
The input() method returns string value. So, if we
want to perform arithmetic operations, we need to
cast the value first. See the example below.
# Python input() function example
# Calling function
val = input("Enter an integer: ")
# Displaying result
val = int(val) # casting into string
sqr = (val*val) # getting square
print("Square of the value:",sqr)
Output:
Enter an integer: 12 Square of the value: 144
Indentation in Python Programming Language
• Indentation refers to implementing proper spaces
and tabs at starting any statement, method and
block of code in the python programming
language.
• Due to these indentations, we can easily identify
the beginning point and at the endpoint of any
conditional loop, functions, if-else statements and
so on.
• The role of all whitespaces matters; if a block of
code is starting by applying a white space, it must
end on the same indent.
• All statements must have the same number of
whitespaces or tabs so that the distance to the
left of the screen belongs to the same block of
code. If a block has to be more deeply nested, it
is indented further to the right.
• Advantages of Indentation in Python
• Indentation is used in python to represent a
certain block of code, but in other programming
languages, they refer to various brackets. Due to
indentation, the code looks more efficient and
beautifully structured.
• Indentation rules used in a python programming
language are very simple; even a programmer
wants their code to be readable.
• Also, indentation increases the efficiency and
readability of the code by structuring it
beautifully.
• Disadvantages of Indentation in Python
• Due to the uses of whitespaces in indentation,
sometimes it is a very tough task to fix the
indentation error when there are many lines of
code.
• The various popular programming languages like
C, C++, Java use braces for indentation, so
anybody coming from the other side of the
developed world finds it hard to adjust to the
idea of using whitespaces for the indentation
# Python program to find the maximum out of two numbers:
def max(x,y): # max function will return the maximum am
ong the two numbers
if(x>y):
return x
else:
return y
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Finding the Maximum out of a:", a ,"and b:", b)
c=max(a,b) # calling the max function
print(c,"is maximum") # printing the result
The output of the above program:
IndentationError: expected an indented block
• Data Types:
1.Single-Value data types - int, float, Complex and
Boolean
2. Multi-Valued Data - Lists, Tuples, Sets,
Dictionaries
Standard data types
• A variable can hold different types of values. For
example, a person's name must be stored as a
string whereas its id must be stored as an integer.
Numbers , Sequence Type, Boolean, Set,Dictionary
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
None Type : NoneType
• Integer data type:
• a=5
• The variable a holds integer value five. Python
interpreter will automatically interpret variables a as
an integer type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'> <type 'str'> <type 'float'>
• Numbers
• Number stores numeric values. The integer, float,
and complex values belong to a Python Numbers
data-type. Python provides the type() function to
know the data-type of the variable.
• Similarly, the isinstance() function is used to
check an object belongs to a particular class.
• Python creates Number objects when a number
is assigned to a variable.
• For example;
• a=5
• print("The type of a", type(a))
•
• b = 40.5
• print("The type of b", type(b))
•
• c = 1+3j
• print("The type of c", type(c))
• print(" c is a complex number", isinstance(1+3j,complex))
• Output:
• The type of a <class 'int'> The type of b <class 'float'> The
type of c <class 'complex'> c is complex number: True
• Int - Integer value can be any length such as
integers 10, 2, 29, -20, -150 etc. Python has no
restriction on the length of an integer. Its value
belongs to int
• Float - Float is used to store floating-point
numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto 15 decimal points.
• complex - A complex number contains an
ordered pair, i.e., x + iy where x and y denote the
real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
In Python, the data type is set when you assign a
value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"})
frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
• Python Lists
• mylist = ["apple", "banana", "cherry"]
• List
• Lists are used to store multiple items in a single
variable.
• Lists are one of 4 built-in data types in Python
used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different
qualities and usage.
• Lists are created using square brackets:
• Example
• Create a List:
• thislist = ["apple", "banana", "cherry"]
print(thislist)
• List Items
• List items are ordered, changeable, and allow
duplicate values.
• List items are indexed, the first item has index [0],
the second item has index [1] etc.
• Ordered
• When we say that lists are ordered, it means that
the items have a defined order, and that order will
not change.
• If you add new items to a list, the new items will be
placed at the end of the list.
• Note: There are some list methods that will change
the order, but in general: the order of the items will
not change.
• Changeable
• The list is changeable, meaning that we can
change, add, and remove items in a list after it
has been created.
• Allow Duplicates
• Since lists are indexed, lists can have items with
the same value:
• Example
• Lists allow duplicate values:
• thislist = ["apple", "banana", "cherry", "apple",
"cherry"]
print(thislist)
List Length
To determine how many items a list has, use the
len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
O/P 3
Python Tuples
mytuple = ("apple", "banana", "cherry")
Tuple
Tuples are used to store multiple items in a single
variable.
Tuple is one of 4 built-in data types in Python
used to store collections of data, the other 3
are List, Set, and Dictionary, all with different
qualities and usage.
A tuple is a collection which is ordered and
unchangeable.
Tuples are written with round brackets.
Example
thistuple = ("apple", "banana", "cherry")
print(thistuple)
o/p ('apple', 'banana', 'cherry')
• Tuple Items
• Tuple items are ordered, unchangeable, and
allow duplicate values.
• Tuple items are indexed, the first item has index
[0], the second item has index [1] etc.
• Ordered
• When we say that tuples are ordered, it means
that the items have a defined order, and that
order will not change.
• Unchangeable
• Tuples are unchangeable, meaning that we
cannot change, add or remove items after the
tuple has been created.
• Allow Duplicates
• Since tuples are indexed, they can have items
with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple",
"cherry")
print(thistuple)
O/P
('apple', 'banana', 'cherry', 'apple', 'cherry')
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
o/p ('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)
Python Sets
myset = {"apple", "banana", "cherry"}
Set
Sets are used to store multiple items in a single
variable.
Set is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.
A set is a collection which is unordered,
unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can
remove items and add new items.
• Set Items
• Set items are unordered, unchangeable, and do
not allow duplicate values.
• Unordered
• Unordered means that the items in a set do not
have a defined order.
• Set items can appear in a different order every
time you use them, and cannot be referred to
by index or key.
Unchangeable
Set items are unchangeable, meaning that we
cannot change the items after the set has been
created.
Once a set is created, you cannot change its items,
but you can remove items and add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
A set can contain different data types:
Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
print(set1)
o/p
{"abc", 34, True, 40, "male"}
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
• Dictionary
• 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.
As of Python version 3.7, dictionaries are ordered. In
Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have
keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
o/p {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
• Ordered or Unordered?
• As of Python version 3.7, dictionaries are ordered. In
Python 3.6 and earlier, dictionaries are unordered.
• When we say that dictionaries are ordered, it means
that the items have a defined order, and that order
will not change.
• Unordered means that the items does not have a
defined order, you cannot refer to an item by using
an index.
• Changeable
• Dictionaries are changeable, meaning that we can
change, add or remove items after the dictionary
has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same
key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
o/p {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Strings
Strings in python are surrounded by either single quotation
marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
Assign String to a Variable
Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
Example
a = "Hello“
print(a)
Multiline Strings
You can assign a multiline string to a variable by
using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Slicing
You can return a range of characters by using the
slice syntax.
Specify the start index and the end index,
separated by a colon, to return a part of the
string.
Example
Get the characters from position 2 to position 5
(not included):
b = "Hello, World!"
print(b[2:5])
Note: The first character has index 0.
• Slice From the Start
• By leaving out the start index, the range will start
at the first character:
• Example
• Get the characters from the start to position 5
(not included):
• b = "Hello, World!"
print(b[:5])
• o/p Hello
Slice To the End
By leaving out the end index, the range will go to
the end:
Example
Get the characters from position 2, and all the way
to the end:
b = "Hello, World!"
print(b[2:])
o/p llo, World!
Negative Indexing
Use negative indexes to start the slice from the
end of the string: Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -
2):
b = "Hello, World!"
print(b[-5:-2])
o/p orl
SIDDARTHA INSTITUTE OF SCIENCE AND
TECHNOLOGY: PUTTUR
(AUTONOMOUS)
II B.Tech. – I Sem.
== != Equality operators.
= %= /= //= -= +=
*= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Control Flow
Branching: Simple if
The if statement
The if statement is used to test a particular condition
and if the condition is true, it executes a block of
code known as if-block.
The condition of if statement can be any valid logical
expression which can be either evaluated to true or
false.
i = i+1
Output:
Enter the number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Python For Loops
A for loop is used for iterating over a sequence (that
is either a list, a tuple, a dictionary, a set, or a
string).
This is less like the for keyword in other
programming languages, and works more like an
iterator method as found in other object-
orientated programming languages.
With the for loop we can execute a set of
statements, once for each item in a list, tuple, set
etc.
Example
# Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
o/p
apple
banana
cherry
The for loop does not require an indexing variable
to set beforehand.
Looping Through a String
Even strings are iterable objects, they contain a
sequence of characters:
Example
#Loop through the letters in the word "banana":
for x in "banana":
print(x)
b
a
n
a
n
a
The range() Function
To loop through a set of code a specified number of
times, we can use the range() function,
The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
Example
#Using the range() function:
for x in range(6):
print(x)
o/p
0
1
2
3
4
5
• Note that range(6) is not the values of 0 to 6,
but the values 0 to 5.
The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
2
3
4
5
The range() function defaults to increment the sequence by
1, however it is possible to specify the increment value by
adding a third parameter: range(2, 30, 3):
Example
# Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
2
5
8
11
14
17
20
23
26
29
Else in For Loop
The else keyword in a for loop specifies a block of
code to be executed when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message
when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
o/p
0
1
2
3
4
5
Finally finished!
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each
iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
o/p
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
The pass Statement
for loops cannot be empty, but if we use for some
reason, have a for loop with no content, put in
the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
SIDDARTHA INSTITUTE OF SCIENCE AND
TECHNOLOGY: PUTTUR
(AUTONOMOUS)
II B.Tech. – I Sem.
Output:
Value of the function is : 50
Value of the function is : 90
Fruitful functions:
Python Function within Another Function
Inner or nested function refers to a function
defined within another defined function. Inner
functions can access the parameters of the outer
scope.
Inner functions are constructed to cover them from
the changes that happen outside the function.
Many developers regard this process as
encapsulation.
Ex:
# defining a nested function
def function1():
string = 'Python functions tutorial'
def function2():
print( string )
function2()
function1()
Output:
Python functions tutorial
Scope and Lifetime of Variables
The scope of a variable refers to the domain of a
program wherever it is declared. A function's
arguments and variables are not accessible
outside the defined function. As a result, they
only have a local domain.
The period of a variable's existence in RAM is
referred to as its lifetime. Variables within a
function have the same lifespan as the function
itself.
When we get out of the function, they are
removed. As a result, a function does not retain a
variable's value from earlier executions.
#defining a function to print a number.
def number( ):
num = 30
print( "Value of num inside the function: ", num)
num = 20
number()
print( "Value of num outside the function:", num)
Output:
Value of num inside the function: 30
Value of num outside the function: 20
Recursive functions:
Recursion is one of an important concept of
programming to solve problems.
It is a function that is called itself.
Example -
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
num = int(input("Enter a number: "))
print("The factorial of a {0} is: ".format(num), facto
rial(num))
Output:
Enter a number: 6 The factorial of a 6 is: 720
Example -
def fib(n) :
if n==0:
return 0
elif n ==1 :
return 1
else :
return fib(n-1) +fib(n-2)
num = int(input("Enter a number: "))
print("The {num} element of fibonacci series is: ".fo
rmat(num), fib(7))
Output:
Enter a number: 7
The 7 element of fibonacci series is: 13
Object Oriented Programming in Python
Classes and Objects:
Python Classes/Objects
Python is an object oriented programming
language.
Almost everything in Python is an object, with its
properties and methods.
A Class is like an object constructor, or a "blueprint"
for creating objects.
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property
named x:
class MyClass:
x=5
print(MyClass)
o/P
<class '__main__.MyClass'>
Create Object
we can use the class named MyClass to create
objects:
Example
Create an object named p1, and print the value of
x:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
o/P : 5
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, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
o/p
John
36
Note: The __init__() function is called
automatically every time the class is being used to
create a new object.
Object Methods
Objects can also contain methods. Methods in
objects are functions that belong to the object.
Let us create a method in the Person class:
Insert a function that prints a greeting, and execute
it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
O/P
Hello my name is John
The self Parameter
The self parameter is a reference to the current
instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it
whatever you like, but it has to be the first
parameter of any function in the class:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
O/P
Hello my name is John
Modify Object Properties
You can modify properties on objects like this:
Example
Set the age of p1 to 40:
p1.age = 40
Delete Object Properties
You can delete properties on objects by using
the del keyword:
Example
Delete the age property from the p1 object:
del p1.age
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
O/P
40
Constructors
Python facilitates a special type of method, also
called as Python Constructors, to initialize the
instance members of the class and to verify enough
object resources for executing any startup task.
Types of Constructors:
Parameterized Constructor
Non- Parameterized Constructor
Features of Python Constructors:
In Python, a Constructor begins with double
underscore (_) and is always named as __init__().
In python Constructors, arguments can also be
passed.
In Python, every class must necessarily have a
Constructor.
If there is a Python class without a Constructor, a
default Constructor is automatically created
without any arguments and parameters.
class Employees():
def __init__(self, Name, Salary):
self.Name = Name
self.Salary = Salary
def details(self):
print ("Employee Name : ", self.Name)
Print( "Employee Salary: ", self.Salary)
print ("\n“)
first = Employees("Khush", 10000)
second = Employees("Raam", 20000)
third = Employees("Lav", 10000)
fourth = Employees("Sita", 30000)
fifth = Employees("Lucky", 50000)
first.details()
second.details()
third.details()
fourth.details()
fifth.details()
Inheritance
Inheritance allows us to define a class that inherits
all the methods and properties from another class.
Parent class is the class being inherited from, also
called base class.
Child class is the class that inherits from another
class, also called derived class.
Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
O/P
John Doe
Create a Child Class
To create a class that inherits the functionality from
another class, send the parent class as a parameter
when creating the child class:
Example
Create a class named Student, which will inherit the
properties and methods from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want
to add any other properties or methods to the
class.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
O/P Mike Olsen
• Add the __init__() Function
• So far we have created a child class that
inherits the properties and methods from its
parent.
• We want to add the __init__() function to the
child class (instead of the pass keyword).
• Note: The __init__() function is called
automatically every time the class is being used
to create a new object.
•
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
x.printname()
Use the super() Function
Python also has a super() function that will make
the child class inherit all the methods and
properties from its parent:
By using the super() function, you do not have to
use the name of the parent element, it will
automatically inherit the methods and properties
from its parent.
Ex:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()
Ex:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname,
"to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
O/P
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-level inheritance is archived when a derived
class inherits another derived class. There is no
limit on the number of levels up to which, the
multi-level inheritance is archived in python.
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance
Python provides us the flexibility to inherit
multiple base classes in the child class.
class Base1:
<class-suite>
class Base2:
<class-suite>
. class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
• Method Overriding
• We can provide some specific implementation of
the parent class method in our child class. When
the parent class method is defined in the child
class with some specific implementation, then
the concept is called method overriding.
• We may need to perform method overriding in
the scenario where the different definition of a
parent class method is needed in the child class.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Output:
Barking
Polymorphism defines the ability to take different
forms. Polymorphism in Python allows us to define
methods in the child class with the same name as
defined in their parent class
• There are different methods to use
polymorphism in Python. You can use different
function, class methods or objects to define
polymorphism.
Polymorphism with Class Methods
class India():
def capital(self):
print("New Delhi")
def language(self):
print("Hindi and English")
class USA():
def capital(self):
print("Washington, “Newyork")
def language(self):
print("English")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
Output:
New Delhi
Hindi and English
Washington, Newyork
English
SIDDARTHA INSTITUTE OF SCIENCE AND
TECHNOLOGY: PUTTUR
(AUTONOMOUS)
II B.Tech. – I Sem.
split Returns a list where the string has been split at each match
print(arr)
• o/p: 1, 2, 3, 4, 5
Checking NumPy Version
• import numpy as np
print(np.__version__)
• Output:
• 1.16.3
NumPy Array Indexing
print(arr[0])
• Output:1
Access 2-D Arrays
• import numpy as np
• o/p:(array([3, 5, 6]),)
NumPy Sorting Arrays
• Sorting Arrays
• Sorting means putting elements in an ordered
sequence.
• Ordered sequence is any sequence that has an
order corresponding to elements, like numeric
or alphabetical, ascending or descending.
• The NumPy ndarray object has a function
called sort(), that will sort a specified array.
Sorting Arrays
print(np.sort(arr))
• Output:0,1,2,3
Pandas is a Python library.
Pandas is used to analyze data.
Pandas 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)
o/p: 0 1
17
2 2 dtype:
int64
Pandas DataFrames
df = pd.read_csv('data.csv')
print(df.head(10))
• Note:Head means first ten rows will collect
from the dataset
Output
Tail()
• import pandas as pd
df = pd.read_csv('data.csv')
print(df.Tail(10))
Note:Tail means last ten rows will collect from
the dataset
Output
Matplotlib Pyplot
• Most of the Matplotlib utilities lies under
the pyplot submodule, and are usually
imported under the plt alias:
plt.plot(xpoints, ypoints)
plt.show()
Output
Matplotlib Plotting
plt.plot(xpoints, ypoints)
plt.show()
Output
SIDDARTHA INSTITUTE OF SCIENCE AND
TECHNOLOGY: PUTTUR
(AUTONOMOUS)
II B.Tech. – I Sem.
for x in mytuple:
print(x)
• Output:Apple,banana,cherry
Generators
• Python Generators are the functions that return
the traversal object and used to create iterators. It
traverses the entire items at once. The generator
can also be an expression.
• we need to
implement __iter__() and __next__() method to
keep track of internal states.
def simple():
for i in range(10):
if(i%2==0):
yield i
#Successive Function call using for loop
for i in simple():
print(i)
Note: yield is similar to return stmt in function
Output
MAP’s
The python map() function is used to return a list of results
after applying a given function to each item of an iterable(list,
tuple etc.)
Syntax:
map(function, iterables)
Parameters
function- It is a function in which a map passes each item of
the iterable.
iterables- It is a sequence, collection or an iterator object
which is to be mapped.
Return
It returns a list of results after applying a given function to
each item of an iterable(list, tuple etc.)
def calculateAddition(n):
return n+n
numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)
# converting map object to set
numbersAddition = set(result)
print(numbersAddition)
numbers = (1, 2, 3, 4)
result = map(lambda x: x-x, numbers)
print(result)
# converting map object to set
numbersSubtract = set(result)
print(numbersSubtract)
O/P
Python filter() Function
Python filter() function is used to get filtered
elements. This function takes two arguments, first
is a function and the second is iterable. The filter
function returns a sequence from iterable for
which function returns True.
The first argument can be None if the function is
not available and returns only elements that are
True.
Syntax
filter (function, iterable)
Example 1
# Python filter() function example
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))
Output:6
Example 2
result1 = filter(None,(1,0,6))
# returns all non-zero values
result2 = filter(None,(1,0,False,True))
# returns all non-zero and True values
# Displaying result
result1 = list(result1)
result2 = list(result2)
print(result1)
print(result2)
O/P
[1, 6]
[1, True]
Files:Sometimes, it is not enough to only display
the data on the console.
The data to be displayed may be very large, and
only a limited amount of data can be displayed on
the console.
A file is a named location on disk to store related
information.
We can access the stored information (non-
volatile) after the program termination.
In Python, files are treated in two modes as text or
binary. The file may be in the text or binary format,
and each line of a file is ended with the special
character.
Hence, a file operation can be done in the following
order.
Open a file
Read or write - Performing operation
Close the file
• Syntax:
• file object = open(<file-name>, <access-
mode>, <buffering>)
fileptr = open(“D:\\file.txt","r")
if fileptr:
print("file is opened successfully")
O/P
<class '_io.TextIOWrapper'> file is opened
successfully
The close() method
Once all the operations are done on the file, we
must close it through our Python script using
the close() method.
Any unwritten information gets destroyed once
the close() method is called on a file object.
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()
Writing the file
• To write some text to a file, we need to open the
file using the open method with one of the
following access modes.
• w: It will overwrite the file if any file exists. The
file pointer is at the beginning of the file.
• a: It will append the existing file. The file pointer
is at the end of the file. It creates a new file if no
file exists.
Example 1
fileptr = open(“D:\file2.txt", "w")
# appending the content to the file
fileptr.write('''''Python is the modern day langua
ge. It makes things so simple.
It is the fastest-growing programing language''')
# closing the opened the file
fileptr.close()
O/P
File2.txt
Python is the modern-day language. It makes
things so simple. It is the fastest growing
programming language.
Reading Lines Using readlines() function
fileptr = open("file2.txt","r");
#stores all the data of the file into the
#variable content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Command Line Arguments
Python command line arguments provides a user-
friendly interface to your text-based command line
program.
Python exposes a mechanism to capture and
extract your Python command line arguments.
These values can be used to modify the behaviour
of a program.
For example, if your program processes data read
from a file, then you can pass the name of the file
to your program
Python allows for command line input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than
Python 2.7.
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.
• Python 3.6
• print("Enter your name:")
x = input()
print("Hello ", x)
Python 2.7
print("Enter your name:")
x = raw_input()
print("Hello ", x)
Save this file as demo_string_input.py, and load it
through the command line:
C:\Users\Your Name>python demo_string_input.py
Our program will prompt the user for a string:
Enter your name:
• The user now enters a name:
• Linus
Then, the program prints it to screen with a little
message:
Hello Linus
Python stops executing when it comes to the input()
function, and continues when the user has given
some input.
• The Python sys module provides access to any
command-line arguments via the sys.argv. This
serves two purposes −
• sys.argv is the list of command-line arguments.
• len(sys.argv) is the number of command-line
arguments.
• Here sys.argv[0] is the program ie. script name.
Example
Consider the following script test.py −
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv),
'arguments.'
print 'Argument List:', str(sys.argv)
Now run above script as follows −
$ python test.py arg1 arg2 arg3
• This produce following result −
• Number of arguments: 4 arguments.
• Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
• NOTE − As mentioned above, first argument is
always script name and it is also being counted in
number of arguments.
Date and Time
Python Dates
A date in Python is not a data type of its own, but
we can import a module named datetime to work
with dates as date objects.
Example 1
import datetime
x = datetime.datetime.now()
print(x)
Output:
2022-09-21 11:54:45.686028
Example 2
• Date Output
• When we execute the code from the example
above the result will be:
• 2022-09-21 11:54:06.435142
• The date contains year, month, day, hour,
minute, second, and microsecond.
• Creating Date Objects
• To create a date, we can use the datetime() class
(constructor) of the datetime module.
• The datetime() class requires three parameters to
create a date: year, month, day.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
O/P
2020-05-17 00:00:00
The strftime() Method
The datetime object has a method for formatting
date objects into readable strings.
Example
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
O/P
June
Example
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A")
O/P
2022
Wednesday
Python – Data Compression:
• In this tutorial, we will learn about the data
compression in Python programming language. In
python, the data can be archived, compressed
using the modules like zlib, gzip, bz2,lzma,zipfile
and tarfile.
• To use the respective module, you need to import
the module first. Let us look at below example.
Example 1
• import zlib >>> s = b'you learn learnt learning
the data daily '
• Output:len(s) 41
Example 2
• t = zlib.compress(s)
• len(t)
• Output : 39
Python Run Time Service
• The modules described in this chapter provide a
wide range of services related to the Python
interpreter and its interaction with its
environment. Here’s an overview:
• sys — System-specific parameters and functions
• sysconfig — Provide access to Python’s
configuration information
– Configuration variables
– Installation paths
– Other functions
– Using sysconfig as a script
Cont,
Data Management and Object Persistence
• During the course of using any software
application, user provides some data to be
processed. The data may be input, using a
standard input device (keyboard) or other devices
such as disk file, scanner, camera, network cable,
WiFi connection, etc.
• Data so received, is stored in computer’s main
memory (RAM) in the form of various data
structures such as, variables and objects until the
application is running. Thereafter, memory
contents from RAM are erased.
Data Peristence
The word ‘persistence’ means "the continuance of an
effect after its cause is removed".
The term data persistence means it continues to exist
even after the application has ended.
Thus, data stored in a non-volatile storage medium
such as, a disk file is a persistent data storage.
Using Python’s built-in File object, it is possible to write
string data to a disk file and read from it. Python’s
standard library, provides modules to store and
retrieve serialized data in various data structures such
as JSON(JSON stands for JavaScript Object Notation )
and XML.
• Python Data Persistence - File API
• Python uses built-in input() and print() functions to perform
standard input/output operations. The input() function reads
bytes from a standard input stream device, i.e. keyboard.
• The print() function on the other hand, sends the data towards
standard output stream device i.e. the display monitor. Python
program interacts with these IO devices through standard
stream objects stdin and stdout defined in sys module.
• The input() function is actually a wrapper around readline()
method of sys.stdin object. All keystrokes from the input
stream are received till ‘Enter’ key is pressed.
• >>> import sys
• >>> x=sys.stdin.readline()
• Welcome to cse dept>>>
• X
• Output :'Welcome to cse dept'
• Python Data Persistence - dbm Package
• The dbm package presents a dictionary like interface
DBM style databases. DBM stands for DataBase
Manager. This is used by UNIX (and UNIX like)
operating system. The dbbm library is a simple
database engine written by Ken Thompson. These
databases use binary encoded string objects as key,
as well as value.
• The database stores data by use of a single key (a
primary key) in fixed-size buckets and uses hashing
techniques to enable fast retrieval of the data by
key.
• The dbm package contains following modules −
• dbm.gnu(generally used database
manager) module is an interface to the DBM
library version as implemented by the GNU
project.
• dbm.ndbm(new database manageer) module
provides an interface to UNIX nbdm
implementation.
• dbm.dumb(data base manager for unix) is used
as a fallback option in the event,when other
dbm implementations are not found. This
requires no external dependencies but is slower
than others.
GUI PROGRAMMING
• Python provides various options for developing
graphical user interfaces (GUIs). Most important
are listed below.
• Tkinter − Tkinter is the Python interface to the
Tk GUI toolkit shipped with Python. We would
look this option in this chapter.
• wxPython − This is an open-source Python
interface for wxWindows http://wxpython.org.
• JPython − JPython is a Python port for Java
which gives Python scripts access to Java class
libraries on the local
machine http://www.jython.org
Turtle is a special feathers of Python. Using Turtle,
we can easily draw in a drawing board.
First we import the turtle module.
Then create a window,
next we create turtle object
and using turtle method we can draw in the
drawing board.
METHOD PARAMETER DESCRIPTION
Turtle() None It creates and returns a new turtle object
forward() amount It moves the turtle forward by the specified amount
backward() amount It moves the turtle backward by the specified amount
right() angle It turns the turtle clockwise
left() angle It turns the turtle counter clockwise
penup() None It picks up the turtle’s Pen
pendown() None Puts down the turtle’s Pen
up() None Picks up the turtle’s Pen
down() None Puts down the turtle’s Pen
color() Color name Changes the color of the turtle’s pen
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
heading() None It returns the current heading
position() None It returns the current position
goto() x, y It moves the turtle to position x,y
begin_fill() None Remember the starting point for a filled polygon
end_fill()
• Turtle is a Python library which used to create
graphics, pictures, and games. It was developed
by Wally Feurzeig, Seymour
Parpet and Cynthina Slolomon in 1967. It was a
part of the original Logo programming language.
• Turtle is a pre-installed library in Python that is
similar to the virtual canvas that we can draw
pictures and attractive shapes. It provides the
onscreen pen that we can use for drawing.
•
• Before working with the turtle library, we must
ensure the two most essential things to do
programming.
• Python Environment - We must be familiar with
the working Python environment. We can use
applications such as IDLE or Jupiter Notebook. We
can also use the Python interactive shell.
• Python Version - We must have Python 3 in our
system; if not, then download it from Python's
official website.
•
• import turtle
• Now, we can access all methods and functions.
First, we need to create a dedicated window
where we carry out each drawing command.
We can do it by initializing a variable for it.
• s = turtle.getscreen()
•
• import turtle
• # Creating turtle screen
• s = turtle.getscreen()
• # To stop the screen to display
• turtle.mainloop()
• Programming with turtle
• First, we need to learn to move the turtle all
direction as we want. We can customize the
pen like turtle and its environment. Let's learn
the couple of commands to perform a few
specific tasks.
• Turtle can be moved in four directions.
• Forward
• Backward
• Left
• Right
• Turtle motion
• The turtle can move forward and backward in
direction that it's facing. Let's see the following
functions.
• forward(distance) or turtle.fd(distance) - It
moves the turtle in the forward direction by a
certain distance. It takes one
parameter distance, which can be an integer or
float.
•
• import turtle
• # Creating turtle screen
• t = turtle.Turtle()
• # To stop the screen to display
• t.forward(100)
• turtle.mainloop()
•
Example - 2:
import turtle
# Creating turtle screen
t = turtle.Turtle()
# Move turtle in opposite direction
t.backward(100)
# To stop the screen to display
turtle.mainloop()
import turtle
# Creating turtle screen
t = turtle.Turtle()
t.heading()
# Move turtle in opposite direction
t.right(25)
t.heading()
# To stop the screen to display
turtle.mainloop()
import turtle
# Creating turtle screen
t = turtle.Turtle()
t.heading()
# Move turtle in left
t.left(100)
t.heading()
# To stop the screen to display
turtle.mainloop()
• Drawing a Shape
• We discussed the movement of the turtle. Now, we
learn to move on to making actual shape. First, we
draw the polygon since they all consist of straight lines
connected at the certain angles. Let's understand the
following example.
• Example -
• t.fd(100)
• t.rt(90)
• t.fd(100)
• t.rt(90)
• t.fd(100)
• t.rt(90)
• t.fd(100)
• import turtle
• # Creating turtle screen
• t = turtle.Turtle()
• t.circle(50)
• turtle.mainloop()