Python
Python
Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming
approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting and rapid application
development.
Python supports multiple programming pattern, including object-oriented, imperative, and functional or procedural programming
styles.
Python is not intended to work in a particular area, such as web programming. That is why it is known as multipurpose programming
language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value
in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in Python development, and edit-
test-debug cycle is very fast.
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known as an identifier and used to hold
value.
In Python, we don't need to specify the type of variable because Python is a infer language and smart enough to get
variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to name
an identifier are given below.
The first character of the variable must be an alphabet or underscore ( _ ).
All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit
(0-9).
Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
Identifier name must not be similar to any keyword defined in the language.
Identifier names are case sensitive; for example, my name, and MyName is not the same.
Examples of valid identifiers: a123, _n, n_9, etc.
Examples of invalid identifiers: 1a, n%4, n 9, etc.
The Python object creates an integer object and displays it to the console. In the above print statement, we have created a string object. Let's check the
type of it using the Python built-in type() function.
type(“Vinod")
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are used to denote objects by that name.
a = 50
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the digit
(0-9), and underscore character(_). Consider the following example of valid variables names.
name = “Vinod"
age = 20
marks = 80.50
print(name)
print(age)
print(marks)
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also known as multiple
assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or assigning
multiple values to multiple variables.
x=y=z=50
print(x)
print(y)
print(z)
a,b,c=5,10,15
print a
print b
print c
Python Variable Types
There are two types of variables in Python - Local variable and Global variable
Local Variable
Local variables are the variables that declared inside
the function and have scope within the function.
Global Variables
Global variables can be used throughout the program,
and its scope is in the entire program. We can use global
variables inside or outside the function.
A variable declared outside the function is the global
variable by default. Python provides the global keyword to
use global variable inside the function. If we don't use the
global keyword, the function treats it as a local variable.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
t
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.
Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below.
Numbers
Sequence Type
Boolean
Set
Dictionary
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.
a=5
print("The type of a", type(a)) #int
b = 40.5
print("The type of b", type(b)) #float
c = 1+3j
print("The type of c", type(c)) #complex
print(" c is a complex number", isinstance(1+3j,complex))
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can use
single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and operators to perform
operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in the list are separated
with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*) works with
the list in the same way as they were working with the strings.
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
d = {1:’vinod', 2:’aashu', 3:’kush', 4:’pooja'}
# Printing dictionary
print (d)
print ([Link]())
print ([Link]())
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine the
given statement true or false. It denotes by the class bool. True can be represented by any non-zero
value or 'T' whereas false can be represented by the 0 or 'F'.
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and has unique elements.
In set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a
built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various
types of values.
# Creating Empty set
set1 = set()
[Link](10)
print(set2)
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.
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Statement Description
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.
The syntax of the if-statement is given below.
if expression:
statement
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
if condition:
#block of statements
else:
#another block of statements (else-block)
Python Loops
The flow of the programs written in any programming language is sequential by default. Sometimes we may need to alter the flow of the program. The
execution of a specific code may need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are capable of repeating some specific code several numbers of times.
Consider the following diagram to understand the working of a loop statement.
Advantages of loops
There are the following advantages of loops in Python.
It provides code re-usability.
Using loops, we do not need to write the same code again and again.
Using loops, we can traverse over the elements of data structures (array or linked lists).
Python for loop
The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary.
for iterating_var in sequence:
statement(s)
str = "Python"
for i in str:
print(i)
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
Syntax:
range(start,stop,step size)
for i in range(10):
print(i,end = ' ')
for i in range(2,n,2):
print(i)
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times for every iteration
of the outer loop.
Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
Python While loop
The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations then the while loop is most effective to use.
while expression:
statements
i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1
#loop statements
break;
str = "python"
for i in str:
if i == 'o':
break
print(i);
Python continue Statement
The continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the
loop and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular [Link]
continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the loop
and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular condition.
Syntax
#loop statements
continue
#the code to be skipped
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is used in the cases where a
statement is syntactically needed but we don't want to use any executable statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't want to give its specific
implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the program file.
i=0
while(i < 10):
i = i+1
if(i == 5):
pass
print(i)
print(i)
Python Function
Functions are the most important aspect of an application. A function can be defined as the organized block of reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the Python program.
The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the
program grows, function makes the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions, which can be called user-defined functions.
User-define functions - The user-defined functions are those define by the user to perform the specific task.
Built-in functions - The built-in functions are those functions that are pre-defined in Python.
Using functions, we can avoid rewriting the same logic/code again and again in a program.
We can call Python functions multiple times in a program and anywhere in a program.
We can track a large Python program easily when it is divided into multiple functions.
Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is given below.
Syntax:
def my_function(parameters):
function_block
return expression
The def keyword, along with the function name is used to define the function.
The identifier rule must follow the function name.
A function accepts the parameter (argument), and they can be optional.
The function block is started with the colon (:), and block statements must be at the same indentation.
The return statement is used to return the value. A function can have only one return
Function Calling
In Python, after the function is created, we can call it from another function. A function must be defined before the function call;
otherwise, the Python interpreter gives an error. To call the function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello World".
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
def sum (a,b):
return a+b;
Arguments in function
The arguments are types of information which can be passed into the function. The arguments are specified in the parentheses. We
can pass any number of arguments, but they must be separate them with a comma.
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func(“aashu")
Types of arguments
There may be several types of arguments which can be passed at the time of function call.
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required Arguments
Till now, we have learned about function calling in Python. However, we can provide the arguments at the time of the function call. As far as the required
arguments are concerned, these are the arguments which are required to be passed at the time of function calling with the exact match of their positions in
the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, the
Python interpreter will show the error.
def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not provided at the time of function call, then
that argument can be initialized with the value given in the definition even if the argument is not specified at the function call.
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
Variable-length Arguments (*args)
In large projects, sometimes we may not know the number of arguments to be passed in advance. In such cases, Python provides us the flexibility to offer
the comma-separated values which are internally treated as tuples at the function call. By using the variable-length arguments, we can pass any number of
arguments.
However, at the function definition, we define the variable-length argument using the *args (star) as *<variable - name >.
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")
Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling and definition. If the same match is found, the values of the
arguments are copied in the function definition.
#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)
#name and message is copied with the values John and hello respectively
func(name = "John",message="hello")
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the program may not be accessible to the
other parts.
In python, the variables are defined with the two types of scopes.
Global variables
Local variables
The variable defined outside any function is known to have a global scope, whereas the variable defined inside a function is known to have a local scope.
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the function itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output:
Python Built-in Functions
The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The python interpreter has
several functions that are always present for use. These functions are known as Built-in Functions. There are several built-in
functions in Python which are listed below:
Python abs() Function
The python abs() function is used to return the absolute value of a number. It takes only one argument, a number whose absolute
value is to be returned. The argument can be an integer and floating-point number. If the argument is a complex number, then, abs()
returns its magnitude.
Python abs() Function Example
# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))
# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))
Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))
Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version of the bytearray() function.
It can create empty bytes object of the specified size.
string = "Hello World."
array = bytes(string, 'utf-8')
print(array)
Python callable() Function
A python callable() function in Python is something that can be called. This built-in function checks and returns true if the object passed appears to be callable, otherwise false.
x=8
print(callable(x))
The python any() function returns true if any item in an iterable is true. Otherwise, it returns False.
l = [4, 3, 2, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
The python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U
escapes.
normalText = 'Python is interesting'
print(ascii(normalText))
print('Pyth\xf6n is interesting')
Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.
string = "Python is a programming language."
Python float()
The python float() function returns a floating-point number from a number or string.
# for integers
print(float(9))
# for floats
print(float(8.19))
Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')
fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())
globals()['age'] = 22
print('The age is:', age)
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
listIter = iter(list)
# prints '1'
print(next(listIter))
# prints '2'
print(next(listIter))
# prints '3'
print(next(listIter))
# prints '4'
print(next(listIter))
# prints '5'
print(next(listIter))
# string
String = 'abcde'
print(list(String))
# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))
def localsPresent():
present = True
return locals()
print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())
numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)
mv = memoryview(randomByteArray)
print(type(python))
print(dir(python))
Python complex()
Python complex() function is used to convert numbers or string into a complex number. This method takes two optional parameters and returns a complex number. The
first parameter is called a real and second as imaginary parts.
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)
Python delattr() function is used to delete an attribute from a class. It takes two parameters, first is an object of the class and second is an attribute which we want to
delete. After deleting the attribute, it no longer available in the class and throws an error if try to call it using the class object.
class Student:
id = 101
name = “vinod"
email = “vinod@[Link]"
# Declaring function
def getinfo(self):
print([Link], [Link], [Link])
s = Student()
[Link]()
delattr(Student,'course') # Removing attribute which is not available
[Link]() # error: throws an error
Python dir() Function
Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be
called and must return the list of attributes. It takes a single object type argument.
# Calling function
att = dir()
# Displaying result
print(att)
Python divmod() function is used to get remainder and quotient of two numbers. This function takes two numeric arguments and returns a tuple. Both arguments are
required and numeric
# Python divmod() function example
# Calling function
result = divmod(10,2)
# Displaying result
print(result)
Python enumerate() function returns an enumerated object. It takes two parameters, first is a sequence of elements and the second is the start index of the sequence.
We can get the elements in sequence either through a loop or next() method.
# Calling function
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))
Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary provides three different constructors to create a dictionary:
If no argument is passed, it creates an empty dictionary.
If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)
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 of those elements of iterable object for which function returns true value.
The first argument can be none, if the function is not available and returns only elements that are true.
# 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))
Python hash() Function
Python hash() function is used to get the hash value of an object. Python calculates the hash value by using the hash algorithm. The hash values are integers and used to compare
dictionary keys during a dictionary lookup. We can hash only the types which are given below:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.
# Calling function
result = hash(21) # integer value
result2 = hash(22.2) # decimal value
# Displaying result
print(result)
print(result2)
In python, a set is a built-in class, and this function is a constructor of this class. It is used to create a new set using elements passed during the call. It takes aniterable object as an argument and returns a new set object.
# Calling function
result2 = set('12')
result3 = set(‘waytocode')
# Displaying result
print(result)
print(result2)
print(result3)
Python hex() function is used to generate hex value of an integer argument. It takes an integer argument and returns an integer converted into a hexadecimal string. In case, we want to get a hexadecimal value of a float, then use
[Link]() function.
# Calling function
result = hex(1)
# integer value
result2 = hex(342)
# Displaying result
print(result)
print(result2)
Python id() function returns the identity of an object. This is an integer which is guaranteed to be unique. This function takes an argument as an object and returns a unique integer number which represents identity. Two objects with
non-overlapping lifetimes may have the same id() value.
# Calling function
# Displaying result
print(val)
print(val2)
print(val3)
Python setattr() Function
Python setattr() function is used to set a value to the object's attribute. It takes three arguments, i.e., an object, a string, and an arbitrary value, and returns none. It is
helpful when we want to add a new attribute to an object and set a value to it.
class Student:
id = 0
name = ""
student = Student(102,“vinod")
print([Link])
print([Link])
#print([Link]) product error
setattr(student, 'email’,’vinod@[Link]') # adding new attribute
print([Link])
Python slice() function is used to get a slice of elements from the collection of elements. Python provides two overloaded slice functions. The first function takes a single argument while the second function
takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection.
# Calling function
# Displaying result
print(result)
print(result2)
Python next() function is used to fetch next item from the collection. It takes two arguments, i.e., an iterator and a default value, and returns an element.
This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
Python input() function is used to get an 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 it. It throws an errorEOFError if EOF is read.
# Displaying result
print("You entered:",val)
Python int() Function
Python int() function is used to get an integer value. It returns an expression converted into an integer number. If the argument is a floating-point, the conversion
truncates the number. If the argument is outside the integer range, then it converts the number into a long type.
If the number is not a number or if a base is given, the number must be a string.
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)
student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))
# negative x, positive y
print(pow(-4, 2))
# negative x, negative y
print(pow(-4, -2))
Python print() Function
The python print() function prints the given object to the screen or other standard output devices.
print("Python is programming language.")
x=7
# Two objects passed
print("x =", x)
y=x
# Three objects passed
print('x =', x, '= y')
The python range() function returns an immutable sequence of numbers starting from 0 by default, increments by 1 (by default) and ends at a specified number.
# empty range
print(list(range(0)))
# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))
# for range
Range = range(8, 12)
print(list(reversed(Range)))
# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
# even choice
print(round(6.6))
Python issubclass() Function
The python issubclass() function returns true if object argument(first argument) is a subclass of second class(second argument).
class Rectangle:
def __init__(rectangleType):
print('Rectangle is a ', rectangleType)
class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')
print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))
Python str
Python type()
The python type() returns the type of the specified object if a single argument is passed to the type() built in function. If three arguments are passed, then it returns a
new type object.
List = [4, 5]
print(type(List))
Dict = {4: 'four', 5: 'five'}
print(type(Dict))
class Python:
a=0
InstanceOfPython = Python()
print(type(InstanceOfPython))
Python vars() function
The python vars() function returns the __dict__ attribute of the given object.
class Python:
def __init__(self, x = 7, y = 9):
self.x = x
self.y = y
InstanceOfPython = Python()
print(vars(InstanceOfPython))
In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument and a+10 is an expression. The given expression gets evaluated and returned the result. The above lambda
function is same as the normal function.
def x(a):
return a+10
print(sum = x(10))
Example:
import file;
name = input("Enter the name?")
[Link](name)
Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.
[Link]:
#place the code in the [Link]
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
[Link]:
from calculation import summation
#it will import only the summation() from [Link]
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()
Python File Handling
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 since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We
can access the stored information (non-volatile) after the program termination.
The file-handling implementation is slightly lengthy or complicated in the other programming language, but it is easier and shorter in Python.
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
Opening a file
Python provides an open() function that accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be
used to perform various operations like reading, writing, etc.
Syntax:
The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open a file.
Example
if fileptr:
print("file is opened successfully")
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.
We can perform any operation on the file externally using the file system which is the currently opened in Python; hence it is good practice to close the file once all the
operations are done.
The syntax to use the close() method is given below.
Syntax
[Link]()
if fileptr:
print("file is opened successfully")
Example 2
#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r")
#stores all the data of the file into the variable content
content = [Link](10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
[Link]()
Python facilitates to read the file line by line by using a function readline() method. The readline() method reads the lines of the file from the beginning, i.e., if we use
the readline() method two times, then we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of our file "[Link]" containing three lines.
Reading lines using readline() function
#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r");
#stores all the data of the file into the variable content
content = [Link]()
content1 = [Link]()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
[Link]()
#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r");
#stores all the data of the file into the variable content
content = [Link]()
#prints the content of the file
print(content)
#closes the opened file
[Link]()
Creating a new file
The new file can be created by using one of the following access modes with the function open().
x: it creates a new file with the specified name. It causes an error a file exists with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.
#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","x")
print(fileptr)
if fileptr:
print("File created successfully")
Python OS module
Renaming the file
The Python os module enables interaction with the operating system. The os module provides the functions that are involved in file processing operations like renaming,
deleting, etc. It provides us the rename() method to rename the specified file to a new name.
import os
Python Exception
An exception can be defined as an unusual condition in a program resulting in the interruption in the
flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is not
executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An
exception is a Python object that represents an error
Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code that exists
after the exception.
Python has many built-in exceptions that enable our program to run without interruption and give
the output. These exceptions are given below:
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common standard
exceptions. A list of common exceptions that can be thrown from a standard Python program is given
below.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
The problem without handling exceptions
As we have already discussed, the exception is an abnormal condition that halts the execution of the program.
Suppose we have two variables a and b, which take the input from the user and perform the division of these values. What if the user entered the zero as
the denominator? It will interrupt the program execution and through a ZeroDivision exception.
Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "[Link]", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
The above program is syntactically correct, but it through the error because of unusual input. That kind of programming may not be suitable or
recommended for the projects because these projects are required uninterrupted execution. That's why an exception-handling plays an essential role in
handling these unexpected exceptions.
If the Python program contains suspicious code that may throw the exception, we must place that code in the try block. The try block must be followed with
the except statement, which contains a block of code that will be executed if there is some exception in the try block.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Example 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
We can also use the else statement with the try-except statement in which, we can place the code which will be executed in the scenario if no exception
occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example 2
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
else:
#block of code
Example
try:
fileptr = open("[Link]","r")
try:
[Link]("Hi I am good")
finally:
[Link]()
print("file closed")
except:
print("Error")
Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful in in that scenario where we need to raise an exception to stop the execution of the program.
For example, there is a program that requires 2GB memory for execution, and if the program tries to occupy 2GB of memory, then we can raise an exception to stop the execution of the
program.
Syntax
raise Exception_class,<value>
Points to remember
To raise an exception, the raise statement is used. The exception class name follows it.
An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the exception.
We can pass the value to an exception to specify the exception type.
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)
Custom Exception
The Python allows us to create our exceptions that can be raised from the program and caught using the except clause. However, we suggest you read this
section after visiting the Python object and classes.
class ErrorInCode(Exception):
def __init__(self, data):
[Link] = data
def __str__(self):
return repr([Link])
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", [Link])
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.
Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns
the total number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the
time.
import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print([Link]())
Output:
1585928913.6519969
import time;
#returns a time tuple
print([Link]([Link]()))
Output:
import time
#returns the formatted time
print([Link]([Link]([Link]())))
To work with dates as date objects, we have to import the datetime module into the python source code.
import datetime
#returns the current datetime object
print([Link]())
2020-04-04 00:00:00
We can also specify the time along with the date to create the datetime object. Consider the following example.
import datetime
#returns the datetime object for the specified time
print([Link](2020,4,4,1,26,40))
Output:
2020-04-04 01:26:40
Regex Functions
1 match This method matches the regex pattern in the string with the optional flag. It returns true if a match is found in the
string otherwise it returns false.
2 search This method returns the match object if there is a match found in the string.
3 findall It returns a list that contains all the matches of a pattern in the string.
4 split Returns a list in which the string has been split in each match.
5 sub Replace one or many matches in the string.
Forming a regular expression
A regular expression can be formed by using the mix of meta-characters, special sequences, and sets.
Meta-Characters
Metacharacter is a character with the specified meaning.
Metacharacter Description Example
[] It represents the set of characters. "[a-z]"
\ It represents the special sequence. "\r"
. It signals that any character is present at some specific place. "Ja.v."
^ It represents the pattern present at the beginning of the string. "^Java"
$ It represents the pattern present at the end of the string. "point"
* It represents zero or more occurrences of a pattern in the string. "hello*"
+ It represents one or more occurrences of a pattern in the string. "hello+"
{} The specified number of occurrences of a pattern the string. "java{2}"
| It represents either this or that character is present. “way|code"
() Capture and group
Special Sequences
Special sequences are the sequences containing \ followed by one of the characters.
Character Description
\A It returns a match if the specified characters are present at the beginning of the string.
\b It returns a match if the specified characters are present at the beginning or the end of the string.
\B It returns a match if the specified characters are present at the beginning of the string but not at the end.
\d It returns a match if the string contains digits [0-9].
\D It returns a match if the string doesn't contain the digits [0-9].
\s It returns a match if the string contains any white space character.
\S It returns a match if the string doesn't contain any white space character.
\w It returns a match if the string contains any word characters.
\W It returns a match if the string doesn't contain any word.
\Z Returns a match if the specified characters are at the end of the string.
Sets
A set is a group of characters given inside a pair of square brackets. It represents the special meaning.
SN Set Description
1 [arn] Returns a match if the string contains any of the specified characters in the set.
2 [a-n] Returns a match if the string contains any of the characters between a to n.
3 [^arn] Returns a match if the string contains the characters except a, r, and n.
4 [0123] Returns a match if the string contains any of the specified digits.
5 [0-9] Returns a match if the string contains any digit between 0 and 9.
6 [0-5][0-9] Returns a match if the string contains any digit between 00 and 59.
10 [a-zA-Z] Returns a match if the string contains any alphabet (lower-case or upper-case).
import re
str = "How are you. How is everything"
matches = [Link]("How", str)
print(matches)
print(matches)
import re
span(): It returns the tuple containing the starting and end position of the match.
string(): It returns a string passed into the function.
group(): The part of the string is returned where the match is found.
import re
Signature
The list comprehension starts with '[' and ']'.
[ expression for item in list if conditional ]
letters = []
for letter in 'Python':
[Link](letter)
print(letters)
Array is an idea of storing multiple items of the same type together and it makes easier to calculate the position of each element by simply adding an
offset to the base value. A combination of the arrays could save a lot of time by reducing the overall size of the code. It is used to store multiple values in
single variable. If you have a list of items that are stored in their corresponding variables like this:
car1 = “aashu"
car2 = “vinod"
car3 = “jack"
If you want to loop through cars and find a specific one, you can use the array.
The array can be handled in Python by a module named array. It is useful when we have to manipulate only specific data values. Following are the
terms to understand the concept of an array:
Array Representation
An array can be declared in various ways and different languages. The important points that should be considered are as follows:
The Array can be created in Python by importing the array module to the python program.
from array import *
arrayName = array(typecode, [initializers])
Accessing array elements
We can access the array elements using the respective indices of those elements.
Array Concatenation
We can easily concatenate any two arrays using the + symbol.
a=[Link]('d',[1.1 , 2.1 ,3.1,2.6,7.8])
b=[Link]('d',[3.7,8.6])
c=[Link]('d')
c=a+b
print("Array c = ",c)
Python Stack and Queue
Data structure organizes the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. A simple Python
list can act as a queue and stack as well. A queue follows FIFO rule (First In First Out) and used in programming for sorting. It is common for stacks and queues to be implemented with an array
or linked list.
Stack
A Stack is a data structure that follows the LIFO(Last In First Out) principle. To implement a stack, we need two simple operations:
push - It adds an element to the top of the stack.
pop - It removes an element from the top of the stack.
Operations:
Adding - It adds the items in the stack and increases the stack size. The addition takes place at the top of the stack.
Deletion - It consists of two conditions, first, if no element is present in the stack, then underflow occurs in the stack, and second, if a stack contains some elements, then the topmost element
gets removed. It reduces the stack size.
Traversing - It involves visiting each element of the stack.
Characteristics:
Insertion order of the stack is preserved.
Useful for parsing the operations.
Duplicacy is allowed.
Queue
A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back
and can remove elements from the front.
To implement a queue, we need two simple operations:
enqueue - It adds an element to the end of the queue.
dequeue - It removes the element from the beginning of the queue.
Operations on Queue
Addition - It adds the element in a queue and takes place at the rear end, i.e., at the back of the queue.
Deletion - It consists of two conditions - If no element is present in the queue, Underflow occurs in the queue, or if a stack contains
some elements then element present at the front gets deleted.
Traversing - It involves to visit each element of the queue.
Characteristics
Insertion order of the queue is preserved.
Duplicacy is allowed.
Useful for parsing CPU task operations.
# Initializing a queue
queue = []
print("Initial queue")
print(queue)
# Uncommenting print([Link](0))
# will raise and IndexError
Python JSON
JSON stands for JavaScript Object Notation, which is a widely used data format for data interchange on the web. JSON is the ideal
format for organizing data between a client and a server. Its syntax is similar to the JavaScript programming language. The main
objective of JSON is to transmit the data between the client and the web server. It is easy to learn and the most effective way to
interchange the data. It can be used with various programming languages such as Python, Perl, Java, etc.
JSON mainly supports 6 types of data type In JavaScript:
String
Number
Boolean
Null
Object
Array
JSON is built on the two structures:
It stores data in the name/value pairs. It is treated as an object, record, dictionary, hash table, keyed list.
The ordered list of values is treated as an array, vector, list, or sequence.
JSON data representation is similar to the Python dictionary. Below is an example of JSON data:
{
"book": [
{
"id": 01,
"language": "English",
"edition": "Second",
"author": "Derrick Mwiti"
],
{
{
"id": 02,
"language": "French",
"edition": "Third",
"author": "Vladimir"
}
}
load()
loads()
dump()
dumps()
Serializing JSON
Serialization is the technique to convert the Python objects to JSON. Sometimes, computer need to process lots of information so it is good to store that
information into the file. We can store JSON data into file using JSON function. The json module provides the dump() and dumps() method that are
used to transform Python object.
thon objects are converted into the following JSON objects. The list is given below:
Python provides a dump() function to transmit(encode) data in JSON format. It accepts two positional arguments, first
is the data object to be serialized and second is the file-like object to which the bytes needs to be written.
Import json
# Key:value mapping
student = {
"Name" : "Peter",
"Roll_no" : "0090014",
"Grade" : "A",
"Age": 20,
"Subject": ["Computer Graphics", "Discrete Mathematics", "Data Structure"]
}
In the above program, we have opened a file named [Link] in writing mode. We opened this file in write mode
because if the file doesn't exist, it will be created. The [Link]() method transforms dictionary into JSON string.
The dumps () function
The dumps() function is used to store serialized data in the Python file. It accepts only one argument that is Python
data for serialization. The file-like argument is not used because we aren't not writing data to disk. Let's consider the
following example:
import json
# Key:value mapping
student = {
"Name" : "Peter",
"Roll_no" : "0090014",
"Grade" : "A",
"Age": 20
}
b = [Link](student)
print(b)
JSON supports primitive data types, such as strings and numbers, as well as nested list, tuples and objects.
import json
Let's take real-life example, one person translates something into Chinese and another person translates back into English, and that may not be exactly
translated. Consider the simple example:
import json
a = (10,20,30,40,50,60,70)
print(type(a))
b = [Link](a)
print(type([Link](b)))
In the above program, we have encoded Python object in the file using dump() function. After that we read JSON file
using load() function, where we have passed read_file as an argument.
The json module also provides loads() function, which is used to convert JSON data to Python object. It is quite similar to
the load() function. Consider the following example:
Import json
a = ["Mathew","Peter",(10,32.9,80),{"Name" : "Tokyo"}]
[Link]() vs [Link]()
The [Link]() function is used to load JSON file, whereas [Link]() function is used to load string.
[Link]() vs [Link]()
The [Link]() function is used when we want to serialize the Python objects into JSON file and [Link]() function is used to
convert JSON data as a string for parsing and printing.
It is defined as a construct that allows you to create, store, and re-use various formatting parameters. It supports several attributes; the most frequently used are:
[Link]: This attribute is used as the separating character between the fields. The default value is a comma (,).
[Link]: This attribute is used to quote fields that contain special characters.
[Link]: It is used to create new lines, and the default value is '\r\n'.
Let's write the following data to a CSV File.
data = [{'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'},
{'Rank': 'A', 'first_name': 'Smith', 'last_name': 'Rodriguez'},
{'Rank': 'C', 'first_name': 'Tom', 'last_name': 'smith'},
{'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'},
{'Rank': 'A', 'first_name': 'Alex', 'last_name': 'Tim'}]
import csv
[Link]()
[Link]({'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'})
[Link]({'Rank': 'A', 'first_name': 'Smith',
'last_name': 'Rodriguez'})
[Link]({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'})
[Link]({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Loive'})
print("Writing complete")
Python read excel file
Excel is a spreadsheet application which is developed by Microsoft. It is an easily accessible tool to organize, analyze, and store the
data in tables. It is widely used in many different applications all over the world. From Analysts to CEOs, various professionals use
Excel for both quick stats and serious data crunching.
Excel Documents
An Excel spreadsheet document is called a workbook which is saved in a file with .xlsx extension. The first row of the spreadsheet is
mainly reserved for the header, while the first column identifies the sampling unit. Each workbook can contain multiple sheets that are
also called a worksheets. A box at a particular column and row is called a cell, and each cell can include a number or text value. The
grid of cells with data forms a sheet.
Creating a Workbook
A workbook contains all the data in the excel file. You can create a new workbook from scratch, or you can easily create a workbook
from the excel file that already exists.
# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
for i in range([Link]):
print(sheet.cell_value(0, i))
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
for i in range([Link]):
print(sheet.cell_value(i, 0))
Code #6: Extract a particular row value
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
print(sheet.row_values(1))
Python Write Excel File
The Python write excel file is used to perform the multiple operations on a spreadsheet using the xlwt module. It is an ideal way to write data and format
information to files with .xls extension.
If you want to write data to any file and don't want to go through the trouble of doing everything by yourself, then you can use a for loop to automate the
whole process a little bit.
Write Excel File Using xlsxwriter Module
We can also write the excel file using the xlsxwriter module. It is defined as a Python module for writing the files in the XLSX file format. It can also be
used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as charts, formatting, images, page setup, auto filters,
conditional formatting, and many others.
We need to use the following command to install xlsxwriter module:
Write Excel File Using openpyxl Module
It is defined as a package which is generally recommended if you want to read and write .xlsx, xlsm, xltx, and xltm files. You can check it by
running type(wb).
The load_workbook() function takes an argument and returns a workbook object, which represents the file. Make sure that you are in the same directory
where your spreadsheet is located. Otherwise, you will get an error while importing.
You can easily use a for loop with the help of the range() function to help you to print out the values of the rows that have values in column 2. If those
particular cells are empty, you will get None.
Writing data to Excel files with xlwt
You can use the xlwt package, apart from the XlsxWriter package to create the spreadsheets that contain your data. It is an alternative package for
writing data, formatting information, etc. and ideal for writing the data and format information to files with .xls extension. It can perform multiple
operations on the spreadsheet.
It supports features such as formatting, images, charts, page setup, auto filters, conditional formatting, and many others.
Pandas have excellent methods for reading all kinds of data from excel files. We can also import the results back to pandas.
Writing Files with pyexcel
You can easily export your arrays back to a spreadsheet by using the save_as() function and pass the array and name of the destination file to the
dest_file_name argument.
It allows us to specify the delimiter and add dest_delimiter argument. You can pass the symbol that you want to use as a delimiter in-between " ".
book = [Link]('[Link]')
sheet = book.add_sheet()
namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position in the tuple. It was used to eliminate the problem of remembering the index of each field of a tuple object
in ordinary tuples.
import collections
d1=[Link]()
d1['A']=10
d1['C']=12
d1['B']=11
d1['D']=13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-in dict class. It provides all methods provided by dictionary but takes the first argument as a default data
type.
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable objects.
deque()
The Python deque() is a double-ended queue which allows us to add and remove elements from both the ends.
Chainmap Objects
A chainmap class is used to groups multiple dictionary together to create a single list. The linked dictionary stores in the list and it is public and can be accessed by the map attribute. Consider the following example.
data - A real dictionary used to store the contents of the UserDict class.
UserList Objects
The UserList behaves as a wrapper class around the list-objects. It is useful when we want to add new functionality to the lists. It provides the
easiness to work with the dictionary.
data - A real list is used to store the contents of the User class.
UserString Objects
The UserList behaves as a wrapper class around the list objects. The dictionary can be accessed as an attribute by using the UserString
object. It provides the easiness to work with the dictionary.
data - A real str object is used to store the contents of the UserString class.
An object-oriented paradigm is to design the program using classes and objects. The object is related to real-word entities such as book,
house, pencil, etc. The oops concept focuses on writing the reusable code. It is a widespread technique to solve the problem by creating
objects.
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you
have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring
defined in the function source code.
class car:
def __init__(self,modelname, year):
[Link] = modelname
[Link] = year
def display(self):
print([Link],[Link])
c1 = car("Toyota", 2016)
[Link]()
Method
The method is a function that is associated with an object. In Python, a method is not unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class,
and the one whose properties are acquired is known as a base class or parent class.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means shape. By polymorphism,
we understand that one task can be performed in different ways. For example - you have a class animal, and all
animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on the
animal. So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs and cats) have a
concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to methods and
variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because data
abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names
to things so that the name captures the core of what a function or a whole program does.
Python Class and Objects
We have already discussed in previous tutorial, a class is a virtual entity and can be seen as a blueprint of an object. The class came into existence when it instantiated. Let's
understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects of this class.
On the other hand, the object is the instance of a class. The process of creating an object can be called instantiation.
In this section of the tutorial, we will discuss creating classes and objects in Python. We will also discuss how a class attribute is accessed by using the object.
Creating classes in Python
In Python, a class can be created by using the keyword class, followed by the class name. The syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite
In Python, we must notice that each class is associated with a documentation string which can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as Employee id, and name.
The class also contains a function display(), which is used to display the information of the Employee.
class Employee:
id = 10
name = "Devansh"
def display (self):
print([Link],[Link])
Here, the self is used as a reference variable, which refers to the current class object. It is always the first argument in the function definition. However, usingself is optional in the
function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables. We can use anything instead of self,
but it must be the first parameter of any function which belongs to the class.
Creating an instance of the class
A class needs to be instantiated if we want to use the class attributes in another class or method. A class can be instantiated by
calling the class using the class name.
The syntax to create the instance of the class is given below.
<object-name> = <class-name>(<arguments>)
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%([Link],[Link]))
# Creating a emp instance of Employee class
emp = Employee()
[Link]()
Delete the Object
We can delete the properties of the object or object itself by using the del keyword
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
# Creating a emp instance of Employee class
emp = Employee()
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in Python. It is used to create an
object.
Parameterized Constructor
Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources
for the object to perform any start-up task.
We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly
used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
[Link]()
The parameterized constructor has multiple parameters along with the self.
Consider the following example.
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
More than One Constructor in Single class
Let's have a look at another scenario, what happen if we declare the two same
constructors in the class.
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
In the above code, the object st called the second constructor whereas both have
the same configuration. The first method is not accessible by the st object.
Internally, the object of the class will always call the last constructor if the class
has multiple constructors.
The built-in functions defined in the class are described in the following table.
SN Function Description
2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.
4 hasattr(obj, name) It returns true if the object contains some specific attribute.
class Student:
[Link] = name
[Link] = id
[Link] = age
print(getattr(s, 'name'))
print(getattr(s, 'age'))
print(hasattr(s, 'id'))
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print([Link])
Built-in class attributes
Along with the other attributes, a Python class also contains some built-in class attributes which provide information about the class.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information about the class namespace.
2 __doc__ It contains a string which has the class documentation
3 __name__ It is used to access the class name.
4 __module__It is used to access the module in which, this class is defined.
5 __bases__ It contains a tuple including all base classes.
class Student:
def __init__(self,name,id,age):
[Link] = name;
[Link] = id;
[Link] = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%([Link],[Link]))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class. In this
section of the tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Consider the following syntax to inherit a base class into the derived class.
Python Inheritance
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
• 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()
• [Link]()
• [Link]()
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. 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.
Python Inheritance
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example
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()
[Link]()
[Link]()
[Link]()
Python provides us the flexibility to inherit multiple base classes in the child class.
Python Inheritance
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
class BaseN:
<class-suite>
<class-suite>
Example
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([Link](10,20))
print([Link](10,20))
print([Link](10,20))
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()
[Link]()
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",[Link]());
print("SBI Rate of interest:",[Link]());
print("ICICI Rate of interest:",[Link]());
Data abstraction in python
Abstraction is an important aspect of object-oriented programming. In python, we can also perform data hiding by
adding the double underscore (___) as a prefix to the attribute which is to be hidden. After this, the attribute will not be
visible outside of the class through the object.
Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
[Link]()