VAC Python Notes
VAC Python Notes
[Link]
Sr. Assistant Professor
CS Dept
Geethanjali College of Engineering and
Technology
Hyderabad
Geethanjali College of Engineering and Technology
Course Outcomes:
Ability to explore python basic concepts
Ability to create practical and contemporary applications
UNIT – I
Introduction to Python, Installing Python. How a Program Works, Using Python, Program
Development Cycle, Input, Processing, and Output, Displaying Output with the Print
Function, Comments, Variables, Reading Input from the Keyboard, Performing
Calculations, Operators. Type conversions, Expressions.
Data types and Expressions: Strings, Assignment and Comments, Numeric Data Types
and Character Sets, Expressions, Functions and Modules.
Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision
Structures, Comparing Strings, Logical Operators, Boolean Variables.
UNIT - II
Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total,
Input Validation Loops, Nested Loops.
Control Statements: Definite Iteration, Formatting Text for Output, Selection,
Conditional Iteration.
File and Exceptions: Introduction to File Input and Output, Using Loops to Process Files,
Processing Records Exceptions.
UNIT - III
Functions: Introduction, Defining and Calling a Void Function, Designing a Program to
Use Functions, Local Variables, Passing Arguments to Functions, Global Variables and
Global Constants, Value-Returning Functions-Generating Random Numbers, The math
Module, Storing Functions in Modules.
Recursion: Introduction, Problem Solving with Recursion, Examples of Recursive
Algorithms.
Strings and Text Files: Accessing Characters and Substrings in a String, Strings and
Number System, String Methods, Basic String Operations, String Slicing, Testing,
Searching, and Manipulating Strings.
UNIT - IV
Lists, Introduction to Lists, List slicing, Finding Items in Lists with the in Operator, List
Methods and Useful Built-in Functions, Copying Lists, Processing Lists, Two-Dimensional
Lists.
Tuples Sequences, Tuples Methods and Useful Built-in Functions.
Dictionaries and Sets: Dictionaries, Sets, Methods and Useful Built-in Functions.
Serializing Objects.
UNIT - V
Design with Classes: Classes and Objects, Classes and Functions, Classes and Methods,
Working with Instances, Inheritance and Polymorphism. Object-Oriented Programming:
Procedural and Object-Oriented Programming, Classes, techniques for Designing
Classes.
Multithreaded Programming: Introduction, Threads and Processes, Python Threads,
Thread Module, Threading Module.
TEXT BOOKS:
1. Kenneth A. Lambert, The Fundamentals of Python: First Programs, 2011, Cengage
Learning.
2. Think Python First Edition, by Allen B. Downey, Orielly publishing
REFERENCE BOOKS:
1. Introduction to Computation and Programming Using Python. John V. Guttag, The MIT
Press.
2. James Payne, Beginning Python using Python 2.6 and Python 3, Wrox publishing
Python Introduction
What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
Python can be treated in a procedural way, an object-orientated way or a
functional way.
Good to know
The most recent major version of Python is Python 3. However, Python 2,
although not being updated with anything other than security updates, is
still quite popular.
It is possible to write Python in a text editor, using an Integrated
Development Environment, such as Thonny, Pycharm, Netbeans or
Eclipse which are particularly useful when managing larger collections of
Python files.
Python Install
Python Quickstart
Python is an interpreted programming language, this means that as a developer
you write Python (.py) files in a text editor and then put those files into the
python interpreter to be executed.
The way to run a python file is like this on the command line:
Let's write our first Python file, called [Link], which can be done in any
text editor.
[Link]
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:
Hello, World!
C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py
From there you can write any python, including our hello world example from
earlier in the tutorial:
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:
exit()
Python Syntax
Execute Python Syntax
Python syntax can be executed by writing directly in the Command Line:
Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:
Indentation
Indentation refers to the spaces at the beginning of a code line.
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Variables
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x = 5
y = "Hello, World!"
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a
comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Exercise:
Insert the missing part of the code below to output "Hello World".
("Hello World")
Variables
Creating Variables
Variables are containers for storing data values.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even
change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Example
x = "John"
# is the same as
x = 'John'
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Example
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
The Python print statement is often used to output variables.
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
Example
x = 5
y = 10
print(x + y)
If you try to combine a string and a number, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.
Example Create a variable inside a function, with the same name as the
global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
To create a global variable inside a function, you can use the global keyword.
Example If you use the global keyword, the variable belongs to the global
scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Also, use the global keyword if you want to change a global variable inside a
function.
Example
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Example
Print the data type of the variable x:
x = 5
print(type(x))
x = 20 Int
x = 20.5 Float
x = 1j Complex
x = range(6) Range
x = True Bool
x = b"Hello" Bytes
x = bytearray(5) Bytearray
x = memoryview(bytes(5)) Memoryview
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Exercise: print the data type of x, what data type would that be?
x = 5
print(type(x))
Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
Example Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Random Number
Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers:
print([Link](1, 10))
Exercise:
Insert the correct syntax to convert x into a decimal number.
x = 5
x = (x)
Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can
be done with casting. Python is an object-orientated language, and as such it
uses classes to define data types, including its primitive types.
Example Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Strings
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.
Example
print("Hello")
print('Hello')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
in the output, the line breaks are inserted at the same position as in the code.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
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])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
String Length
To get the length of a string, use the len() function.
String Methods
Python has a set of built-in methods that you can use on strings.
a = "Hello, World!"
print([Link]())
Example The split() method splits the string into substrings if it finds
instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
Check String
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:
The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print([Link](quantity, itemno, price))
You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print([Link](quantity, itemno, price))
Escape Character
To insert characters that are illegal in a string, use an escape character.
Example You will get an error if you use double quotes inside a
string that is surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
String Methods
Python has a set of built-in methods that you can use on strings.
All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the
position of where it was found
index() Searches the string for a specified value and returns the
position of where it was found
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
Booleans
Booleans represent one of two values: True or False.
Boolean Values
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and Python returns
the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
print(bool(x))
print(bool(y))
Any list, tuple, set, and dictionary are True, except empty ones.
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
print(myFunction())
if myFunction():
print("YES!")
else:
print("NO!")
Exercise:
The statement below would print a Boolean value, which one?
print(10 > 9)
Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
Assignment operators are used to assign values to variables:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Comparison Operators
Comparison operators are used to compare two values:
== Equal x == y
!= Not equal x != y
Logical Operators
Logical operators are used to combine conditional statements:
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
is not Returns True if both variables are not the same x is not y
object
Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
<< Zero fill left Shift left by pushing zeros in from the right and let
shift the leftmost bits fall off
Exercise:
Multiply 10 with 5, and print the result.
print(10 5)
User Input
Example The following example asks for the username, and when
you entered the username, it gets printed on the screen:
Python 3.6
username = input("Enter username:")
print("Username is: " + username)
Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username)
Python stops executing when it comes to the input() function, and continues
when the user has given some input.
if ... else
Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example if statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand if
If you have only one statement to execute, you can put it on the same line as
the if statement.
You can also have multiple else statements on the same line:
or logical operator
The or keyword is a logical operator, used to combine conditional statements:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Nested if
if statements inside if statements, is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Example
a = 33
b = 200
if b > a:
pass
Exercise:
Print "Hello World if a is greater than b.
a = 50
b = 10
a b
print("Hello World")
Loops
Python has two primitive loop commands:
while loops
for loops
The while loop requires relevant variables to be ready, in this example we need
to define an indexing variable, i, which we set to 1.
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Exercise:
Print i as long as i is less than 6.
i = 1
i < 6
print(i)
i += 1
The for loop does not require an indexing variable to set beforehand.
Example Exit the loop when x is "banana", but this time the break
comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
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":
for x in adj:
for y in fruits:
print(x, y)
Example
for x in [0, 1, 2]:
pass
Exercise:
Loop through the items in the fruits list.
Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " is a fruit.")
my_function("Apple")
my_function("Banana")
my_function("Mango")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
my_function("Apple", "Mango")
If you try to call the function with 1 or 3 arguments, you will get an error:
my_function("Apple")
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Example
def myfunction():
pass
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
Exercise:
Create a function named my_function.
:
print("Hello from a function")
Modules
What is a Module?
Consider a module to be the same as a code library.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Use a Module
Now we can use the module we just created, by using the import statement:
Example Import the module named mymodule, and call the greeting
function:
import mymodule
[Link]("students”)
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
person1 = {
"name": "Ram",
"age": 36,
"country": "India"
}
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
a = mm.person1["age"]
print(a)
Built-in Modules
There are several built-in modules, which you can import whenever you like.
x = [Link]()
print(x)
Example List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Example: The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "Ram",
"age": 36,
"country": "India"
}
print (person1["age"])
When importing using the from keyword, do not use the module name when
referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]
Exercise:
What is the correct syntax to import a module named "mymodule"?
mymodule
Functions (Contd..)
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. 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.
o Using functions, we can avoid rewriting the same logic/code again and
again in a program.
o We can call functions multiple times in a program and anywhere in a
program.
o We can track a large Python program easily when it is divided into
multiple functions.
o However, Function calling is always overhead in a Python program.
Creating a Function
Python provides the def keyword to define the function. The syntax for defining
the function is given below.
def my_function(parameters):
function_block
return expression
o The def keyword, along with the function name is used to define the
function.
o The function name must follow identifier rules.
o A function accepts the parameter (argument), and they can be optional.
o The function block is started with the colon (:), and block statements
must be at the same indentation.
o The return statement is used to return the value. A function can have
only one return
Function Calling
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.
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
Syntax
return [expression_list]
It can contain the expression which gets evaluated and value is returned to the
caller function. If the return statement has no expression or does not exist itself
in the function then it returns the None object.
Example1
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
In the above code, we have defined the function named sum, and it has a
statement c = a+b, which computes the given values, and the result is
returned by the return statement to the caller function.
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Output: None
In the above code, we have defined the same function without the return
statement as we can see that the sum() function returned the None object to
the caller function.
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.
Output: Hi Students
a = int(input("Enter a: "))
b = int(input("Enter b: "))
Output:
Enter a: 10
Enter b: 20
Sum = 30
def change_list(list1):
[Link](20)
[Link](30)
print("list inside function = ",list1)
list1 = [10,30,40,50]
change_list(list1)
print("list outside function = ",list1)
Output:
change_string(string1)
print("printing the string outside function :",string1)
Output:
Types of arguments
There may be several types of arguments which can be passed at the time of
function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
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))
Output:
Example
The function simple_interest accepts three arguments and returns the s
imple interest accordingly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
Output:
def calculate(a,b):
return a+b
calculate(10) # this causes an error as we are missing a required arguments b.
Output:
Default Arguments
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
Output:
def printme(name,age=22):
print("My name is",name,"and age is",age)
D. Subhashini,Sr. Assist Prof CS
dept
Geethanjali College of Engineering and Technology
printme(name = "john")
#the variable age is not passed into the function however the default value of
age is considered in the function
printme(age = 10,name="David")
#the value of age is overwritten here, 10 will be printed as age
Output:
Example
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")
Output:
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.
def func(name,message):
print("printing the message with",name,"and ",message)
func(name = "John",message="hello")
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:
Example Function called with the keyword arguments, that does not
match
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))
Output:
Python allows us to provide the mix of the required arguments and keyword
arguments at the time of function call. However, the required argument must not
be given after the keyword argument, i.e., once the keyword argument is
encountered in the function call, the next arguments must also be the keyword
arguments.
Example
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
#the first argument is not the keyword argument
func("John",message="hello",name2="Jhony")
Output:
The following example will cause an error due to an improper mix of keyword
and required arguments being passed in the function call.
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
func("John",message="hello","David")
Output:
Python provides the facility to pass the multiple keyword arguments which can
be represented as **kwargs. It is similar as the *args but it stores the
argument in the dictionary format.
def food(**kwargs):
print(kwargs)
food(a="Apple")
food(fruits="Orange", Vegetables ="Carrot")
Output:
{'a': 'Apple'}
{'fruits': 'Orange', 'Vegetables': 'Carrot'}
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.
1. Global variables
2. 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.
Output:
Example
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:
Output:
The sum is 60
Value of sum outside the function: 0
def calculate(*args):
global sum
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)
Output:
The sum is 60
Value of sum outside the function: 60
Iterators
Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
print(next(myit))
print(next(myit))
print(next(myit))
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
for x in mytuple:
print(x)
for x in mystr:
print(x)
The for loop actually creates an iterator object and executes the next() method
for each loop.
File Open
Python has several functions for creating, reading, updating, and deleting
files.
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not
exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("[Link]")
Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
[Link]
The open() function returns a file object, which has a read() method for reading
the content of the file:
Example
f = open("[Link]", "r")
print([Link]())
If the file is located in a different location, you will have to specify the file path,
like this:
f = open("D:\\myfiles\[Link]", "r")
print([Link]())
f = open("[Link]", "r")
print([Link](5))
D. Subhashini,Sr. Assist Prof CS
dept
Geethanjali College of Engineering and Technology
Read Lines
You can return one line by using the readline() method:
f = open("[Link]", "r")
print([Link]())
By calling readline() two times, you can read the two first lines:
f = open("[Link]", "r")
print([Link]())
print([Link]())
By looping through the lines of the file, you can read the whole file, line by line:
f = open("[Link]", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
Example Close the file when you are finish with it:
f = open("[Link]", "r")
print([Link]())
[Link]()
Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.
Example Open the file "[Link]" and append content to the file:
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
Python provides the tell() method which is used to print the byte number at
which the file pointer currently exists. Consider the following example.
Output:
For this purpose, the Python provides us the seek() method which enables us
to modify the file pointer position externally.
Syntax:
<fileptr>.seek(offset[,from])
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as the
reference position. If it is set to 2, the end of the file pointer is used as the
reference position.
Example
Output:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
f = open("[Link]", "w")
Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:
import os
[Link]("[Link]")
import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the [Link]() method:
import os
[Link]("myfolder")
The file object provides the following methods to manipulate the files on various operating systems.
SN Method Description
1 [Link]() It closes the opened file. The file once closed, it can't be
read or write anymore.
3 [Link]()
It returns the file descriptor used by the underlying
implementation to request I/O from the OS.
4 [Link]()
It returns true if the file is connected to a TTY device,
otherwise returns false.
7 [Link]([size])
It reads one line from the file and places the file pointer to
the beginning of the new line.
8
[Link]([sizehin It returns a list containing all the lines of the file. It reads
t]) the file until the EOF occurs using readline() function.
9 [Link](offset[,from
It modifies the position of the file pointer to a specified
)
offset with the specified reference.
10 [Link]()
It returns the current position of the file pointer within the
file.
Exceptions
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 by 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.
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. Let's see the following example.
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. We can handle these exceptions in the following way.
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")
Output:
Enter a:10
Enter b:0
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")
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
Example
try:
a = int(input("Enter
a:"))
b = a/b;
c int(input("Enter
b:"))
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
try:
a = int(input("Enter
a:"))
b = a/b
c int(input("Enter
b:"))
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Enter a:10
Enter b:0
can't divide by
zero division by
zero
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("[Link]","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
1. [Link]()
Output:
The Python allows us to declare the multiple exceptions with the except clause.
Declaring multiple exceptions is useful in the cases where a try block throws
multiple exceptions. The syntax is given below.
Syntax
try:
#block of code
else:
#block of code
Example
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
Python provides the optional finally statement, which is used with the try
statement. It is executed no matter what exception occurs and used to release
the external resource. The finally block provides a guarantee of the execution.
We can use the finally block with the try block in which we can place the
necessary code, which must be executed before the try statement throws an
exception.
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
try:
fileptr = open("[Link]","r")
try:
[Link]("Hi I am good")
finally:
[Link]()
print("file closed")
except:
print("Error")
Output:
file closed
Error
Raising exceptions
Syntax
Points to remember
1. To raise an exception, the raise statement is used. The exception class name follows
it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which
stores the value of the exception.
4. 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")
Output:
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)
Output:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
Enter a:10
Enter b:0
The value of b can't be 0
Modules
A python module can be defined as a python program file which contains a
python code including python functions, class, or variables. In other words, we
can say that our python code file saved with the extension (.py) is treated as the
module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Example
In this example, we will create a module named as [Link] which contains a
function func that contains a code to print some message on the console.
Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named file.
We need to load the module in our python code to use its functionality. Python
provides two types of statements as defined below.
The import statement is used to import all the functionality of one module into
another. Here, we must notice that we can use the functionality of any python
source file by importing that file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is
loaded once regardless of the number of times, it has been imported into our file.
Hence, if we need to call the function displayMsg() defined in the file [Link], we
have to import that file as a module into our module as shown in the example
below.
Example:
import file;
name = input("Enter the name?") [Link](name)
Output:
Enter the
name?John Hi John
Instead of importing the whole module into the namespace, python provides the
flexibility to import only the specific attributes of a module. This can be done by
using from? import statement. The syntax to use the from-import statement is
given below.
[Link]:
[Link]:
Output:
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we
can use this name to use that module in our python source [Link] syntax to rename a
module is given below.
Example
Output:
Enter
a?10
Enter
b?20 Sum
= 30
Math Module
Python math module is defined as the most famous mathematical functions, which
includes trigonometric functions, representation functions, logarithmic functions, etc.
Furthermore, it also defines two mathematical constants, i.e., Pie and Euler number,
etc.
Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.
[Link]()
This method returns the natural logarithm of a given number. It is calculated to the base
e.
Example
import math
x=
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :', [Link]([Link](number), 10))
Output:
math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.
Example
import math
x=13 # small value of of x
print('log10(x) is :', math.log10(x))
Output:
log10(x) is : 1.1139433523068367
[Link]()
This method returns a floating-point number after raising e to the given number.
Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', [Link](number)-1)
Output:
[Link](x,y)
This method returns the power of the x corresponding to the value of y. If value of x is
negative or y is not integer value than it raises a ValueError.
Example
import math
number = [Link](10,2)
print("The power of number:",number)
Output:
[Link](x)
This method returns the floor value of the x. It returns the less than or equal value to x.
Example:
import math
number = [Link](10.7 5201)
print("The floor value is:",number)
[Link](x)
This method returns the ceil value of the x. It returns the greater than or equal value to
x.
import math
number = [Link](10.25201)
print("The floor value is:",number)
Output:
[Link](x)
This method returns the absolute value of x.
import math
number = [Link](10.001)
print("The floor absolute is:",number)
Output:
[Link]()
This method returns the factorial of the given number x. If x is not integral, it raises a
ValueError.
Example
import math
number = [Link](7)
print("The factorial of number:",number)
Output:
[Link](x)
This method returns the fractional and integer parts of x. It carries the sign of x is float.
Example
import math
number = [Link](44.5)
print("The modf of number:",number)
Output:
Python provides the several math modules which can perform the complex task in
single- line of code.
What is Threading?
A single process can consist of multiple threads each thread in a program performs a
particular task.
Example: In the game, a game as a whole is a single process but it consists of several threads
responsible for playing music taking input from the user and running the opponent, etc. All
these are the separate tasks that are managed by threads.
Thread
In computing, a process is an instance of a computer program that is being executed. Any
process has 3 basic components:
An executable program.
The associated data needed by the program (variables, work space, buffers, etc.)
The execution context of the program (State of process)
A thread is an entity within a process that can be scheduled for execution. Also, it isthe smallest
unit of processing that can be performed in an OS (Operating System).
In simple words, a thread is a sequence of such instructions within a program that can be
executed independently of other code. For simplicity, you can assume that a thread is simply a
subset of a process!
Stack pointer: Points to thread’s stack in the process. Stack contains the local
variables under thread’s scope.
Program counter: a register which stores the address of the instruction currently
being executed by thread.
Thread state: can be running, ready, waiting, start or done.
Thread’s register set: registers assigned to thread for computations.
Parent process Pointer: A pointer to the Process control block (PCB) of theprocess
that the thread lives on.
Consider the diagram below to understand the relation between process and its thread:
Multithreading
Each thread contains its own register set and local variables (stored in stack).
All thread of a process share global variables (stored in heap) and
the program code.
Consider the diagram below to understand how multiple threads exist in memory:
Consider the diagram below in which a process contains two active threads:
Multithreading in Python
In Python, the threading module provides a very simple and intuitive API for spawning
multiple threads in a program.
kernel thread
user thread
Kernel Threads are a part of the operating system, while the User-space threads are not
implemented in the kernel.
There are two modules which support the usage of threads in Python3:
_thread
threading
The thread module has been "deprecated" for quite a long time. Users are encouraged to
use the threading module instead. Hence, in Python 3, the module "thread" is not available
anymore. However, it has been renamed to "_thread" for backwards compatibilities in
Python3.
This method call enables a fast and efficient way to create new threads in both Linuxand
Windows.
The method call returns immediately and the child thread starts and calls function with the
passed list of args. When the function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing
any arguments. kwargs is an optional dictionary of keyword arguments.
Example
import _thread
import time
try:
except:
while 1:
pass
Output
When the above code is executed, it produces the following result −
Although it is very effective for low-level threading, the thread module is very limited
compared to the newer threading module.
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
isAlive() − The isAlive() method checks whether a thread is still executing.
getName() − The getName() method returns the name of a thread.
setName() − The setName() method sets the name of a thread.
def calc_square(number):
print("Calculate square numbers: ")
for i in numbers:
[Link](0.2) #artificial time-delay
print('square: ', str(n*n))
def calc_cube(number):
print("Calculate cude numbers: ")
for i in numbers:
[Link](0.2)
print('cube: ', str(n*n*n))
arr = [2,3,8,9]
t = [Link]()
t1 = [Link](target = cal_square,args=(arr,))
t2 = [Link](target = cal_cube,args=(arr,))
[Link]()
To create a new thread, we create an object of Thread class. It takes following arguments:
target: the function to be executed by thread
args: the arguments to be passed to the target function
To start a thread, we use start method of Thread class.
[Link]()
[Link]()
Once the threads start, the current program (you can think of it like a main thread) also
keeps on executing. In order to stop execution of current program until a thread is
complete, we use join method.
[Link]()
[Link]()
As a result, the current program will first wait for the completion of t1 and then t2. Once,
they are finished, the remaining statements of current program are executed.
Consider the diagram below for a better understanding of how above program works:
The reason to use time delay here just to demonstrate that in which scenario multi-
threading could be useful here we are calculating square and then cubes when we are using
a [Link]() here what's happening is CPU idle and is doing nothing for 0.2 sec.
Consider the python program given below in which we print thread name and corresponding
process for each task:
import threading
import os
def task1():
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 1: {}".format([Link]()))
def task2():
print("Task 2 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 2: {}".format([Link]()))
# creating threads
t1 = [Link](target=task1, name='t1')
t2 = [Link](target=task2, name='t2')
# starting threads
[Link]()
[Link]()
Classes in Python:
In Python, a class is a user-defined data type that contains both the data itself and the
methods that may be used to manipulate it. In a sense, classes serve as a template to
create objects. They provide the characteristics and operations that the objects will employ.
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.
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.
Example:
Code:
class Person:
def __init__(self, name, age):
# This is the constructor method that is called when creating a new
Person object
# It takes two parameters, name and age, and initializes them as a
ttributes of the object
[Link] = name
[Link] = age
def greet(self):
# This is a method of the Person class that prints a greeting messa
ge
print("Hello, my name is " + [Link])
Name and age are the two properties of the Person class. Additionally, it has a function
called greet that prints a greeting.
Objects in Python:
An object is a particular instance of a class with unique characteristics and functions. After a
class has been established, you may make objects based on it. By using the class
constructor, you may create an object of a class in Python. The object's attributes are
initialised in the constructor, which is a special procedure with the name __init__.
Syntax:
Code:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
print("Hello, my name is " + [Link])
# Create a new instance of the Person class and assign it to the variable
person1
person1 = Person("Ayan", 25)
[Link]()
Output:
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.
_ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is
called. Although it is used to set the object's attributes, it is often referred to as a
constructor.
The self-argument is the only one required by the __init__ method. This argument refers to
the newly generated instance of the class. To initialise the values of each attribute
associated with the objects, you can declare extra arguments in the __init__ method.
Code:
class Person:
count = 0 # This is a class variable
def __init__(self, name, age):
[Link] = name # This is an instance variable
[Link] = age
[Link] += 1 # Accessing the class variable using the name
of the class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
Output:
2
Whereas, instance variables are specific to each instance of a class. They are specified
using the self-argument in the __init__ method. Here's an illustration:
Code:
class Person:
def __init__(self, name, age):
[Link] = name # This is an instance variable
[Link] = age
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print([Link])
print([Link])
Output:
Ayan
30
Class variables are created separately from any class methods and are shared by all class
copies. Every instance of a class has its own instance variables, which are specified in the
__init__ method utilising the self-argument.
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.
1. Parameterized Constructor
2. 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.
Example
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
Example
class Student:
count = 0
def __init__(self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])
Output:
The number of students: 3
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")
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]()
Output:
This is parametrized constructor
Hello John
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
Output:
101 Joseph
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
Output:
The Second Constructor
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.
SN Function Description
It is used to access
1 getattr(obj,name,default) the attribute of the
object.
It is used to set a
particular value to the
2 setattr(obj, name,value)
specific attribute of an
object.
It is used to delete a
3 delattr(obj, name)
specific attribute.
Example
class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age
# creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print([Link])
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
SN Attribute Description
Example
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__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
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.
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>
Example 1
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]()
Output:
dog barking
Animal Speaking
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<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))
Output:
30
200
0.5
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(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:
True
False
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(isinstance(d,Derived))
Output:
True
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]()
Output:
Barking
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]()
Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'