SlideShare ist ein Scribd-Unternehmen logo
1 von 91
Downloaden Sie, um offline zu lesen
1 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
History: Python is a widely used general-purpose, high level programming scripting
language. It was created by Guido van Rossum in 1991
Q.Python Features
1) Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the semicolon
or curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.
2) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
3) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once
4) Free and Open Source
Python is freely available for everyone. It is freely available on its official
website www.python.org.
5) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
6) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application
7) Dynamic Memory Allocation
2 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
In Python, we don't need to specify the data-type of the variable. When we assign some value
to the variable, it automatically allocates the memory to the variable at run time. Suppose we
are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
8) Embeddable
The code of the other programming language can use in the Python source code. It can use
Python source code in another programming language as well.
Q.Comparing C,C++,Python
C C++ Python
C was developed by
Dennis Ritchie between
the year 1969 and 1973 at
AT&T Bell Labs.
C++ was developed by
Bjarne Stroustrup in
1979.
Python was created by Guido
van Rossum, and released in
1991.
More difficult to write
code in contrast to both
Python and C++ due to
complex syntax.
C++ code is less complex
than C but more complex
in contrast to python. Easier to write code.
Longer lines of code as
compared to python.
Longer lines of code as
compared to python.
3-5 times shorter than
equivalent C/C++ programs.
Variables are declared in
C.
Variables are declared in
C++ Python has no declaration.
C is a compiled language.
C++ is a compiled
language.
Python is an interpreted
language.
C contains 32 keywords.
C++ contains 52
keywords. Python contains 33 keywords.
For the development of
code, C supports
procedural programming.
C++ is known as hybrid
language because C++
supports both procedural
Python supports multiple
programming paradigms,
including procedural, object-
3 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
C C++ Python
and object oriented
programming paradigms.
oriented, and functional
programming.
C does not support
inheritance.
C++ support both single
and multiple inheritance
Python supports all 5 types of
inheritance i.e. single
inheritance, multiple
inheritance, multilevel
inheritance, hierarchical
inheritance, and hybrid
inheritance
C provides malloc() and
calloc() functions for
dynamic memory
allocation, and free() for
memory de-allocation.
C++ provides new
operator for memory
allocation and delete
operator for memory de-
allocation.
Python’s memory allocation
and deallocation method is
automatic.
Direct support for
exception handling is not
supported by C.
Exception handling is
supported by C++.
Exception handling is
supported by Python.
Different Types Of extension
Python scripts may have one of several file extensions. Each file extension has a special
meaning and purpose.
• *.py - Regular scripts
• *.py3 - (rarely used) Python3 script; Python3 scripts usually end with "*.py" not
"*.py3"
• *.pyc - compiled script (Bytecode)
4 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
• *.pyo - optimized pyc bytecode file (As of Python3.5, Python will only use pyc
rather than pyo and pyc)
• *.pyw - Python script for Windows that is executed with pythonw.exe
• *.pyx - Cython src to be converted to C/C++
• *.pyd - Python script made as a Windows DLL
Q.Application of Phyton
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
5 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python
provides many useful frameworks, and these are given below:
o Django and Pyramid framework(Use for heavy applications)
o Flask and Bottle (Micro-framework)
o Plone and Django CMS (Advance Content management)
2) Desktop GUI Applications
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute. This kind of application was more
popular in the old generation of computers. Python can develop this kind of application very
effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes
it the most suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.
o SCons is used to build control.
6 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
o Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
o Round or Trac for bug tracking and project management.
5) Scientific and Numeric
This is the era of Artificial intelligence where the machine can perform the task the same as
the human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
Implementing machine learning algorithms require complex mathematical calculation. Python
has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc.
If you have some basic knowledge of Python, you need to import libraries on the top of the
code. Few popular frameworks of machine libraries are given below.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example
of a business application. This kind of application requires extensively, scalability and
readability, and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business
application.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc.
The few multimedia libraries are given below.
o Gstreamer
7 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
o Pyglet
o QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system. Python can create a 3D CAD application
by using the following functionalities.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
10) Image Processing Application
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given
below.
• OpenCV
• Pillow
• SimpleITK
Disadvantages of Python
1. Slow Speed
Python is an interpreted language and dynamically-typed language.
The line by line execution of code often leads to slow execution.
2. Not Memory Efficient
8 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
To provide simplicity to the developer, Python has to do a little tradeoff.
The Python programming language uses a large amount of memory.
This can be a disadvantage while building applications when we prefer memory optimization.
3. Weak in Mobile Computing
Python is generally used in server-side programming.
It don’t get to see Python on the client-side or mobile applications because of the following
reasons.
Python is not memory efficient and it has slow processing power as compared to other
languages.
4. Database Access
Programming in Python is easy and stress-free.
But when it are interacting with the database, it lacks behind.
The Python’s database access layer is primitive and underdeveloped in comparison to the
popular technologies like JDBC and ODBC.
Huge enterprises need smooth interaction of complex legacy data and Python is thus rarely
used in enterprises.
5. Runtime Errors
Python is a dynamically typed language so the data type of a variable can change anytime.
A variable containing integer number may hold a string in the future, which can lead
to Runtime Errors.
Therefore Python programmers need to perform thorough testing of the applications.
Q. First Program In Python
1.
>>> print("Hello, World!")
o/p Hello, World!
9 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
OR
Save above file p.py
Run =>python p.py
Q. Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are
valid example.
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. An identifier can be of any length.
5. Python is a case-sensitive language. This means, Variable and variable are not the same.
Valid Identifier
Salay, sum_sal etc
Q.Python Keywords
• Keywords are the reserved words in Python.
10 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
• It cannot use a keyword as a variable name, function name or any other identifier. They
are used to define the syntax and structure of the Python language.
• In Python, keywords are case sensitive.
• There are 33 keywords in Python 3.7. This number can vary slightly over the course of
time.
• All the keywords except True, False and None are in lowercase and they must be
written as they are. The list of all the keywords is given below.
False await else import pass
None break except in raise
True class finally is return
And continue For lambda try
As def from nonlocal while
Assert del global not with
Async elif if or yield
11 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Q.Python Comments
1. Single Line Comment
It is used to single line comment by using #
e.g
#print("Hello,World!")
2. Multi line comment
It is used to “”” (tripal quotes)
e.g
"""
This is python
This is Java
"""
Q.Lines and Indentation
Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation.
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the same amount
Note:
1.Semicolon at the end of statement is optional
2.Instead of {},indentations are used to represent block
12 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
For e.g 1:valid
if condtion:
statement
statement
For e.g 2 : invalid
if condtion:
statement
statement
else:
statement
statement
Multi-Line Statements
Explicit Line Continuation
• Statements in Python typically end with a new line. Python does, however, allow the
use of the line continuation character () to denote that the line should continue. For
example −
total = item_one + 
item_two + 
item_three
Implicit Line continuation
• Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Q.Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
x=5
13 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
y=”vision”
print(x)
print(y)
type()
Get the data type of a variable with the type() function.
x= 5
y= "John"
print(type(x))o/p===➔<class=’int’>
print(type(y)) /p===➔<class 'str'>
Q.Data Type
Python supports three types of numeric data.
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
e.g. x = 20
14 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
e.g. x = 20.5
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
e.g x = 1j
Q.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
• Python Arithmetic Operators
Arithmetic operators
Operator
Name Example
+ Addition x + y
15 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
Operator
Example Same As
= 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
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
16 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
<<= x <<= 3 x = x << 3
Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
Or Returns True if one of the statements is true x < 5 or x < 4
Not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Python 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:
17 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description
Example
in Returns True if a sequence with the specified value
is present in the object
x in y
not in Returns True if a sequence with the specified value
is not present in the object
x not in y
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name
& AND
| OR
^ XOR
Operator Description
Example
is Returns true if both variables are the same object x is y
is not Returns true if both variables are not the same object x is not y
18 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
~ NOT
<< Zero fill left shift
>> Signed right shift
Data Type Conversion
Sr.No. Function & Description
1 int(x[,base])
Converts x to an integer. base specifies the base if x is a string.
2 long(x[,base])
Converts x to a long integer. base specifies the base if x is a string.
3 float(x)
Converts x to a floating-point number.
4 complex(real[,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
19 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Sr.No. Function & Description
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
20 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Sr.No. Function & Description
17 oct(x)
Converts an integer to an octal string.
Q.print Function
The print() function prints the specified message to the screen, or other standard output device.
Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Values
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before printed
sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default
is ' '
end='end' Optional. Specify what to print at the end. Default is 'n' (line feed)
File Optional. An object with a write method. Default is sys.stdout
Flush Optional. A Boolean, specifying if the output is flushed (True) or buffered
(False). Default is False
21 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
e.g
1.print("Hello", "how are you?")
2.c=4
print('value is', c) o/p==➔value is c
3.b = "for"
print("Geeks", b , "Geeks") o/p===➔Greeks for Greeks
4.print(1,2,3,4) o/p=➔1 2 3 4
5.print(1,2,3,4,sep=’#’,end=’&’) o/p➔1#2#3#4&
6.print(1,2,3,4,sep=’*’) o/p➔1*2*3*4
Q.input function
The input() function allows user input.
Syntax
input(prompt)
Where
prompt=>A string, representing default message before input
22 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
e.g
x = input('”enter value'”)
print('”Hello”,x)
Addition of two nos
a = input('enter value1')
b=input('enter value2')
c=int(a)+int(b)
print('addition is',c)
Q.Control Statement
1.condtional statement
1.if statement
Syntax
if boolean-expression:
#statements
e.g
a= 33
b= 200
if b>a:
print("b is greater than a")
2.if-else statement
Syntax
if boolean-expression:
23 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
#statements
else:
#statements
e.g
i = 10
if i % 2 == 0:
print("Number is even")
else:
print("Number is odd")
3. Nested if-elif
Syntax
if boolean-expression:
#statements
elif boolean-expression:
#statements
elif boolean-expression:
#statements
elif boolean-expression:
#statements
else:
#statements
e.g
1.
a= 200
b= 33
if b>a:
print(“bismax”)
elif a==b:
print("aandbareequal")
else:
print("a is greater than b")
24 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
e.g
2
x= 41
if x> 10:
print("Aboveten,")
if x> 20:
print("andalsoabove20!")
else:
print("but not above 20.")
Loop
1. While
Syntax
while expression:
statement(s)
e.g
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
2.For loop
Syntax
for iterating_var in sequence:
statements(s)
e.g
for ch in 'vision':
print 'Current Letter :', ch
25 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.
Syntax
range(start, stop, step)
Parameter Description
Start Optional. An integer number specifying at which position to start.
Default is 0
Stop Required. An integer number specifying at which position to stop
(not included).
Step Optional. An integer number specifying the incrementation. Default
is 1
x= range(3, 6)
for n in x:
print(n)
o/p 3 4 5
26 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
x= range(3, 10, 2)
for n in x:
print(n)
o/p 3 5 7 9
Using Else Statement in loop
for x in range(6):
print(x)
else:
print("Fi+inally finished!")
o/p 0 1 2 3 4 5
finallyfinished
Break & Continue Statement
1.
i= 1
while i< 6:
print(i)
if i== 3:
27 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
break
i = i+1
2.
i= 0
while i< 6:
i+= 1
if i== 3:
continue
print(i)
Pass statement
pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens
and the statement results into no operation.
The pass statement is generally used as a placeholder
i.e. when the user does not know what code to write. So user simply places pass at that line.
Sometimes, pass is used when the user doesn’t want any code to execute. So user simply
places pass there as empty code. Empty code is not allowed in loops, function definitions,
class definitions, or in if statements. So using pass statement user avoids this error.
e.g
1.
a = 33
b = 200
if b > a:
pass
print("pass statement")
2.
28 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
def myfunction():
pass
Note: The pass statement is a null statement. But the difference between pass and comment
is that comment is ignored by the interpreter whereas pass is not ignored.
Q.Math Function
List of Functions in Python Math Module
Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x)
Returns the mantissa and exponent of x as the pair (m,
e)
fsum(iterable)
Returns an accurate floating point sum of values in the
iterable
isfinite(x)
Returns True if x is neither an infinity nor a NaN (Not a
Number)
isinf(x) Returns True if x is a positive or negative infinity
29 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
isnan(x) Returns True if x is a NaN
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x - 1
log(x[, b]) Returns the logarithm of x to the base b (defaults to e)
log1p(x) Returns the natural logarithm of 1+x
log2(x) Returns the base-2 logarithm of x
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
acos(x) Returns the arc cosine of x
asin(x) Returns the arc sine of x
atan(x) Returns the arc tangent of x
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
30 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
lgamma(x)
Returns the natural logarithm of the absolute value of the
Gamma function at x
Pi
Mathematical constant, the ratio of circumference of a
circle to it's diameter (3.14159...)
E mathematical constant e (2.71828...)
import math
31 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
print(math.pi)
Q.String
String is sequence of character.
String declaration
1.Using Double quotes
a=”Hello”
print(a)
2.UsingSingleQuotes
a=’hello’
print(a)
2.Multiline Strings
You can assign a multiline string to a variable by using three quotes:
1.Using 3 double quotes
a= """visionacademy,
classesforbcs/bca/bba."""
print(a)
2.Using 3 Single quotes
a= '''visionacademy,classesforbcs/bca/bba.'''
print(a)
Representations of String
32 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
• Strings are stored individual character in contiguous location
• It can access from both direction (forward & backward)
• Both forward & backword indexing are provided using string in python
Forward indexing start with 0,1,2,3,…
Backward indexing start with -1,-2,-3……..
Escape Characters
Code Result
' Single Quote
 Backslash
n New Line
r Carriage Return
t Tab
b Backspace
f Form Feed
ooo Octal value
xhh Hex value
33 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
e.g
txt = "HellonWorld!"
print(txt)
Slicing a String
If S is a string, the expression S [ start : stop : step ] returns the portion of the string from
index start to index stop, at a step size step.
Syntax
Basic Example
Here is a basic example of string slicing.
S = ' A B C D E F G H I '
print(S[2:7]) # C D E F G
34 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Note that the item at index 7 'H' is not included.
Slice with Negative Indices
You can also specify negative indices while slicing a string.
S = ' A B C D E F G H I '
print(S[-7:-2]) # C D E F G
Slice with Positive & Negative Indices
You can specify both positive and negative indices at the same time.
35 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
S = ' A B C D E F G H I '
print(S[2:-5]) # C D
Specify Step of the Slicing
You can specify the step of the slicing using step parameter. The step parameter is optional
and by default 1.
# Return every 2nd item between position 2 to 7
S = ' A B C D E F G H I '
print(S[2:7:2]) # C E G
Negative Step Size
You can even specify a negative step size.
# Returns every 2nd item between position 6 to 1 in reverse order
S = ' A B C D E F G H I '
print(S[6:1:-2]) # G E C
Slice at Beginning & End
Omitting the start index starts the slice from the index 0. Meaning, S[:stop] is equivalent
to S[0:stop]
# Slice first three characters from the string
S = ' A B C D E F G H I '
print(S[:3]) # A B C
36 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Whereas, omitting the stop index extends the slice to the end of the string.
Meaning, S[start:] is equivalent to S[start:len(S)]
# Slice last three characters from the string
S = ' A B C D E F G H I '
print(S[6:]) # G H I
Note:
Rules of slicing
==============================
IF negative step size given
By default start value=>-1
By default end value==> -(len+1)
==========================================
if not given step size then it shld consider by default positive(+1)
By default start value o
By default end value==>length of string
====================================================
IF positive step size given
By default start value=> 0
By default end value==> length of string
=======================================
s[1:] valid
37 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
String operator
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give
HelloPython
* Repetition - Creates new strings, concatenating multiple
copies of the same string
a*2 will give -
HelloHello
[] Slice - Gives the character from the given index a[1] will give e
[ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell
b[2:]=>thon
b[:3]=>Pyt
b[-4:-2]=>th
In Membership - Returns true if a character exists in the given
string
H in a =>1
not in Membership - Returns true if a character does not exist in
the given string
M not in a =>1
38 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
% Format - Performs String formatting
Build-in String Method
Method Description
capitalize() Converts the first character to upper case
e.g
txt= "hello,andwelcometomyworld."
x=txt.capitalize()
print (x)
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
txt= "Iloveapples,applearemyfavoritefruit"
x=txt.count("apple")
print(x)
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of
where it was found
txt= "Hello,welcometomyworld."
x=txt.find("welcome")
print(x)
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of
where it was found
39 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
txt= "50800"
x=txt.isdigit()
print(x)
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
txt= "HellomyFRIENDS"
x=txt.lower()
print(x)
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified
value
40 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
txt= "Ilikebananas"
x=txt.replace("bananas", "apples")
print(x)
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
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
txt= "welcometothejungle"
x=txt.split()
print(x)
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
txt= "Hellomyfriends"
x=txt.upper()
print(x)
zfill() Fills the string with a specified number of 0 values at the beginning
41 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Q List
• A list in Python is used to store the sequence of various types of data.
• Python lists are mutable(Its mean it can modify its element after it created).
• A list can be defined as a collection of values or items of different types. The items in
the list are separated with the comma (,) and enclosed with the square brackets [].
• It allowed duplicate value
Syntax
Listname=[value1, value2,…..valuen]
e.g
list1 = ["apple", "banana", "cherry", "apple", "cherry"]
list2 = ["abc", 34, True, 40, "male"]
print(list1)
print(list2)
o/p
["apple", "banana", "cherry", "apple", "cherry"]
[‘abc’, 34, True, 40, ‘male’]
Display List using loop
list=["apple", "banana", "cherry"]
for i in range(len(list)):
print(list[i])
OR
list = ["apple", "banana", "cherry"]
42 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
for x in list:
print(x)
Accessing Element in List
List index
e.g
list1=["apple", "banana", "cherry"]
print(list1[1] o/p=>bannan
print(list1[-1]) o/p=>cherry
Slicing List
e.g
list1=["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list1[2:5]) o/p=>[‘cherry’,’orange’,’kiwi’]
print(thislist[:4]) o/p=>[‘apple’,’banana’,’cherry’,’orange’]
print(thislist[2:]) o/p=>[‘cherry’,’kiwi’,’melon’,’msngo’]
print(thislist[-4:-1]) o/p=>[‘orange’,’kiwi’,’melon’]
Inserting Item
thislist=["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) o/p=➔[‘apple’, ‘banana’,’watermelon’, "cherry"]
Updating List
43 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2] o/p=➔1997
list[2] = 2001;
print "New value available at index 2 : "
print list[2] o/p➔2001
Change a Range of Item Values
thislist=["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3]=["blackcurrant", "watermelon"]
print(thislist)
o/p[‘apple’,’blackcurrant’,watermelon’,’orange’,’kiwi’,’mango’]
thislist=["apple", "banana", "cherry"]
thislist[1:2]=["blackcurrant", "watermelon"]
print(thislist)
o/p[‘apple’,’balckcurrent’,’watermelon’]
thislist=["apple", "banana", "cherry"]
thislist[1:3]=["watermelon"]
print(thislist)
o/p [‘apple’,’watermelon’]
Remove Item
1.remove():The remove() method removes the specified item.
44 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
list=["apple", "banana", "cherry"]
list.remove("banana")
print(list)
o/p [‘apple’,’cherry’]
2.pop():The pop() method removes the specified index.
list=["apple", "banana", "cherry"]
list.pop(1)
print(list)
o/p [‘apple’,’cherry’]
If you do not specify the index, the pop() method removes the last item.
list=["apple", "banana", "cherry"]
list.pop()
print(list)
o/p [‘apple’,’banana’]
3.Del():The del keyword also removes the specified index
list=["apple", "banana", "cherry"]
del list[0]
print(list)
o/p [‘banana’,’cherry’]
The del keyword can also delete the list completely.
list=["apple", "banana", "cherry"]
del list
45 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
4.clear():The clear() method empties the list
list = ["apple", "banana", "cherry"]
list.clear()
print(thislist)
Method Description
append() Adds an element at the end of the list fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(x)
copy() Returns a copy of the list fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x)
count() Returns the number of elements with
the specified value
fruits = ["apple", "banana", "cherry"]
x = fruits.count("cherry")
print(x)
extend() Add the elements of a list (or any
iterable), to the end of the current list
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
index() Returns the index of the first element
with the specified value
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)
o/p 2
reverse() Reverses the order of the list fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
sort() Sorts the list cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
46 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
print(cars)
List Comprehension
It is a one line for loop that produce python list data structure. It is complete substitute for
labda function as well as function map(),filter() & reduce function.
Syntax
newlist = [expression for item in iterable if condition == True]
e.g 1
Where
The expression is the current item in the iteration
fruits=["apple", "banana", "cherry", "kiwi", "mango"]
newlist=[x for x in fruits if "a" in x]
print(newlist)
o/p["apple", "banana", "mango"]
e.g 2
newlist = [x for x in range(10)]
print(newlist)
o/p
[0,1,2,3,4,5,6,7,8,9]
Q Python Tuple
47 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
1. Tuples are used to store multiple items in a single variable.
2. Tuples are written with round brackets.
3. A tuple is a is ordered collection & immutable(The value of the items stored in
the tuple cannot be changed after tuple has been created)
4. It allowed duplicate
Syntax
tupleame=(value1, value2,…..valuen)
e.g
tuple=("apple", "banana", "cherry")
print(tuple)
o/p
(‘apple’, ‘banana’, ‘cherry’)
Display tuple using loop
t=("apple", "banana", "cherry")
for i in range(len(t)):
print(t[i])
Or
t = ("apple", "banana", "cherry")
for x in t:
print(x)
Accessing Element in Tuple
Tuple index
e.g
tuple=("apple", "banana", "cherry")
print(tuple[1]) o/p=>bannan
48 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
print(tuple[-1]) o/p=>cherry
Slicing
e.g
t = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(t[2:5]) ➔ o/p (‘cherry’, ‘orange’, ‘kiwi’)
print(t[:4]) o/p=>(‘apple’,’banana’,’cherry’,’orange’)
print(t[2:]) o/p=>(‘cherry’,’kiwi’,’melon’,’mango’)
print(t[-4:-1]) o/p=>(‘orange’,’kiwi’,’melon’)
Update Tuple
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
It can convert the tuple into a list, change the list, and convert the list back into a tuple
Add Items
thistuple=("apple", "banana", "cherry")
y= list(thistuple)
y.append("orange")
thistuple= tuple(y)
o/p (‘apple’, ‘banana’, ‘cherry’, ’orange’)
Update Items
x=("apple", "banana", "cherry")
y= list(x)
y[1]= "kiwi"
49 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
x= tuple(y)
print(x)
o/p(‘apple’, ‘kiwi’, ‘cherry’)
Remove Item
thistuple=("apple", "banana", "cherry")
y= list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
o/p(‘banana’, ‘cherry’)
Basic Tuple operations
The operators like concatenation (+), repetition (*), Membership (in) works in the same way
as they work with the list. Consider the following table for more detail.
Let's say Tuple T1 = (1, 2, 3, 4, 5) and Tuple T2 = (6, 7, 8, 9) are declared.
Operator Description Example
Repetition The repetition operator enables the tuple
elements to be repeated multiple times.
T2=T1*2
(1, 2, 3, 4, 5, 1,
2, 3, 4, 5)
Concatenation It concatenates the tuple mentioned on
either side of the operator.
T3=T1+T2
o/p
(1, 2, 3, 4, 5, 6, 7,
8, 9)
50 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Membership It returns true if a particular item exists
in the tuple otherwise false
print (2 in T1)
prints True.
Iteration The for loop is used to iterate over the
tuple elements.
for i in T1:
print(i)
Output
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
Build In function
Sr.No. Function with Description Eg
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
It return following result
If T1>T2 return(1)
If T1=T2 return(0)
If T1<T2 return(-1)
list1 = [ 1, 2, 4, 3]
list2 = [ 1, 2, 5, 8]
list3 = [ 1, 2, 5, 8, 10]
list4 = [ 1, 2, 4, 3]
print cmp(list2, list1) o/p 1
print cmp(list2, list3) o/p -1
print cmp(list4, list1) o/p 0
51 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
2 len(tuple)
Gives the total length of the tuple.
t(1,2,3)
print len(t) o/p 3
3 max(tuple)
Returns item from the tuple with max
value.
t(1,2,3)
print max(t) o/p 3
4 min(tuple)
Returns item from the tuple with min
value.
t(1,2,3)
print min(t) o/p 1
5 tuple(seq)
Converts a list into tuple.
aList = [123, 'xyz', 'zara', 'abc']
aTuple = tuple(aList)
print aTuple
o/p
(123,’xyz’,’zara’)
Q.Set
• Sets are used to store multiple items in a single variable.
• A set is a collection which is both unordered and unindexed.
• Sets are written with curly brackets { }.
• It doesn’t allowed duplicate value
• It is mutable(The value of the items stored in the set can be changed after set has been
created)
Syntax
tupleame={value1, value2,…..valuen}
52 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
thisset = {"apple", "banana", "cherry"}
print(thisset)
o/p {‘apple’, ‘cherry’, ’banana’}
Display Set using loop
thisset={"apple", "banana", "cherry"}
for x in thisset:
print(x)
Update Set
1.Add Item
thisset={"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
2.To add items from another set into the current set, use the update() method.
thisset={"apple", "banana", "cherry"}
tropical={"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
3.To remove item using discard method
thisset={"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
53 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
4 To remove all item using clear method
thisset={"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Set Operation (Union, Intersection, Difference Symmetric )
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference means it contain both sets but not in intersection
print("Symmetric difference :", A ^ B)
0,6,8,1,3,5
o/p
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
Symmetric difference : {0, 1, 3, 5, 6, 8}
54 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Q.Dictionaries
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection is unordered,
• It is changeable(mutable)
• It does not allow duplicates.
• Dictionaries are written with curly brackets{}, and have keys and values
Syntax
Dictionary name = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
e.g
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
o/p
{ "brand": "Ford", "model": "Mustang", "year": 1964}
55 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Loop Through a Dictionary
1. Print all key names in the dictionary, one by one
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
2.Print all values in the dictionary, one by one
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thislist[x])
3.both keys and values, by using the items() method:
for x,y in thisdict.items():
print(x, y)
Access Value from Dictionary
thisdict ={
"brand": "Ford",
"model": "Mustang",
56 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
"year": 1964
}
print ("thisdict[brand]:",thisdict["brand"]);
print ("thisdict[model]:",thisdict["model"]);
print ("thisdict[year]:",thisdict["year"]);
Update Dictionary
1.Add a Item
thisdict ={ "brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
2.Update Item
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
3.Remove Item
1.Using del method
57 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
thisdict= {
"brand": "Ford", "model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
2.The del keyword can also delete the dictionary completely
thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict)
2.The clear() method empties the dictionary
thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
o/p {}
3. The pop() method removes the item with the specified key name
Thisdict {
"brand": "Ford",
"model": "Mustang",
58 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
"year": 1964
}
thisdict.pop("model")
print(thisdict)
4.The popitem() method removes the last inserted item
thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
copy()
Returns a copy of the dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
items()
Return the dictionary's key-value pairs
car={
"brand": "Ford",
59 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
"model": "Mustang",
"year": 1964
}
x=car.items()
print(x)
get()
Returns the value of the specified key
car={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x=car.get("model")
print(x)
setdefault()
Returns the value of the specified key. If the key does not exist: insert the key, with the specified
value
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
keys()
60 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Returns a list containing the dictionary's keys
car={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x=car.keys()
print(x)
OR
for x in car.keys():
print(x)
values()
Returns a list of all the values in the dictionary
car={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x=car.values()
print(x)
OR
for x in thisdict.values():
print(x)
Q.Python Functions
• A function is a block of code which only runs when it is called.
61 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
• It can pass data, known as parameters, into a function.
• A function can return data as a result
Syntax
Python provides the def keyword to define the function
def functionname(parameters):
function_block
return expression
e.g 1
def display():
print("hello world")
display() # calling function
e.g 3
def sum(a,b):
c=a+b;
return c;
a = 10
b = 20
print("The sum is:",sum(a,b)) # calling sum() function in print statement
Function Argument
There are 2 ways passing argument to the function
1.Call by Reference
It pass as address as parameter to the function
def change_list(list1):
list1.append(20)
62 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
list1.append(30)
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]
#calling the function
change_list(list1)
print("list outside function = ",list1)
o/p list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
2. Call By value
It pass as value as parameter to the function
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
1.Required arguments
• Required arguments are the argument passed to a function in correct positional order.
• No. of argument of the function call should match exactly with function definition
def calculate(a,b):
return a+b
63 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
calculate(10,20)
2.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.
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme("john")
3.Keyword arguments
• Python allows us to call the function with the keyword Arguments(key = value).
• 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(message="hello", name = "amit")
**kwargs
Python provides the facility to pass the multiple keyword arguments which can be
represented as **kwargs.
def food(**kwargs):
print(kwargs)
food(fruits="Orange", Vagitables="Carrot")
o/p
64 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
{'fruits': 'Orange', 'Vagitables': 'Carrot'}
Rules
• positional argument after keyword arguments will result in errors.
e.g
greet(name="amit","How do you do?")
• Non Default argument must present before default argument in function header
def greet(msg = "Good morning!", name): =➔error
4.Variable-length Arguments (*args)
The variable-length arguments can pass any number of arguments.
Syntax
*<variable - name >
def printme(*names):
print(names)
printme("john","David","smith","nick")
Scope of variables
The variables are defined with the two types of scopes.
1. Global variables: variables declared inside the function known as Global Variable.
X=300;
def myfunc():
global x;#if not declared global keyword then it consider local
65 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
x= 200;
print(x);
myfunc()
print(x)
2. Local variables: variables declared outside the function known as Global Variable.
def myfunc():
x= 300
print(x)
myfunc()
Recursion
It is mechanism to calling itself known as recursion.
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
n=3;
f=factorial(n);
print(f);
Anonymous Function
• A function without name known as anonymous function.
• In Python anonymous function define by using Lambda function
• A lambda function can take any number of arguments, but can only have one
expression.
66 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Syntax
lambda arguments : expression
e.g 1
x= lambda a:a+ 10
print(x(5))
e.g 2
x= lambda a,b,c:a+b+c
print(x(5, 6, 2))
e.g 3 : Using if-else
Syntax
lambda x : True if (condtion) else False
x=lambda n:"no is positive" n>0 else "no is negative"
print(x(5)
67 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Function Programming Tools
(filter(),map(),reduce())
Map()
The map() function in Python takes in a function and a list as an argument. The function is
called with a lambda function and a list and a new list is returned which contains all the
lambda modified items returned by that function for each item
Syntax
Map(finction,list)
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2, li))
print(final_list)
o/p
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Filter()
The filter() function in Python takes in a function and a list as arguments. This offers an
elegant way to filter out all the elements of a sequence “sequence”, for which the function
returns True.
Syntax
Filter(function,list)
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)
o/p
[5, 7, 97, 77, 23, 73, 61]
68 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Reduce()
The reduce() function in Python takes in a function and a list as an argument. The function
is called with a lambda function and an iterable and a new reduced result is returned. This
performs a repetitive operation over the pairs of the iterable. The reduce() function belongs
to the functools module.
Syntax
reduce(function, sequence[, initial])
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)
o/p 193
Q.Python Classes/Objects
Python is also an object-oriented language.
It support following features
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Creation of class & object
Syntax
69 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
class ClassName:
<statement-1>
.
.
<statement-N>
Syntax
Objectname=classname(aguments)
e.g 1
class Person:
def __init__(self):#constrcutor
self.name=“amol”
self.age = 36
def myfunc(self):
print("name is " + self.name)
print("age is " + self.age)
p1=Person() #instance_creation
print(p1.name)
print(p1.age)
e.g 2
class Person:
def __init__(self,name,age): #constrcutor
self.name=name
self.age = age
def myfunc(self):
print("name is " + self.name)
print("age is " + self.age)
p1=Person("amol", 36) #instance creation
70 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
print(p1.name)
print(p1.age)
self parameter
• The self parameter is a reference to the current instance of the class and It is used
to access attribute of the class.
• It has to be the first parameter of any function in the class.
• Python will automatically send a reference to the instance. It can capture the of the
instance with any variable name(self).
Constructor
• A constructor is a special type of method (function) that is called automatically
whenever an object of that class is created.
• A constructor is a special type of method (function) which is used to initialize the
instance members of the class.
• The name of constructor is always name _init()_
• Constructors can be of non-parametrized & parameterized.
e.g
1.non-parametrized
class Person:
def __init__(self): #constrcutor
self.name=“amol”
self.age = 36
p1 = Person()
e.g
2 parameterized
71 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
class Person:
def __init__(self,name,age): #constrcutor
self.name=name
self.age = age
p1 = Person("amol", 36)
Garbage collection
• Python deletes unwanted objects (built-in types or class instances) automatically to free
the memory space. The process by which Python periodically frees and reclaims blocks
of memory that no longer are in use is called Garbage Collection.
• Python's garbage collector runs during program execution when an object's reference
count reaches zero.
• An object's reference count increases when it is assigned a new name or placed value.
The object's reference count decreases when it's deleted with del, its reference is
reassigned, or its reference goes out of scope. When an object's reference count reaches
zero, Python collects it automatically.
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
d=b # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
d=none # Decreases ref. count of <40>
Destructor
• The __del__() method is a known as a destructor method in Python.
• when the object is destroyed, due to garbage collection, then _del_ method is called.
• This method might be used to clean up any non memory resources used by an instance
72 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Syntax
def __del__(self):
# body of destructor
class SomeObj:
def __init__(self):
print('The object is created.')
def __del__(self):
print('The object is destroyed.')
obj1 = SomeObj()
obj2 = obj1
obj3 = obj1
print("Set obj1 to None...")
obj1 = None
print("Set obj2 to None...")
obj2 = None
print("Set obj3 to None...")
obj3 = None
Method Overloading
python does not support method overloading by default. But there are different ways to
achieve method overloading in Python.
The problem with method overloading in Python is that it may overload the methods but can
only use the latest defined method.
def product(a, b):
p = a * b
print(p)
# Second product method
# Takes three argument and print their
# product
73 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
def product(a, b, c):
p = a * b*c
print(p)
# Uncommenting the below line shows an error
# product(4, 5)
# This line will call the second product method
product(4, 5, 5)
Operator Overloading
Python support operator overloading.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point(1, 2)
p2 = Point(2, 3)
p3=p1+p2 #p3=p1.__add__(p2)
print(p3)
74 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
List of special method of operator overloading
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Type of inheritance
1.Single Inheritance: A derived class is inherited from the only one base class known as
Single inheritance .
Syntax
class derived-class(base class):
75 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
<class-suite>
e.g
class A:
def disp1(self):
print("disp1 method in base")
class B(A):
def disp2(self):
print("disp2 method in derived")
ob = B()
ob.disp1()
ob.disp2()
Using Constructor(super keyword)
class A:
def __init__(self,a):
self.a=a
class B(A):
def __init__(self,a,b):
super().__init__(a)
self.b=b
def disp(self):
print("a is",self.a)
print("b is",self.b)
ob=B(1,2)
ob.disp()
2.MultiLevel Inheritance: Multi-level inheritance is archived when a derived class inherits
another derived class.
Syntax
76 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
e.g
class A:
def disp1(self):
print("disp1 method in base")
class B(A):
def disp2(self):
print("disp2 method in derived1")
class C(B):
def disp3(self):
print("disp3 method in derived2")
ob = C()
ob.disp1()
ob.disp2()
ob.disp3()
3.Multiple inheritance: To inherit multiple base classes in the child class known as multiple
inheritance.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
77 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>
e.g
class A:
def disp1(self):
print("disp1 method in base")
class B:
def disp2(self):
print("disp2 method in derived1")
class C(A,B):
def disp3(self):
print("disp3 method in derived2")
ob = C()
ob.disp1()
ob.disp2()
ob.disp3()
Hierarchical Inheritance
Hierarchical inheritance involves more then derived classes derived from the single base or
parent class.
class A:
def disp1(self):
print("disp1 method in base")
class B(A):
def disp2(self):
A
C
B
78 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
print("disp2 method in derived1")
class C(A):
def disp3(self):
print("disp3 method in derived2")
ob1 = B()
ob1.disp1()
ob1.disp2()
ob2=C()
ob2.disp1()
ob2.disp3()
79 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Base Class Constructor
80 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Access Specifier
81 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
public(By
Deafult)
The members
declared as Public
are accessible
from outside the
Class through an
object of the class
class Student:
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
class Result(Student):
def disp(self):
print("rollno is ",self.rollno)
print("name is ",self.name)
ob=Result(1,"om")
ob.disp()
Private
__(Double
underscore) to
a variable
name makes
it private
The members
declared as
Protected are
accessible from
outside the class
but only in a class
derived from it
that is in the child
or subclass
class Student:
def __init__(self,rollno,name):
self.__rollno=rollno
self.__name=name
class Result(Student):
def disp(self):
print("rollno is ",self.__rollno)
print("name is ",self.__name)
ob=Result(1,"om")
ob.disp()
o/p error
Protected
_(single
underscore) to
a variable
name makes
it protected
These members
are only accessible
from within the
class. No outside
Access is allowed.
class Student:
def __init__(self,rollno,name):
self._rollno=rollno
self._name=name
class Result(Student):
def disp(self):
print("rollno is ",self._rollno)
print("name is ",self._name)
ob=Result(1,"om")
ob.disp()
82 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Method Overriding
When the parent class method is redefined in their child class with same name with same
prototype, then the concept is called method overriding.
class A:
def func1(self):
print("this is function 1")
class B(A):
def func1(self):
super().func1()
print("this is function 2")
ob = B()
ob.func1()
Python Exception
Definition:
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.
List of Standard Exceptions −
Sr.No. Exception Name & Description
1 Exception
Base class for all exceptions
2 StopIteration
Raised when the next() method of an iterator does not point to any
object.
3 SystemExit
Raised by the sys.exit() function.
83 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
4 StandardError
Base class for all built-in exceptions except StopIteration and
SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric
types.
9 AssertionError
Raised in case of failure of the Assert statement.
10 AttributeError
Raised in case of failure of attribute reference or assignment.
11 EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12 ImportError
Raised when an import statement fails.
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
14 LookupError
Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
84 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
16 KeyError
Raised when the specified key is not found in the dictionary.
17 NameError
Raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or method
but no value has been assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python
environment.
20 IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that does
not exist.
21 IOError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.
24 SystemError
Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function.
If not handled in the code, causes the interpreter to exit.
26 TypeError
Raised when an operation or function is attempted that is invalid for
the specified data type.
85 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
27 ValueError
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.
Handling an exception
The try: block contains one or more statements which are likely to encounter an exception.
If the statements in this block are executed without an exception, the subsequent except:
block is skipped.
If the exception does occur, the program flow is transferred to the except: block.
The else keyword to define a block of code to be executed if no errors were raised
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
e.g
try:
86 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("Division by 0 not accepted")
else:
print("else block")
e.g 2 Handles all types of exception
try:
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except Exception:
print("Division by 0 not accepted")
else:
print("else block")
except Clause with Multiple Exceptions
Syntax
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
e.g
try:
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except (ArithmeticError,ZeroDivisionError):
print("Division by 0 not accepted")
else:
print("else block")
87 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Finally Block
The finally block, if specified, will be executed regardless if the try block raises an error or not.
Syntax
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
e.g
try:
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("Division by 0 not accepted")
finally:
print("finally block")
Raise an exception
Python also provides the raise keyword to be used throw an exception to be explicitly.
Syntax
raise [Exception [, args]
Where
Exception :It is the type of exception (for example, NameError)
Argument: It is a value for the exception argument.
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
88 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
User-defined Exceptions
e.g
class Myerror(Exception):
def __init__(self,arg):
self.arg=arg
try:
n=int(input("enter value"))
if(n<0):
raise Myerror("no is negative")
else:
print("postive value")
except Myerror as e:
print (e.arg)
89 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
Q.Python 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
module to be the same as a code library
To creation of User Defined package
1.To create module
def show(name):
print("Hello, " + name)
Note: save as mymodule.py
2. The import Statement
It can use any Python source file as a module by executing an import statement in some other
Python source file.
syntax −
import module1[, module2[,... moduleN]
import mymodule
mymodule.show("om")
e.g To add some part in above module
90 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
person1={
"name": "om",
"age": 22,
"country": "india"
}
save above code in mymodule.py
import mymodule
a=mymodule.person1["age"]
print(a)
Import From Module
It can choose to import only parts from a module, by using the from keyword.
from modname import name1[, name2[, ... nameN]]
def show(name):
print("Hello," +name)
person1={
"name": "om",
"age": 22,
"country": "india"
}
Import only the person1 dictionary from the module
91 Vision Academy Since 2005
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT)
Python Notes
http://www.visionacademe.com
from mymodule import person1
print (person1["age"])
from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement
from mymodule import *
print (person1["age"])
show("om")
Re-naming a Module
It can create an alias when it import a module, by using the as keyword
import mymodule as mx
a=mx.person1["age"]
print(a)
Pre defined module
import calendar
cal = calendar.month(2021, 1)
print ("Here is the calendar:")
print (cal)
#current date & time
import datetime
x = datetime.datetime.now()
print(x)

Weitere ähnliche Inhalte

Ähnlich wie Python_final_print_batch_II_vision_academy.pdf

intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdfANIKULSAIKH
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSCisco Russia
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1Kanchilug
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyTIB Academy
 
Python Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechPython Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechRamanamurthy Banda
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Why Python in required in Civil Engineering
Why Python in required in Civil EngineeringWhy Python in required in Civil Engineering
Why Python in required in Civil EngineeringRushikesh Kolhe
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
 
The main Python implementation, named CPython, is written in C meeti.pdf
The main Python implementation, named CPython, is written in C meeti.pdfThe main Python implementation, named CPython, is written in C meeti.pdf
The main Python implementation, named CPython, is written in C meeti.pdfanudamobileshopee
 
Final presentation on python
Final presentation on pythonFinal presentation on python
Final presentation on pythonRaginiJain21
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-pythonYuvaraja Ravi
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data sciencebhavesh lande
 

Ähnlich wie Python_final_print_batch_II_vision_academy.pdf (20)

intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OS
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Summer Training Project.pdf
Summer Training Project.pdfSummer Training Project.pdf
Summer Training Project.pdf
 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
python unit2.pptx
python unit2.pptxpython unit2.pptx
python unit2.pptx
 
Python Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechPython Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & Tech
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Why Python in required in Civil Engineering
Why Python in required in Civil EngineeringWhy Python in required in Civil Engineering
Why Python in required in Civil Engineering
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
The main Python implementation, named CPython, is written in C meeti.pdf
The main Python implementation, named CPython, is written in C meeti.pdfThe main Python implementation, named CPython, is written in C meeti.pdf
The main Python implementation, named CPython, is written in C meeti.pdf
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Final presentation on python
Final presentation on pythonFinal presentation on python
Final presentation on python
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data science
 

Kürzlich hochgeladen

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 

Kürzlich hochgeladen (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 

Python_final_print_batch_II_vision_academy.pdf

  • 1. 1 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com History: Python is a widely used general-purpose, high level programming scripting language. It was created by Guido van Rossum in 1991 Q.Python Features 1) Easy to Learn and Use Python is easy to learn as compared to other programming languages. Its syntax is straightforward and much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended programming language for beginners. 2) Interpreted Language Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being interpreted language, it makes debugging easy and portable. 3) Cross-platform Language Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop the software for several competing platforms by writing a program only once 4) Free and Open Source Python is freely available for everyone. It is freely available on its official website www.python.org. 5) Object-Oriented Language Python supports object-oriented language and concepts of classes and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to programmer to write reusable code and develop applications in less code. 6) GUI Programming Support Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application 7) Dynamic Memory Allocation
  • 2. 2 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com In Python, we don't need to specify the data-type of the variable. When we assign some value to the variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15. 8) Embeddable The code of the other programming language can use in the Python source code. It can use Python source code in another programming language as well. Q.Comparing C,C++,Python C C++ Python C was developed by Dennis Ritchie between the year 1969 and 1973 at AT&T Bell Labs. C++ was developed by Bjarne Stroustrup in 1979. Python was created by Guido van Rossum, and released in 1991. More difficult to write code in contrast to both Python and C++ due to complex syntax. C++ code is less complex than C but more complex in contrast to python. Easier to write code. Longer lines of code as compared to python. Longer lines of code as compared to python. 3-5 times shorter than equivalent C/C++ programs. Variables are declared in C. Variables are declared in C++ Python has no declaration. C is a compiled language. C++ is a compiled language. Python is an interpreted language. C contains 32 keywords. C++ contains 52 keywords. Python contains 33 keywords. For the development of code, C supports procedural programming. C++ is known as hybrid language because C++ supports both procedural Python supports multiple programming paradigms, including procedural, object-
  • 3. 3 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com C C++ Python and object oriented programming paradigms. oriented, and functional programming. C does not support inheritance. C++ support both single and multiple inheritance Python supports all 5 types of inheritance i.e. single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance, and hybrid inheritance C provides malloc() and calloc() functions for dynamic memory allocation, and free() for memory de-allocation. C++ provides new operator for memory allocation and delete operator for memory de- allocation. Python’s memory allocation and deallocation method is automatic. Direct support for exception handling is not supported by C. Exception handling is supported by C++. Exception handling is supported by Python. Different Types Of extension Python scripts may have one of several file extensions. Each file extension has a special meaning and purpose. • *.py - Regular scripts • *.py3 - (rarely used) Python3 script; Python3 scripts usually end with "*.py" not "*.py3" • *.pyc - compiled script (Bytecode)
  • 4. 4 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com • *.pyo - optimized pyc bytecode file (As of Python3.5, Python will only use pyc rather than pyo and pyc) • *.pyw - Python script for Windows that is executed with pythonw.exe • *.pyx - Cython src to be converted to C/C++ • *.pyd - Python script made as a Windows DLL Q.Application of Phyton 1) Web Applications We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
  • 5. 5 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python provides many useful frameworks, and these are given below: o Django and Pyramid framework(Use for heavy applications) o Flask and Bottle (Micro-framework) o Plone and Django CMS (Advance Content management) 2) Desktop GUI Applications The GUI stands for the Graphical User Interface, which provides a smooth interaction to any application. Python provides a Tk GUI library to develop a user interface. Some popular GUI libraries are given below. o Tkinter or Tk o wxWidgetM o Kivy (used for writing multitouch applications ) o PyQt or Pyside 3) Console-based Application Console-based applications run from the command-line or shell. These applications are computer program which are used commands to execute. This kind of application was more popular in the old generation of computers. Python can develop this kind of application very effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for the command-line applications. Python provides many free library or module which helps to build the command-line apps. The necessary IO libraries are used to read and write. It helps to parse argument and create console help text out-of-the-box. There are also advance libraries that can develop independent console apps. 4) Software Development Python is useful for the software development process. It works as a support language and can be used to build control and management, testing, etc. o SCons is used to build control.
  • 6. 6 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com o Buildbot and Apache Gumps are used for automated continuous compilation and testing. o Round or Trac for bug tracking and project management. 5) Scientific and Numeric This is the era of Artificial intelligence where the machine can perform the task the same as the human. Python language is the most suitable language for Artificial intelligence or machine learning. It consists of many scientific and mathematical libraries, which makes easy to solve complex calculations. Implementing machine learning algorithms require complex mathematical calculation. Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some basic knowledge of Python, you need to import libraries on the top of the code. Few popular frameworks of machine libraries are given below. o SciPy o Scikit-learn o NumPy o Pandas o Matplotlib 6) Business Applications Business Applications differ from standard applications. E-commerce and ERP are an example of a business application. This kind of application requires extensively, scalability and readability, and Python provides all these features. Oddo is an example of the all-in-one Python-based application which offers a range of business applications. Python provides a Tryton platform which is used to develop the business application. 7) Audio or Video-based Applications Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The few multimedia libraries are given below. o Gstreamer
  • 7. 7 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com o Pyglet o QT Phonon 8) 3D CAD Applications The CAD (Computer-aided design) is used to design engineering related architecture. It is used to develop the 3D representation of a part of a system. Python can create a 3D CAD application by using the following functionalities. o Fandango (Popular ) o CAMVOX o HeeksCNC o AnyCAD o RCAM 9) Enterprise Applications Python can be used to create applications that can be used within an Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc. 10) Image Processing Application Python contains many libraries that are used to work with the image. The image can be manipulated according to our requirements. Some libraries of image processing are given below. • OpenCV • Pillow • SimpleITK Disadvantages of Python 1. Slow Speed Python is an interpreted language and dynamically-typed language. The line by line execution of code often leads to slow execution. 2. Not Memory Efficient
  • 8. 8 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com To provide simplicity to the developer, Python has to do a little tradeoff. The Python programming language uses a large amount of memory. This can be a disadvantage while building applications when we prefer memory optimization. 3. Weak in Mobile Computing Python is generally used in server-side programming. It don’t get to see Python on the client-side or mobile applications because of the following reasons. Python is not memory efficient and it has slow processing power as compared to other languages. 4. Database Access Programming in Python is easy and stress-free. But when it are interacting with the database, it lacks behind. The Python’s database access layer is primitive and underdeveloped in comparison to the popular technologies like JDBC and ODBC. Huge enterprises need smooth interaction of complex legacy data and Python is thus rarely used in enterprises. 5. Runtime Errors Python is a dynamically typed language so the data type of a variable can change anytime. A variable containing integer number may hold a string in the future, which can lead to Runtime Errors. Therefore Python programmers need to perform thorough testing of the applications. Q. First Program In Python 1. >>> print("Hello, World!") o/p Hello, World!
  • 9. 9 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com OR Save above file p.py Run =>python p.py Q. Python Identifiers An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another. Rules for writing identifiers 1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example. 2. An identifier cannot start with a digit. 3. Keywords cannot be used as identifiers. 4. An identifier can be of any length. 5. Python is a case-sensitive language. This means, Variable and variable are not the same. Valid Identifier Salay, sum_sal etc Q.Python Keywords • Keywords are the reserved words in Python.
  • 10. 10 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com • It cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. • In Python, keywords are case sensitive. • There are 33 keywords in Python 3.7. This number can vary slightly over the course of time. • All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below. False await else import pass None break except in raise True class finally is return And continue For lambda try As def from nonlocal while Assert del global not with Async elif if or yield
  • 11. 11 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Q.Python Comments 1. Single Line Comment It is used to single line comment by using # e.g #print("Hello,World!") 2. Multi line comment It is used to “”” (tripal quotes) e.g """ This is python This is Java """ Q.Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation. Indentation refers to the spaces at the beginning of a code line. Python uses indentation to indicate a block of code. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount Note: 1.Semicolon at the end of statement is optional 2.Instead of {},indentations are used to represent block
  • 12. 12 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com For e.g 1:valid if condtion: statement statement For e.g 2 : invalid if condtion: statement statement else: statement statement Multi-Line Statements Explicit Line Continuation • Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character () to denote that the line should continue. For example − total = item_one + item_two + item_three Implicit Line continuation • Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example − days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] Q.Variables Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. x=5
  • 13. 13 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com y=”vision” print(x) print(y) type() Get the data type of a variable with the type() function. x= 5 y= "John" print(type(x))o/p===➔<class=’int’> print(type(y)) /p===➔<class 'str'> Q.Data Type Python supports three types of numeric data. 1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the length of an integer. Its value belongs to int e.g. x = 20
  • 14. 14 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal points. e.g. x = 20.5 3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc. e.g x = 1j Q.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 • Python Arithmetic Operators Arithmetic operators Operator Name Example + Addition x + y
  • 15. 15 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y Assignment Operators Operator Example Same As = 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 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3
  • 16. 16 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com <<= x <<= 3 x = x << 3 Comparison Operators Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y Python Logical Operators Operator Description Example and Returns True if both statements are true x < 5 and x < 10 Or Returns True if one of the statements is true x < 5 or x < 4 Not Reverse the result, returns False if the result is true not(x < 5 and x < 10) Python 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:
  • 17. 17 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Python Membership Operators Membership operators are used to test if a sequence is presented in an object: Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y Python Bitwise Operators Bitwise operators are used to compare (binary) numbers: Operator Name & AND | OR ^ XOR Operator Description Example is Returns true if both variables are the same object x is y is not Returns true if both variables are not the same object x is not y
  • 18. 18 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com ~ NOT << Zero fill left shift >> Signed right shift Data Type Conversion Sr.No. Function & Description 1 int(x[,base]) Converts x to an integer. base specifies the base if x is a string. 2 long(x[,base]) Converts x to a long integer. base specifies the base if x is a string. 3 float(x) Converts x to a floating-point number. 4 complex(real[,imag]) Creates a complex number. 5 str(x) Converts object x to a string representation. 6 repr(x) Converts object x to an expression string.
  • 19. 19 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Sr.No. Function & Description 7 eval(str) Evaluates a string and returns an object. 8 tuple(s) Converts s to a tuple. 9 list(s) Converts s to a list. 10 set(s) Converts s to a set. 11 dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. 12 frozenset(s) Converts s to a frozen set. 13 chr(x) Converts an integer to a character. 14 unichr(x) Converts an integer to a Unicode character. 15 ord(x) Converts a single character to its integer value. 16 hex(x) Converts an integer to a hexadecimal string.
  • 20. 20 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Sr.No. Function & Description 17 oct(x) Converts an integer to an octal string. Q.print Function The print() function prints the specified message to the screen, or other standard output device. Syntax print(object(s), sep=separator, end=end, file=file, flush=flush) Parameter Values Parameter Description object(s) Any object, and as many as you like. Will be converted to string before printed sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' ' end='end' Optional. Specify what to print at the end. Default is 'n' (line feed) File Optional. An object with a write method. Default is sys.stdout Flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
  • 21. 21 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com e.g 1.print("Hello", "how are you?") 2.c=4 print('value is', c) o/p==➔value is c 3.b = "for" print("Geeks", b , "Geeks") o/p===➔Greeks for Greeks 4.print(1,2,3,4) o/p=➔1 2 3 4 5.print(1,2,3,4,sep=’#’,end=’&’) o/p➔1#2#3#4& 6.print(1,2,3,4,sep=’*’) o/p➔1*2*3*4 Q.input function The input() function allows user input. Syntax input(prompt) Where prompt=>A string, representing default message before input
  • 22. 22 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com e.g x = input('”enter value'”) print('”Hello”,x) Addition of two nos a = input('enter value1') b=input('enter value2') c=int(a)+int(b) print('addition is',c) Q.Control Statement 1.condtional statement 1.if statement Syntax if boolean-expression: #statements e.g a= 33 b= 200 if b>a: print("b is greater than a") 2.if-else statement Syntax if boolean-expression:
  • 23. 23 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com #statements else: #statements e.g i = 10 if i % 2 == 0: print("Number is even") else: print("Number is odd") 3. Nested if-elif Syntax if boolean-expression: #statements elif boolean-expression: #statements elif boolean-expression: #statements elif boolean-expression: #statements else: #statements e.g 1. a= 200 b= 33 if b>a: print(“bismax”) elif a==b: print("aandbareequal") else: print("a is greater than b")
  • 24. 24 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com e.g 2 x= 41 if x> 10: print("Aboveten,") if x> 20: print("andalsoabove20!") else: print("but not above 20.") Loop 1. While Syntax while expression: statement(s) e.g count = 0 while (count < 9): print 'The count is:', count count = count + 1 2.For loop Syntax for iterating_var in sequence: statements(s) e.g for ch in 'vision': print 'Current Letter :', ch
  • 25. 25 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. Syntax range(start, stop, step) Parameter Description Start Optional. An integer number specifying at which position to start. Default is 0 Stop Required. An integer number specifying at which position to stop (not included). Step Optional. An integer number specifying the incrementation. Default is 1 x= range(3, 6) for n in x: print(n) o/p 3 4 5
  • 26. 26 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com x= range(3, 10, 2) for n in x: print(n) o/p 3 5 7 9 Using Else Statement in loop for x in range(6): print(x) else: print("Fi+inally finished!") o/p 0 1 2 3 4 5 finallyfinished Break & Continue Statement 1. i= 1 while i< 6: print(i) if i== 3:
  • 27. 27 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com break i = i+1 2. i= 0 while i< 6: i+= 1 if i== 3: continue print(i) Pass statement pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation. The pass statement is generally used as a placeholder i.e. when the user does not know what code to write. So user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code to execute. So user simply places pass there as empty code. Empty code is not allowed in loops, function definitions, class definitions, or in if statements. So using pass statement user avoids this error. e.g 1. a = 33 b = 200 if b > a: pass print("pass statement") 2.
  • 28. 28 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com def myfunction(): pass Note: The pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. Q.Math Function List of Functions in Python Math Module Function Description ceil(x) Returns the smallest integer greater than or equal to x. copysign(x, y) Returns x with the sign of y fabs(x) Returns the absolute value of x factorial(x) Returns the factorial of x floor(x) Returns the largest integer less than or equal to x fmod(x, y) Returns the remainder when x is divided by y frexp(x) Returns the mantissa and exponent of x as the pair (m, e) fsum(iterable) Returns an accurate floating point sum of values in the iterable isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number) isinf(x) Returns True if x is a positive or negative infinity
  • 29. 29 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com isnan(x) Returns True if x is a NaN ldexp(x, i) Returns x * (2**i) modf(x) Returns the fractional and integer parts of x trunc(x) Returns the truncated integer value of x exp(x) Returns e**x expm1(x) Returns e**x - 1 log(x[, b]) Returns the logarithm of x to the base b (defaults to e) log1p(x) Returns the natural logarithm of 1+x log2(x) Returns the base-2 logarithm of x log10(x) Returns the base-10 logarithm of x pow(x, y) Returns x raised to the power y sqrt(x) Returns the square root of x acos(x) Returns the arc cosine of x asin(x) Returns the arc sine of x atan(x) Returns the arc tangent of x atan2(y, x) Returns atan(y / x) cos(x) Returns the cosine of x hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
  • 30. 30 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com sin(x) Returns the sine of x tan(x) Returns the tangent of x degrees(x) Converts angle x from radians to degrees radians(x) Converts angle x from degrees to radians acosh(x) Returns the inverse hyperbolic cosine of x asinh(x) Returns the inverse hyperbolic sine of x atanh(x) Returns the inverse hyperbolic tangent of x cosh(x) Returns the hyperbolic cosine of x sinh(x) Returns the hyperbolic cosine of x tanh(x) Returns the hyperbolic tangent of x erf(x) Returns the error function at x erfc(x) Returns the complementary error function at x gamma(x) Returns the Gamma function at x lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x Pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...) E mathematical constant e (2.71828...) import math
  • 31. 31 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com print(math.pi) Q.String String is sequence of character. String declaration 1.Using Double quotes a=”Hello” print(a) 2.UsingSingleQuotes a=’hello’ print(a) 2.Multiline Strings You can assign a multiline string to a variable by using three quotes: 1.Using 3 double quotes a= """visionacademy, classesforbcs/bca/bba.""" print(a) 2.Using 3 Single quotes a= '''visionacademy,classesforbcs/bca/bba.''' print(a) Representations of String
  • 32. 32 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com • Strings are stored individual character in contiguous location • It can access from both direction (forward & backward) • Both forward & backword indexing are provided using string in python Forward indexing start with 0,1,2,3,… Backward indexing start with -1,-2,-3…….. Escape Characters Code Result ' Single Quote Backslash n New Line r Carriage Return t Tab b Backspace f Form Feed ooo Octal value xhh Hex value
  • 33. 33 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com e.g txt = "HellonWorld!" print(txt) Slicing a String If S is a string, the expression S [ start : stop : step ] returns the portion of the string from index start to index stop, at a step size step. Syntax Basic Example Here is a basic example of string slicing. S = ' A B C D E F G H I ' print(S[2:7]) # C D E F G
  • 34. 34 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Note that the item at index 7 'H' is not included. Slice with Negative Indices You can also specify negative indices while slicing a string. S = ' A B C D E F G H I ' print(S[-7:-2]) # C D E F G Slice with Positive & Negative Indices You can specify both positive and negative indices at the same time.
  • 35. 35 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com S = ' A B C D E F G H I ' print(S[2:-5]) # C D Specify Step of the Slicing You can specify the step of the slicing using step parameter. The step parameter is optional and by default 1. # Return every 2nd item between position 2 to 7 S = ' A B C D E F G H I ' print(S[2:7:2]) # C E G Negative Step Size You can even specify a negative step size. # Returns every 2nd item between position 6 to 1 in reverse order S = ' A B C D E F G H I ' print(S[6:1:-2]) # G E C Slice at Beginning & End Omitting the start index starts the slice from the index 0. Meaning, S[:stop] is equivalent to S[0:stop] # Slice first three characters from the string S = ' A B C D E F G H I ' print(S[:3]) # A B C
  • 36. 36 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Whereas, omitting the stop index extends the slice to the end of the string. Meaning, S[start:] is equivalent to S[start:len(S)] # Slice last three characters from the string S = ' A B C D E F G H I ' print(S[6:]) # G H I Note: Rules of slicing ============================== IF negative step size given By default start value=>-1 By default end value==> -(len+1) ========================================== if not given step size then it shld consider by default positive(+1) By default start value o By default end value==>length of string ==================================================== IF positive step size given By default start value=> 0 By default end value==> length of string ======================================= s[1:] valid
  • 37. 37 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com String operator String Special Operators Assume string variable a holds 'Hello' and variable b holds 'Python', then − Operator Description Example + Concatenation - Adds values on either side of the operator a + b will give HelloPython * Repetition - Creates new strings, concatenating multiple copies of the same string a*2 will give - HelloHello [] Slice - Gives the character from the given index a[1] will give e [ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell b[2:]=>thon b[:3]=>Pyt b[-4:-2]=>th In Membership - Returns true if a character exists in the given string H in a =>1 not in Membership - Returns true if a character does not exist in the given string M not in a =>1
  • 38. 38 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com % Format - Performs String formatting Build-in String Method Method Description capitalize() Converts the first character to upper case e.g txt= "hello,andwelcometomyworld." x=txt.capitalize() print (x) casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string txt= "Iloveapples,applearemyfavoritefruit" x=txt.count("apple") print(x) encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found txt= "Hello,welcometomyworld." x=txt.find("welcome") print(x) format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found
  • 39. 39 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits txt= "50800" x=txt.isdigit() print(x) isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string lower() Converts a string into lower case txt= "HellomyFRIENDS" x=txt.lower() print(x) lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value
  • 40. 40 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com txt= "Ilikebananas" x=txt.replace("bananas", "apples") print(x) 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 rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list txt= "welcometothejungle" x=txt.split() print(x) splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case txt= "Hellomyfriends" x=txt.upper() print(x) zfill() Fills the string with a specified number of 0 values at the beginning
  • 41. 41 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Q List • A list in Python is used to store the sequence of various types of data. • Python lists are mutable(Its mean it can modify its element after it created). • A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets []. • It allowed duplicate value Syntax Listname=[value1, value2,…..valuen] e.g list1 = ["apple", "banana", "cherry", "apple", "cherry"] list2 = ["abc", 34, True, 40, "male"] print(list1) print(list2) o/p ["apple", "banana", "cherry", "apple", "cherry"] [‘abc’, 34, True, 40, ‘male’] Display List using loop list=["apple", "banana", "cherry"] for i in range(len(list)): print(list[i]) OR list = ["apple", "banana", "cherry"]
  • 42. 42 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com for x in list: print(x) Accessing Element in List List index e.g list1=["apple", "banana", "cherry"] print(list1[1] o/p=>bannan print(list1[-1]) o/p=>cherry Slicing List e.g list1=["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(list1[2:5]) o/p=>[‘cherry’,’orange’,’kiwi’] print(thislist[:4]) o/p=>[‘apple’,’banana’,’cherry’,’orange’] print(thislist[2:]) o/p=>[‘cherry’,’kiwi’,’melon’,’msngo’] print(thislist[-4:-1]) o/p=>[‘orange’,’kiwi’,’melon’] Inserting Item thislist=["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist) o/p=➔[‘apple’, ‘banana’,’watermelon’, "cherry"] Updating List
  • 43. 43 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2] o/p=➔1997 list[2] = 2001; print "New value available at index 2 : " print list[2] o/p➔2001 Change a Range of Item Values thislist=["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3]=["blackcurrant", "watermelon"] print(thislist) o/p[‘apple’,’blackcurrant’,watermelon’,’orange’,’kiwi’,’mango’] thislist=["apple", "banana", "cherry"] thislist[1:2]=["blackcurrant", "watermelon"] print(thislist) o/p[‘apple’,’balckcurrent’,’watermelon’] thislist=["apple", "banana", "cherry"] thislist[1:3]=["watermelon"] print(thislist) o/p [‘apple’,’watermelon’] Remove Item 1.remove():The remove() method removes the specified item.
  • 44. 44 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com list=["apple", "banana", "cherry"] list.remove("banana") print(list) o/p [‘apple’,’cherry’] 2.pop():The pop() method removes the specified index. list=["apple", "banana", "cherry"] list.pop(1) print(list) o/p [‘apple’,’cherry’] If you do not specify the index, the pop() method removes the last item. list=["apple", "banana", "cherry"] list.pop() print(list) o/p [‘apple’,’banana’] 3.Del():The del keyword also removes the specified index list=["apple", "banana", "cherry"] del list[0] print(list) o/p [‘banana’,’cherry’] The del keyword can also delete the list completely. list=["apple", "banana", "cherry"] del list
  • 45. 45 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 4.clear():The clear() method empties the list list = ["apple", "banana", "cherry"] list.clear() print(thislist) Method Description append() Adds an element at the end of the list fruits = ['apple', 'banana', 'cherry'] fruits.append("orange") print(x) copy() Returns a copy of the list fruits = ["apple", "banana", "cherry"] x = fruits.copy() print(x) count() Returns the number of elements with the specified value fruits = ["apple", "banana", "cherry"] x = fruits.count("cherry") print(x) extend() Add the elements of a list (or any iterable), to the end of the current list fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print(fruits) index() Returns the index of the first element with the specified value fruits = ['apple', 'banana', 'cherry'] x = fruits.index("cherry") print(x) o/p 2 reverse() Reverses the order of the list fruits = ['apple', 'banana', 'cherry'] fruits.reverse() print(fruits) sort() Sorts the list cars = ['Ford', 'BMW', 'Volvo'] cars.sort()
  • 46. 46 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com print(cars) List Comprehension It is a one line for loop that produce python list data structure. It is complete substitute for labda function as well as function map(),filter() & reduce function. Syntax newlist = [expression for item in iterable if condition == True] e.g 1 Where The expression is the current item in the iteration fruits=["apple", "banana", "cherry", "kiwi", "mango"] newlist=[x for x in fruits if "a" in x] print(newlist) o/p["apple", "banana", "mango"] e.g 2 newlist = [x for x in range(10)] print(newlist) o/p [0,1,2,3,4,5,6,7,8,9] Q Python Tuple
  • 47. 47 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 1. Tuples are used to store multiple items in a single variable. 2. Tuples are written with round brackets. 3. A tuple is a is ordered collection & immutable(The value of the items stored in the tuple cannot be changed after tuple has been created) 4. It allowed duplicate Syntax tupleame=(value1, value2,…..valuen) e.g tuple=("apple", "banana", "cherry") print(tuple) o/p (‘apple’, ‘banana’, ‘cherry’) Display tuple using loop t=("apple", "banana", "cherry") for i in range(len(t)): print(t[i]) Or t = ("apple", "banana", "cherry") for x in t: print(x) Accessing Element in Tuple Tuple index e.g tuple=("apple", "banana", "cherry") print(tuple[1]) o/p=>bannan
  • 48. 48 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com print(tuple[-1]) o/p=>cherry Slicing e.g t = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(t[2:5]) ➔ o/p (‘cherry’, ‘orange’, ‘kiwi’) print(t[:4]) o/p=>(‘apple’,’banana’,’cherry’,’orange’) print(t[2:]) o/p=>(‘cherry’,’kiwi’,’melon’,’mango’) print(t[-4:-1]) o/p=>(‘orange’,’kiwi’,’melon’) Update Tuple Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. It can convert the tuple into a list, change the list, and convert the list back into a tuple Add Items thistuple=("apple", "banana", "cherry") y= list(thistuple) y.append("orange") thistuple= tuple(y) o/p (‘apple’, ‘banana’, ‘cherry’, ’orange’) Update Items x=("apple", "banana", "cherry") y= list(x) y[1]= "kiwi"
  • 49. 49 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com x= tuple(y) print(x) o/p(‘apple’, ‘kiwi’, ‘cherry’) Remove Item thistuple=("apple", "banana", "cherry") y= list(thistuple) y.remove("apple") thistuple = tuple(y) print(thistuple) o/p(‘banana’, ‘cherry’) Basic Tuple operations The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with the list. Consider the following table for more detail. Let's say Tuple T1 = (1, 2, 3, 4, 5) and Tuple T2 = (6, 7, 8, 9) are declared. Operator Description Example Repetition The repetition operator enables the tuple elements to be repeated multiple times. T2=T1*2 (1, 2, 3, 4, 5, 1, 2, 3, 4, 5) Concatenation It concatenates the tuple mentioned on either side of the operator. T3=T1+T2 o/p (1, 2, 3, 4, 5, 6, 7, 8, 9)
  • 50. 50 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Membership It returns true if a particular item exists in the tuple otherwise false print (2 in T1) prints True. Iteration The for loop is used to iterate over the tuple elements. for i in T1: print(i) Output 1 2 3 4 5 Length It is used to get the length of the tuple. len(T1) = 5 Build In function Sr.No. Function with Description Eg 1 cmp(tuple1, tuple2) Compares elements of both tuples. It return following result If T1>T2 return(1) If T1=T2 return(0) If T1<T2 return(-1) list1 = [ 1, 2, 4, 3] list2 = [ 1, 2, 5, 8] list3 = [ 1, 2, 5, 8, 10] list4 = [ 1, 2, 4, 3] print cmp(list2, list1) o/p 1 print cmp(list2, list3) o/p -1 print cmp(list4, list1) o/p 0
  • 51. 51 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 2 len(tuple) Gives the total length of the tuple. t(1,2,3) print len(t) o/p 3 3 max(tuple) Returns item from the tuple with max value. t(1,2,3) print max(t) o/p 3 4 min(tuple) Returns item from the tuple with min value. t(1,2,3) print min(t) o/p 1 5 tuple(seq) Converts a list into tuple. aList = [123, 'xyz', 'zara', 'abc'] aTuple = tuple(aList) print aTuple o/p (123,’xyz’,’zara’) Q.Set • Sets are used to store multiple items in a single variable. • A set is a collection which is both unordered and unindexed. • Sets are written with curly brackets { }. • It doesn’t allowed duplicate value • It is mutable(The value of the items stored in the set can be changed after set has been created) Syntax tupleame={value1, value2,…..valuen}
  • 52. 52 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com thisset = {"apple", "banana", "cherry"} print(thisset) o/p {‘apple’, ‘cherry’, ’banana’} Display Set using loop thisset={"apple", "banana", "cherry"} for x in thisset: print(x) Update Set 1.Add Item thisset={"apple", "banana", "cherry"} thisset.add("orange") print(thisset) 2.To add items from another set into the current set, use the update() method. thisset={"apple", "banana", "cherry"} tropical={"pineapple", "mango", "papaya"} thisset.update(tropical) print(thisset) 3.To remove item using discard method thisset={"apple", "banana", "cherry"} thisset.discard("banana") print(thisset)
  • 53. 53 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 4 To remove all item using clear method thisset={"apple", "banana", "cherry"} thisset.clear() print(thisset) Set Operation (Union, Intersection, Difference Symmetric ) A = {0, 2, 4, 6, 8}; B = {1, 2, 3, 4, 5}; # union print("Union :", A | B) # intersection print("Intersection :", A & B) # difference print("Difference :", A - B) # symmetric difference means it contain both sets but not in intersection print("Symmetric difference :", A ^ B) 0,6,8,1,3,5 o/p Union : {0, 1, 2, 3, 4, 5, 6, 8} Intersection : {2, 4} Difference : {0, 8, 6} Symmetric difference : {0, 1, 3, 5, 6, 8}
  • 54. 54 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Q.Dictionaries • Dictionaries are used to store data values in key:value pairs. • A dictionary is a collection is unordered, • It is changeable(mutable) • It does not allow duplicates. • Dictionaries are written with curly brackets{}, and have keys and values Syntax Dictionary name = { <key>: <value>, <key>: <value>, . . . <key>: <value> } e.g thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) o/p { "brand": "Ford", "model": "Mustang", "year": 1964}
  • 55. 55 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Loop Through a Dictionary 1. Print all key names in the dictionary, one by one thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(x) 2.Print all values in the dictionary, one by one thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(thislist[x]) 3.both keys and values, by using the items() method: for x,y in thisdict.items(): print(x, y) Access Value from Dictionary thisdict ={ "brand": "Ford", "model": "Mustang",
  • 56. 56 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com "year": 1964 } print ("thisdict[brand]:",thisdict["brand"]); print ("thisdict[model]:",thisdict["model"]); print ("thisdict[year]:",thisdict["year"]); Update Dictionary 1.Add a Item thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) 2.Update Item The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added. The argument must be a dictionary, or an iterable object with key:value pairs. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.update({"color": "red"}) 3.Remove Item 1.Using del method
  • 57. 57 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com thisdict= { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict) 2.The del keyword can also delete the dictionary completely thisdict= { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict print(thisdict) 2.The clear() method empties the dictionary thisdict= { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.clear() print(thisdict) o/p {} 3. The pop() method removes the item with the specified key name Thisdict { "brand": "Ford", "model": "Mustang",
  • 58. 58 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com "year": 1964 } thisdict.pop("model") print(thisdict) 4.The popitem() method removes the last inserted item thisdict= { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(thisdict) copy() Returns a copy of the dictionary car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.copy() print(x) items() Return the dictionary's key-value pairs car={ "brand": "Ford",
  • 59. 59 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com "model": "Mustang", "year": 1964 } x=car.items() print(x) get() Returns the value of the specified key car={ "brand": "Ford", "model": "Mustang", "year": 1964 } x=car.get("model") print(x) setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.setdefault("model", "Bronco") print(x) keys()
  • 60. 60 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Returns a list containing the dictionary's keys car={ "brand": "Ford", "model": "Mustang", "year": 1964 } x=car.keys() print(x) OR for x in car.keys(): print(x) values() Returns a list of all the values in the dictionary car={ "brand": "Ford", "model": "Mustang", "year": 1964 } x=car.values() print(x) OR for x in thisdict.values(): print(x) Q.Python Functions • A function is a block of code which only runs when it is called.
  • 61. 61 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com • It can pass data, known as parameters, into a function. • A function can return data as a result Syntax Python provides the def keyword to define the function def functionname(parameters): function_block return expression e.g 1 def display(): print("hello world") display() # calling function e.g 3 def sum(a,b): c=a+b; return c; a = 10 b = 20 print("The sum is:",sum(a,b)) # calling sum() function in print statement Function Argument There are 2 ways passing argument to the function 1.Call by Reference It pass as address as parameter to the function def change_list(list1): list1.append(20)
  • 62. 62 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com list1.append(30) print("list inside function = ",list1) #defining the list list1 = [10,30,40,50] #calling the function change_list(list1) print("list outside function = ",list1) o/p list inside function = [10, 30, 40, 50, 20, 30] list outside function = [10, 30, 40, 50, 20, 30] 2. Call By value It pass as value as parameter to the function 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 1.Required arguments • Required arguments are the argument passed to a function in correct positional order. • No. of argument of the function call should match exactly with function definition def calculate(a,b): return a+b
  • 63. 63 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com calculate(10,20) 2.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. def printme(name,age=22): print("My name is",name,"and age is",age) printme("john") 3.Keyword arguments • Python allows us to call the function with the keyword Arguments(key = value). • 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(message="hello", name = "amit") **kwargs Python provides the facility to pass the multiple keyword arguments which can be represented as **kwargs. def food(**kwargs): print(kwargs) food(fruits="Orange", Vagitables="Carrot") o/p
  • 64. 64 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com {'fruits': 'Orange', 'Vagitables': 'Carrot'} Rules • positional argument after keyword arguments will result in errors. e.g greet(name="amit","How do you do?") • Non Default argument must present before default argument in function header def greet(msg = "Good morning!", name): =➔error 4.Variable-length Arguments (*args) The variable-length arguments can pass any number of arguments. Syntax *<variable - name > def printme(*names): print(names) printme("john","David","smith","nick") Scope of variables The variables are defined with the two types of scopes. 1. Global variables: variables declared inside the function known as Global Variable. X=300; def myfunc(): global x;#if not declared global keyword then it consider local
  • 65. 65 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com x= 200; print(x); myfunc() print(x) 2. Local variables: variables declared outside the function known as Global Variable. def myfunc(): x= 300 print(x) myfunc() Recursion It is mechanism to calling itself known as recursion. def factorial(n): if n == 1: return n else: return n * factorial(n-1) n=3; f=factorial(n); print(f); Anonymous Function • A function without name known as anonymous function. • In Python anonymous function define by using Lambda function • A lambda function can take any number of arguments, but can only have one expression.
  • 66. 66 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Syntax lambda arguments : expression e.g 1 x= lambda a:a+ 10 print(x(5)) e.g 2 x= lambda a,b,c:a+b+c print(x(5, 6, 2)) e.g 3 : Using if-else Syntax lambda x : True if (condtion) else False x=lambda n:"no is positive" n>0 else "no is negative" print(x(5)
  • 67. 67 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Function Programming Tools (filter(),map(),reduce()) Map() The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item Syntax Map(finction,list) li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(map(lambda x: x*2, li)) print(final_list) o/p [10, 14, 44, 194, 108, 124, 154, 46, 146, 122] Filter() The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Syntax Filter(function,list) li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(filter(lambda x: (x%2 != 0) , li)) print(final_list) o/p [5, 7, 97, 77, 23, 73, 61]
  • 68. 68 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Reduce() The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module. Syntax reduce(function, sequence[, initial]) from functools import reduce li = [5, 8, 10, 20, 50, 100] sum = reduce((lambda x, y: x + y), li) print (sum) o/p 193 Q.Python Classes/Objects Python is also an object-oriented language. It support following features o Class o Object o Method o Inheritance o Polymorphism o Data Abstraction o Encapsulation Creation of class & object Syntax
  • 69. 69 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com class ClassName: <statement-1> . . <statement-N> Syntax Objectname=classname(aguments) e.g 1 class Person: def __init__(self):#constrcutor self.name=“amol” self.age = 36 def myfunc(self): print("name is " + self.name) print("age is " + self.age) p1=Person() #instance_creation print(p1.name) print(p1.age) e.g 2 class Person: def __init__(self,name,age): #constrcutor self.name=name self.age = age def myfunc(self): print("name is " + self.name) print("age is " + self.age) p1=Person("amol", 36) #instance creation
  • 70. 70 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com print(p1.name) print(p1.age) self parameter • The self parameter is a reference to the current instance of the class and It is used to access attribute of the class. • It has to be the first parameter of any function in the class. • Python will automatically send a reference to the instance. It can capture the of the instance with any variable name(self). Constructor • A constructor is a special type of method (function) that is called automatically whenever an object of that class is created. • A constructor is a special type of method (function) which is used to initialize the instance members of the class. • The name of constructor is always name _init()_ • Constructors can be of non-parametrized & parameterized. e.g 1.non-parametrized class Person: def __init__(self): #constrcutor self.name=“amol” self.age = 36 p1 = Person() e.g 2 parameterized
  • 71. 71 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com class Person: def __init__(self,name,age): #constrcutor self.name=name self.age = age p1 = Person("amol", 36) Garbage collection • Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection. • Python's garbage collector runs during program execution when an object's reference count reaches zero. • An object's reference count increases when it is assigned a new name or placed value. The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically. a = 40 # Create object <40> b = a # Increase ref. count of <40> d=b # Increase ref. count of <40> c = [b] # Increase ref. count of <40> del a # Decrease ref. count of <40> b = 100 # Decrease ref. count of <40> c[0] = -1 # Decrease ref. count of <40> d=none # Decreases ref. count of <40> Destructor • The __del__() method is a known as a destructor method in Python. • when the object is destroyed, due to garbage collection, then _del_ method is called. • This method might be used to clean up any non memory resources used by an instance
  • 72. 72 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Syntax def __del__(self): # body of destructor class SomeObj: def __init__(self): print('The object is created.') def __del__(self): print('The object is destroyed.') obj1 = SomeObj() obj2 = obj1 obj3 = obj1 print("Set obj1 to None...") obj1 = None print("Set obj2 to None...") obj2 = None print("Set obj3 to None...") obj3 = None Method Overloading python does not support method overloading by default. But there are different ways to achieve method overloading in Python. The problem with method overloading in Python is that it may overload the methods but can only use the latest defined method. def product(a, b): p = a * b print(p) # Second product method # Takes three argument and print their # product
  • 73. 73 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com def product(a, b, c): p = a * b*c print(p) # Uncommenting the below line shows an error # product(4, 5) # This line will call the second product method product(4, 5, 5) Operator Overloading Python support operator overloading. class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "({0},{1})".format(self.x, self.y) def __add__(self, other): x = self.x + other.x y = self.y + other.y return Point(x, y) p1 = Point(1, 2) p2 = Point(2, 3) p3=p1+p2 #p3=p1.__add__(p2) print(p3)
  • 74. 74 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com List of special method of operator overloading Python Inheritance Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class. Type of inheritance 1.Single Inheritance: A derived class is inherited from the only one base class known as Single inheritance . Syntax class derived-class(base class):
  • 75. 75 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com <class-suite> e.g class A: def disp1(self): print("disp1 method in base") class B(A): def disp2(self): print("disp2 method in derived") ob = B() ob.disp1() ob.disp2() Using Constructor(super keyword) class A: def __init__(self,a): self.a=a class B(A): def __init__(self,a,b): super().__init__(a) self.b=b def disp(self): print("a is",self.a) print("b is",self.b) ob=B(1,2) ob.disp() 2.MultiLevel Inheritance: Multi-level inheritance is archived when a derived class inherits another derived class. Syntax
  • 76. 76 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com class class1: <class-suite> class class2(class1): <class suite> class class3(class2): <class suite> e.g class A: def disp1(self): print("disp1 method in base") class B(A): def disp2(self): print("disp2 method in derived1") class C(B): def disp3(self): print("disp3 method in derived2") ob = C() ob.disp1() ob.disp2() ob.disp3() 3.Multiple inheritance: To inherit multiple base classes in the child class known as multiple inheritance. Syntax class Base1: <class-suite> class Base2: <class-suite>
  • 77. 77 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com class BaseN: <class-suite> class Derived(Base1, Base2, ...... BaseN): <class-suite> e.g class A: def disp1(self): print("disp1 method in base") class B: def disp2(self): print("disp2 method in derived1") class C(A,B): def disp3(self): print("disp3 method in derived2") ob = C() ob.disp1() ob.disp2() ob.disp3() Hierarchical Inheritance Hierarchical inheritance involves more then derived classes derived from the single base or parent class. class A: def disp1(self): print("disp1 method in base") class B(A): def disp2(self): A C B
  • 78. 78 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com print("disp2 method in derived1") class C(A): def disp3(self): print("disp3 method in derived2") ob1 = B() ob1.disp1() ob1.disp2() ob2=C() ob2.disp1() ob2.disp3()
  • 79. 79 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Base Class Constructor
  • 80. 80 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Access Specifier
  • 81. 81 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com public(By Deafult) The members declared as Public are accessible from outside the Class through an object of the class class Student: def __init__(self,rollno,name): self.rollno=rollno self.name=name class Result(Student): def disp(self): print("rollno is ",self.rollno) print("name is ",self.name) ob=Result(1,"om") ob.disp() Private __(Double underscore) to a variable name makes it private The members declared as Protected are accessible from outside the class but only in a class derived from it that is in the child or subclass class Student: def __init__(self,rollno,name): self.__rollno=rollno self.__name=name class Result(Student): def disp(self): print("rollno is ",self.__rollno) print("name is ",self.__name) ob=Result(1,"om") ob.disp() o/p error Protected _(single underscore) to a variable name makes it protected These members are only accessible from within the class. No outside Access is allowed. class Student: def __init__(self,rollno,name): self._rollno=rollno self._name=name class Result(Student): def disp(self): print("rollno is ",self._rollno) print("name is ",self._name) ob=Result(1,"om") ob.disp()
  • 82. 82 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Method Overriding When the parent class method is redefined in their child class with same name with same prototype, then the concept is called method overriding. class A: def func1(self): print("this is function 1") class B(A): def func1(self): super().func1() print("this is function 2") ob = B() ob.func1() Python Exception Definition: An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. List of Standard Exceptions − Sr.No. Exception Name & Description 1 Exception Base class for all exceptions 2 StopIteration Raised when the next() method of an iterator does not point to any object. 3 SystemExit Raised by the sys.exit() function.
  • 83. 83 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 4 StandardError Base class for all built-in exceptions except StopIteration and SystemExit. 5 ArithmeticError Base class for all errors that occur for numeric calculation. 6 OverflowError Raised when a calculation exceeds maximum limit for a numeric type. 7 FloatingPointError Raised when a floating point calculation fails. 8 ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types. 9 AssertionError Raised in case of failure of the Assert statement. 10 AttributeError Raised in case of failure of attribute reference or assignment. 11 EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. 12 ImportError Raised when an import statement fails. 13 KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. 14 LookupError Base class for all lookup errors. 15 IndexError Raised when an index is not found in a sequence.
  • 84. 84 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 16 KeyError Raised when the specified key is not found in the dictionary. 17 NameError Raised when an identifier is not found in the local or global namespace. 18 UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it. 19 EnvironmentError Base class for all exceptions that occur outside the Python environment. 20 IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 21 IOError Raised for operating system-related errors. 22 SyntaxError Raised when there is an error in Python syntax. 23 IndentationError Raised when indentation is not specified properly. 24 SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. 25 SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. 26 TypeError Raised when an operation or function is attempted that is invalid for the specified data type.
  • 85. 85 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com 27 ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. 28 RuntimeError Raised when a generated error does not fall into any category. 29 NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. Handling an exception The try: block contains one or more statements which are likely to encounter an exception. If the statements in this block are executed without an exception, the subsequent except: block is skipped. If the exception does occur, the program flow is transferred to the except: block. The else keyword to define a block of code to be executed if no errors were raised Syntax try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block. e.g try:
  • 86. 86 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com x=int(input('Enter a number: ')) y=int(input('Enter another number: ')) z=x/y except ZeroDivisionError: print("Division by 0 not accepted") else: print("else block") e.g 2 Handles all types of exception try: x=int(input('Enter a number: ')) y=int(input('Enter another number: ')) z=x/y except Exception: print("Division by 0 not accepted") else: print("else block") except Clause with Multiple Exceptions Syntax try: You do your operations here; ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block. e.g try: x=int(input('Enter a number: ')) y=int(input('Enter another number: ')) z=x/y except (ArithmeticError,ZeroDivisionError): print("Division by 0 not accepted") else: print("else block")
  • 87. 87 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Finally Block The finally block, if specified, will be executed regardless if the try block raises an error or not. Syntax try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. e.g try: x=int(input('Enter a number: ')) y=int(input('Enter another number: ')) z=x/y except ZeroDivisionError: print("Division by 0 not accepted") finally: print("finally block") Raise an exception Python also provides the raise keyword to be used throw an exception to be explicitly. Syntax raise [Exception [, args] Where Exception :It is the type of exception (for example, NameError) Argument: It is a value for the exception argument. try: x=int(input('Enter a number upto 100: ')) if x > 100: raise ValueError(x)
  • 88. 88 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com except ValueError: print(x, "is out of allowed range") else: print(x, "is within the allowed range") User-defined Exceptions e.g class Myerror(Exception): def __init__(self,arg): self.arg=arg try: n=int(input("enter value")) if(n<0): raise Myerror("no is negative") else: print("postive value") except Myerror as e: print (e.arg)
  • 89. 89 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com Q.Python 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 module to be the same as a code library To creation of User Defined package 1.To create module def show(name): print("Hello, " + name) Note: save as mymodule.py 2. The import Statement It can use any Python source file as a module by executing an import statement in some other Python source file. syntax − import module1[, module2[,... moduleN] import mymodule mymodule.show("om") e.g To add some part in above module
  • 90. 90 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com person1={ "name": "om", "age": 22, "country": "india" } save above code in mymodule.py import mymodule a=mymodule.person1["age"] print(a) Import From Module It can choose to import only parts from a module, by using the from keyword. from modname import name1[, name2[, ... nameN]] def show(name): print("Hello," +name) person1={ "name": "om", "age": 22, "country": "india" } Import only the person1 dictionary from the module
  • 91. 91 Vision Academy Since 2005 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/Dip(Comp/II)/MCS/MCA/MCS/BE(Comp/IT) Python Notes http://www.visionacademe.com from mymodule import person1 print (person1["age"]) from...import * Statement It is also possible to import all names from a module into the current namespace by using the following import statement from mymodule import * print (person1["age"]) show("om") Re-naming a Module It can create an alias when it import a module, by using the as keyword import mymodule as mx a=mx.person1["age"] print(a) Pre defined module import calendar cal = calendar.month(2021, 1) print ("Here is the calendar:") print (cal) #current date & time import datetime x = datetime.datetime.now() print(x)