SlideShare a Scribd company logo
1 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
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
37 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
% 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
38 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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
39 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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
40 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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’]
41 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Display List using loop
list=["apple", "banana", "cherry"]
for i in range(len(list)):
print(list[i])
OR
list = ["apple", "banana", "cherry"]
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
42 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
thislist=["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) o/p=➔[‘apple’, ‘banana’,’watermelon’, "cherry"]
Updating List
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)
43 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
o/p [‘apple’,’watermelon’]
Remove Item
1.remove():The remove() method removes the specified item.
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)
44 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
o/p [‘banana’,’cherry’]
The del keyword can also delete the list completely.
list=["apple", "banana", "cherry"]
del list
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)
45 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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()
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)
46 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
o/p
[0,1,2,3,4,5,6,7,8,9]
Q Python Tuple
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
47 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Tuple index
e.g
tuple=("apple", "banana", "cherry")
print(tuple[1]) o/p=>bannan
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’)
48 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Update Items
x=("apple", "banana", "cherry")
y= list(x)
y[1]= "kiwi"
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’)
Packing Tuple
When we create a tuple, It normally assign values to it. This is called "packing" a tuple
fruits = ("apple", "banana", "cherry")
print(fruits)
Unpacking Tuple
It allowed to extract the values back into variables. This is called "unpacking"
fruits=("apple", "banana", "cherry")
(green,yellow,red)=fruits
print(green) o/p=>apple
49 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
print(yellow) o/p=>banana
print(red) o/p=>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)
Membership It returns true if a particular item exists
in the tuple otherwise false
print (2 in T1)
prints True.
50 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
list1 = [ 1, 2, 4, 3]
list2 = [ 1, 2, 5, 8]
list3 = [ 1, 2, 5, 8, 10]
list4 = [ 1, 2, 4, 3]
51 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
If T1>T2 return(1)
If T1=T2 return(0)
If T1<T2 return(-1)
print cmp(list2, list1) o/p 1
print cmp(list2, list3) o/p -1
print cmp(list4, list1) o/p 0
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’)
52 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Sr.no List Tuple
1 The literal syntax of list is
shown by the [].
The literal syntax of the tuple is
shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the a variable
length.
The tuple has the fixed length.
4 The list provides more
functionality than a tuple.
The tuple provides less
functionality than the list.
5 List iteration is slower and is
time consuming
Tuple iteration is faster
6 The lists are more memory The tuples are less memory.
7. L=[1,2,3] T=(1,2,3)
53 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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 immutable(The value of the items stored in the set cannot be changed after set has
been created)
Syntax
tupleame={value1, value2,…..valuen}
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"}
54 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
thisset.update(tropical)
print(thisset)
3.To remove item using discard method
thisset={"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
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)
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}
55 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
56 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
}
print(thisdict)
o/p
{ "brand": "Ford", "model": "Mustang", "year": 1964}
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:
57 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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",
"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
58 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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
59 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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",
"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()
60 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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",
"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()
61 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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()
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
}
62 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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.
• 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;
63 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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)
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.
64 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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.
65 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
{'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")
66 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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);
67 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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.
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 Use as an anonymous function inside another function
def myfunc(n):
return lambda a:a*n
mydoubler=myfunc(2)
print(mydoubler(11))
Function Programming Tools
68 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
(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]
69 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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.Packing and Unpacking Arguments
1.args*
• It can use * to unpack the list so that all elements of it can be passed as different
parameters
• The single asterisk(*) form of *args can be used as parameter to send non keyworded
Variable-length argument list to a functions.
• * used for tuple
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code
my_list = [1, 2, 3, 4]
# Unpacking list into four arguments
fun(*my_list)
70 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
o/p
(1,2,3,4)
2.**kwargs
• It is used to pass a keyworded, variable length argument dictionary to a function.
• ** is used for dictionaries.
def fun(a, b, c):
print(a, b, c)
# A call with unpacking of dictionary
d = {'a':2, 'b':4, 'c':10}
fun(**d)
o/p
2 4 10
Function Object(First Class Function)
First class objects in a language are handled uniformly throughout. They may be stored in
data structures, passed as arguments, or used in control structures. A programming language
is said to support first-class functions if it treats functions as first-class objects. Python
supports the concept of First Class functions
Properties
• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables, lists, …
Python functions are first class objects. In the example below, we are assigning function to a
variable. This assignment doesn’t call the function. It takes the function object referenced by
shout and creates a second name pointing to it, yell
# Python program to illustrate functions
# can be treated as objects
71 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
def shout(text):
return text.upper()
print (shout('Hello'))
yell = shout
print (yell('Hello'))
Function Duck Type
Duck Typing is a type system used in dynamic languages. Python doesn’t care about which
class of object it is, if it is an object & required behaviours is present for that object then it
will work. The type of object is distinguished only at runtime. This is called as duck typing.
The name Duck Typing comes from the phrase:
“If it looks like a duck and quacks like a duck, it’s a duck”
class Bird:
def fly(self):
print("fly with wings")
class Airplane:
def fly(self):
print("fly with fuel")
class Fish:
def swim(self):
print("fish swim in sea")
for obj in Bird(), Airplane(), Fish():
obj.fly()
o/p
fly with wings
fly with fuel
AttributeError: 'Fish' object has no attribute 'fly
72 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Generator
Python generator gives us easier way to create python iterators. A generator is a function that
return an object(iterator) which it can iterate over(one value at a time)
Generators Function
• Defined with the def keyword
• Use the yield keyword
• May contain several yield keywords.
• Returns an iterator.
Generator Object
Generator Function return a generator object. It is used either by calling the next method
on generator object or using the generator object in for in loop
e.g
def gen():
yield 1
yield 2
yield 3
for i in gen():
print(i)
o/p
1
2
3
def gen():
yield 1
yield 2
yield 3
x=gen()
print(x.__next__())
print(x.__next__())
print(x.__next__())
o/p
1
2
3
73 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
It is as easy as defining a normal function, but with a yield statement instead of
a return statement.
The difference is that while a return statement terminates a function entirely, yield statement
pauses the function saving all its states and later continues from there on successive calls.
Differences between Generator function and Normal function
• Generator function contains one or more yield statements.
• When called, it returns an object (iterator) but does not start execution immediately.
• Methods like __iter__() and __next__() are implemented automatically. So we can
iterate through the items using next().
• Once the function yields, the function is paused and the control is transferred to the
caller.
• Local variables and their states are remembered between successive calls.
Factorial no
def gen(n):
f=1
i=1
while i<=n:
f=f*i
i=i+1
yield f
n=int(input("enter val"))
for i in gen(n):
print(i)
Generator Expression
Python also provides a generator expression, which is a shorter way of defining simple
generator functions. The generator expression is an anonymous generator function.
74 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
A generator expression looks similar to a list comprehension but the simple difference is
that it uses parenthesis over square brackets.
list comprehension produces the entire list, generator expression produces one item at a
time
Syntax
genexpr=(expression for item in collection)
sq = (x*x for x in range(5))
for i in sq:
print(i)
Python Iterators
• An iterator is an object that contains a countable number of values.
• An iterator is an object that can be iterated upon, meaning that you can traverse through
all the values.
• Python, an iterator is an object which implements the iterator protocol, which consist
of the methods __iter__() and __next__().
Lists, tuples, dictionaries,sets,strings are all iterable objects. They are iterable containers which
it can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
mytuple=("apple", "banana", "cherry")
myit= iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
OR
my = ("apple", "banana", "cherry")
for x in my:
75 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
print(x)
o/p
apple
banana
Cherry
• Create an Iterator
class MyNumbers:
def __iter__(self):
self.a= 1
return self
def __next__(self):
x=self.a
self.a+= 1
return x
myclass=MyNumbers()
myiter=iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
• StopIteration
class MyNumbers:
def __iter__(self):
self.a= 1
return self
def __next__(self):
if self.a<= 20:
x=self.a
76 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
self.a+= 1
return x
else:
raise StopIteration
myclass= MyNumbers()
myiter=iter(myclass)
for x in myiter:
print(x)
Iterator Generator
Class is used to implement an iterator Function is used to implement a
generator.
Local Variables aren’t used. Generator saves the state of the
local variable every time ‘yield’
pauses the loop in python.
Iterators are used mostly to iterate or convert
other objects to an iterator using iter()
function.
Generators are mostly used in
loops to generate an iterator by
returning all the values in the
loop without affecting the
iteration of the loop
Iterator uses iter() and next() functions Generator uses yield keyword
Every iterator is not a generator Every generator is an iterator
77 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Iterator Generator
my = ("apple", "banana", "cherry")
for x in my:
print(x)
def gen():
yield 1
yield 2
yield 3
for i in gen():
print(i)
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
class ClassName:
<statement-1>
.
.
<statement-N>
Syntax
Objectname=classname(aguments)
78 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
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.
79 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
• 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
class Person:
def __init__(self,name,age): #constrcutor
80 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
Syntax
def __del__(self):
# body of destructor
81 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
def product(a, b, c):
p = a * b*c
print(p)
82 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
# 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)
83 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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):
<class-suite>
e.g
84 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
class class1:
<class-suite>
class class2(class1):
85 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
<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>
class BaseN:
<class-suite>
86 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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):
print("disp2 method in derived1")
class C(A):
def disp3(self):
A
C
B
87 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
print("disp3 method in derived2")
ob1 = B()
ob1.disp1()
ob1.disp2()
ob2=C()
ob2.disp1()
ob2.disp3()
Base Class Constructor
88 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Access Specifier
89 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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()
90 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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()
Class or Static Variables
• Class or Static variables are the variables that belong to the class and not to objects.
• Class or Static variables are shared amongst objects of the class.
• All variables which are assigned a value in the class declaration are class variables.
And variables which are assigned values inside class methods are instance
variables.
class Student:
stream = 'computer' # Class Variable
def __init__(self,name,roll):
self.name = name # Instance Variable
self.roll = roll # Instance Variable
a = Student('amol', 1)
b = Student('punit', 2)
print(a.stream) # prints "computer"
91 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
print(b.stream) # prints "computer"
print(a.name) # prints "amol"
print(b.name) # prints "punit"
print(a.roll) # prints "1"
print(b.roll) # prints "2"
# Class variables can be accessed using class
# name also
print(Student.stream) # prints "computer"
# Now if we change the stream for just a it won't be changed for b
a.stream = 'computer sci'
print(a.stream) # prints 'computer sci'
print(b.stream) # prints 'computer'
# To change the stream for all instances of the class we can change it
# directly from the class
CSStudent.stream = 'comp'
print(a.stream) # prints 'comp'
print(b.stream) # prints 'comp’
Class Method & Static Method
Class Method Static Method
The class method takes cls (class) as first argument. The static method does not take any specific parameter.
Class method can access and modify the class state.
i.e
It can access class attributes
Static Method cannot access or modify the class state.
i.e
It cannot access either class attributes or instance
attributes.
92 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
The class method takes the class as parameter to know
about the state of that class.
Static methods do not know about class state. These
methods are used to do some utility tasks by taking some
parameters.
@classmethod decorator is used here. @staticmethod decorator is used here.
It can be called using
the ClassName.MethodName() or object.MethodName().
It can be called using
the ClassName.MethodName() or object.MethodName().
class my_class:
@classmethod
def function_name(cls, arguments):
#Function Body
return value
class my_class:
@staticmethod
def function_name(arguments):
#Function Body
return value
93 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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.
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.
94 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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.
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.
95 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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.
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
96 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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:
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]]]):
97 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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")
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")
98 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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)
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)
99 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
What is Assertion?
The assert keyword is used for debugging code. assert statement has a condition or expression
which is supposed to be always true. If the condition is false assert halts the program and gives
an AssertionError.
Syntax
assert <condition>
assert <condition>,<error message>
e.g 1.Assert using without error
x = "vision"
assert x == "goodbye"
print("both strings are same")
o/p AssertionError
e.g 2.Assert using without error
x = "goodbye"
#if condition returns False, AssertionError is
raised:
assert x == "goodbye"
print("both strings are same")
o/p both strings are same
Eg. 3 Assert using error
x = "vision"
#if condition returns False, AssertionError is
raised:
Eg.4 Assert using error
x = "goodbye"
#if condition returns False, AssertionError is
raised:
100 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
assert x == "goodbye", "both strings are
same'"
print("both strings are same")
o/p
assert x == "goodbye", "both strings are not
same"
AssertionError: both strings are not same
assert x == "goodbye", "both strings are not
same"
print("both strings are same")
o/p both strings are same
101 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
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
person1={
"name": "om",
"age": 22,
"country": "india"
}
102 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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
from mymodule import person1
print (person1["age"])
from...import * Statement
103 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
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)
104 Vision Academy
(9822506209/9823037693)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY)
Python Notes
http://www.visionacademe.com
Tkinter(GUI) Programming
Python provides the standard library Tkinter for creating the graphical user interface for
desktop based applications.
• Tkinter top-level window can be created by using the following steps.
1. import the Tkinter module.
2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer
screen.
• Creating the application main window.
from tkinter import *
parent = Tk()
parent.mainloop() # It is similar to getch() or infinite loop
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf

More Related Content

Similar to Python_final_print_vison_academy_9822506209.pdf

intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdfANIKULSAIKH
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyTIB Academy
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PuneEthan's Tech
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)guobichrng
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Ali alshehri c++_comparison between c++&amp;python
Ali alshehri c++_comparison between c++&amp;pythonAli alshehri c++_comparison between c++&amp;python
Ali alshehri c++_comparison between c++&amp;pythonAliAAAlshehri
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1Kanchilug
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSCisco Russia
 
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
 
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
 
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
 
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
 
Module1-Chapter1_ppt.pptx
Module1-Chapter1_ppt.pptxModule1-Chapter1_ppt.pptx
Module1-Chapter1_ppt.pptxSandeepR95
 

Similar to Python_final_print_vison_academy_9822506209.pdf (20)

intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech Pune
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Summer Training Project.pdf
Summer Training Project.pdfSummer Training Project.pdf
Summer Training Project.pdf
 
Ali alshehri c++_comparison between c++&amp;python
Ali alshehri c++_comparison between c++&amp;pythonAli alshehri c++_comparison between c++&amp;python
Ali alshehri c++_comparison between c++&amp;python
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OS
 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
 
python unit2.pptx
python unit2.pptxpython unit2.pptx
python unit2.pptx
 
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
 
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
 
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
 
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
 
Module1-Chapter1_ppt.pptx
Module1-Chapter1_ppt.pptxModule1-Chapter1_ppt.pptx
Module1-Chapter1_ppt.pptx
 

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 

Python_final_print_vison_academy_9822506209.pdf

  • 1. 1 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 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
  • 37. 37 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 % 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
  • 38. 38 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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
  • 39. 39 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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
  • 40. 40 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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’]
  • 41. 41 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Display List using loop list=["apple", "banana", "cherry"] for i in range(len(list)): print(list[i]) OR list = ["apple", "banana", "cherry"] 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
  • 42. 42 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com thislist=["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist) o/p=➔[‘apple’, ‘banana’,’watermelon’, "cherry"] Updating List 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)
  • 43. 43 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com o/p [‘apple’,’watermelon’] Remove Item 1.remove():The remove() method removes the specified item. 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)
  • 44. 44 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com o/p [‘banana’,’cherry’] The del keyword can also delete the list completely. list=["apple", "banana", "cherry"] del list 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)
  • 45. 45 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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() 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)
  • 46. 46 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com o/p [0,1,2,3,4,5,6,7,8,9] Q Python Tuple 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
  • 47. 47 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Tuple index e.g tuple=("apple", "banana", "cherry") print(tuple[1]) o/p=>bannan 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’)
  • 48. 48 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Update Items x=("apple", "banana", "cherry") y= list(x) y[1]= "kiwi" 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’) Packing Tuple When we create a tuple, It normally assign values to it. This is called "packing" a tuple fruits = ("apple", "banana", "cherry") print(fruits) Unpacking Tuple It allowed to extract the values back into variables. This is called "unpacking" fruits=("apple", "banana", "cherry") (green,yellow,red)=fruits print(green) o/p=>apple
  • 49. 49 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com print(yellow) o/p=>banana print(red) o/p=>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) Membership It returns true if a particular item exists in the tuple otherwise false print (2 in T1) prints True.
  • 50. 50 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 list1 = [ 1, 2, 4, 3] list2 = [ 1, 2, 5, 8] list3 = [ 1, 2, 5, 8, 10] list4 = [ 1, 2, 4, 3]
  • 51. 51 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com If T1>T2 return(1) If T1=T2 return(0) If T1<T2 return(-1) print cmp(list2, list1) o/p 1 print cmp(list2, list3) o/p -1 print cmp(list4, list1) o/p 0 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’)
  • 52. 52 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Sr.no List Tuple 1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the (). 2 The List is mutable. The tuple is immutable. 3 The List has the a variable length. The tuple has the fixed length. 4 The list provides more functionality than a tuple. The tuple provides less functionality than the list. 5 List iteration is slower and is time consuming Tuple iteration is faster 6 The lists are more memory The tuples are less memory. 7. L=[1,2,3] T=(1,2,3)
  • 53. 53 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 immutable(The value of the items stored in the set cannot be changed after set has been created) Syntax tupleame={value1, value2,…..valuen} 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"}
  • 54. 54 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com thisset.update(tropical) print(thisset) 3.To remove item using discard method thisset={"apple", "banana", "cherry"} thisset.discard("banana") print(thisset) 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) 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}
  • 55. 55 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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
  • 56. 56 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com } print(thisdict) o/p { "brand": "Ford", "model": "Mustang", "year": 1964} 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:
  • 57. 57 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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", "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
  • 58. 58 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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
  • 59. 59 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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", "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()
  • 60. 60 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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", "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()
  • 61. 61 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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() 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 }
  • 62. 62 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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. • 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;
  • 63. 63 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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) 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.
  • 64. 64 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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.
  • 65. 65 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 {'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")
  • 66. 66 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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);
  • 67. 67 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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. 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 Use as an anonymous function inside another function def myfunc(n): return lambda a:a*n mydoubler=myfunc(2) print(mydoubler(11)) Function Programming Tools
  • 68. 68 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com (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]
  • 69. 69 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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.Packing and Unpacking Arguments 1.args* • It can use * to unpack the list so that all elements of it can be passed as different parameters • The single asterisk(*) form of *args can be used as parameter to send non keyworded Variable-length argument list to a functions. • * used for tuple def fun(a, b, c, d): print(a, b, c, d) # Driver Code my_list = [1, 2, 3, 4] # Unpacking list into four arguments fun(*my_list)
  • 70. 70 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com o/p (1,2,3,4) 2.**kwargs • It is used to pass a keyworded, variable length argument dictionary to a function. • ** is used for dictionaries. def fun(a, b, c): print(a, b, c) # A call with unpacking of dictionary d = {'a':2, 'b':4, 'c':10} fun(**d) o/p 2 4 10 Function Object(First Class Function) First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions Properties • A function is an instance of the Object type. • You can store the function in a variable. • You can pass the function as a parameter to another function. • You can return the function from a function. • You can store them in data structures such as hash tables, lists, … Python functions are first class objects. In the example below, we are assigning function to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell # Python program to illustrate functions # can be treated as objects
  • 71. 71 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com def shout(text): return text.upper() print (shout('Hello')) yell = shout print (yell('Hello')) Function Duck Type Duck Typing is a type system used in dynamic languages. Python doesn’t care about which class of object it is, if it is an object & required behaviours is present for that object then it will work. The type of object is distinguished only at runtime. This is called as duck typing. The name Duck Typing comes from the phrase: “If it looks like a duck and quacks like a duck, it’s a duck” class Bird: def fly(self): print("fly with wings") class Airplane: def fly(self): print("fly with fuel") class Fish: def swim(self): print("fish swim in sea") for obj in Bird(), Airplane(), Fish(): obj.fly() o/p fly with wings fly with fuel AttributeError: 'Fish' object has no attribute 'fly
  • 72. 72 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Generator Python generator gives us easier way to create python iterators. A generator is a function that return an object(iterator) which it can iterate over(one value at a time) Generators Function • Defined with the def keyword • Use the yield keyword • May contain several yield keywords. • Returns an iterator. Generator Object Generator Function return a generator object. It is used either by calling the next method on generator object or using the generator object in for in loop e.g def gen(): yield 1 yield 2 yield 3 for i in gen(): print(i) o/p 1 2 3 def gen(): yield 1 yield 2 yield 3 x=gen() print(x.__next__()) print(x.__next__()) print(x.__next__()) o/p 1 2 3
  • 73. 73 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com It is as easy as defining a normal function, but with a yield statement instead of a return statement. The difference is that while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls. Differences between Generator function and Normal function • Generator function contains one or more yield statements. • When called, it returns an object (iterator) but does not start execution immediately. • Methods like __iter__() and __next__() are implemented automatically. So we can iterate through the items using next(). • Once the function yields, the function is paused and the control is transferred to the caller. • Local variables and their states are remembered between successive calls. Factorial no def gen(n): f=1 i=1 while i<=n: f=f*i i=i+1 yield f n=int(input("enter val")) for i in gen(n): print(i) Generator Expression Python also provides a generator expression, which is a shorter way of defining simple generator functions. The generator expression is an anonymous generator function.
  • 74. 74 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com A generator expression looks similar to a list comprehension but the simple difference is that it uses parenthesis over square brackets. list comprehension produces the entire list, generator expression produces one item at a time Syntax genexpr=(expression for item in collection) sq = (x*x for x in range(5)) for i in sq: print(i) Python Iterators • An iterator is an object that contains a countable number of values. • An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. • Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__(). Lists, tuples, dictionaries,sets,strings are all iterable objects. They are iterable containers which it can get an iterator from. All these objects have a iter() method which is used to get an iterator: mytuple=("apple", "banana", "cherry") myit= iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) OR my = ("apple", "banana", "cherry") for x in my:
  • 75. 75 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com print(x) o/p apple banana Cherry • Create an Iterator class MyNumbers: def __iter__(self): self.a= 1 return self def __next__(self): x=self.a self.a+= 1 return x myclass=MyNumbers() myiter=iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) • StopIteration class MyNumbers: def __iter__(self): self.a= 1 return self def __next__(self): if self.a<= 20: x=self.a
  • 76. 76 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com self.a+= 1 return x else: raise StopIteration myclass= MyNumbers() myiter=iter(myclass) for x in myiter: print(x) Iterator Generator Class is used to implement an iterator Function is used to implement a generator. Local Variables aren’t used. Generator saves the state of the local variable every time ‘yield’ pauses the loop in python. Iterators are used mostly to iterate or convert other objects to an iterator using iter() function. Generators are mostly used in loops to generate an iterator by returning all the values in the loop without affecting the iteration of the loop Iterator uses iter() and next() functions Generator uses yield keyword Every iterator is not a generator Every generator is an iterator
  • 77. 77 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Iterator Generator my = ("apple", "banana", "cherry") for x in my: print(x) def gen(): yield 1 yield 2 yield 3 for i in gen(): print(i) 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 class ClassName: <statement-1> . . <statement-N> Syntax Objectname=classname(aguments)
  • 78. 78 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 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.
  • 79. 79 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com • 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 class Person: def __init__(self,name,age): #constrcutor
  • 80. 80 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 Syntax def __del__(self): # body of destructor
  • 81. 81 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 def product(a, b, c): p = a * b*c print(p)
  • 82. 82 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com # 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)
  • 83. 83 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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): <class-suite> e.g
  • 84. 84 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 class class1: <class-suite> class class2(class1):
  • 85. 85 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com <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> class BaseN: <class-suite>
  • 86. 86 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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): print("disp2 method in derived1") class C(A): def disp3(self): A C B
  • 87. 87 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com print("disp3 method in derived2") ob1 = B() ob1.disp1() ob1.disp2() ob2=C() ob2.disp1() ob2.disp3() Base Class Constructor
  • 88. 88 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Access Specifier
  • 89. 89 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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()
  • 90. 90 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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() Class or Static Variables • Class or Static variables are the variables that belong to the class and not to objects. • Class or Static variables are shared amongst objects of the class. • All variables which are assigned a value in the class declaration are class variables. And variables which are assigned values inside class methods are instance variables. class Student: stream = 'computer' # Class Variable def __init__(self,name,roll): self.name = name # Instance Variable self.roll = roll # Instance Variable a = Student('amol', 1) b = Student('punit', 2) print(a.stream) # prints "computer"
  • 91. 91 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com print(b.stream) # prints "computer" print(a.name) # prints "amol" print(b.name) # prints "punit" print(a.roll) # prints "1" print(b.roll) # prints "2" # Class variables can be accessed using class # name also print(Student.stream) # prints "computer" # Now if we change the stream for just a it won't be changed for b a.stream = 'computer sci' print(a.stream) # prints 'computer sci' print(b.stream) # prints 'computer' # To change the stream for all instances of the class we can change it # directly from the class CSStudent.stream = 'comp' print(a.stream) # prints 'comp' print(b.stream) # prints 'comp’ Class Method & Static Method Class Method Static Method The class method takes cls (class) as first argument. The static method does not take any specific parameter. Class method can access and modify the class state. i.e It can access class attributes Static Method cannot access or modify the class state. i.e It cannot access either class attributes or instance attributes.
  • 92. 92 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com The class method takes the class as parameter to know about the state of that class. Static methods do not know about class state. These methods are used to do some utility tasks by taking some parameters. @classmethod decorator is used here. @staticmethod decorator is used here. It can be called using the ClassName.MethodName() or object.MethodName(). It can be called using the ClassName.MethodName() or object.MethodName(). class my_class: @classmethod def function_name(cls, arguments): #Function Body return value class my_class: @staticmethod def function_name(arguments): #Function Body return value
  • 93. 93 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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. 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.
  • 94. 94 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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. 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.
  • 95. 95 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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. 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
  • 96. 96 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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: 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]]]):
  • 97. 97 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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") 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")
  • 98. 98 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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) 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)
  • 99. 99 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com What is Assertion? The assert keyword is used for debugging code. assert statement has a condition or expression which is supposed to be always true. If the condition is false assert halts the program and gives an AssertionError. Syntax assert <condition> assert <condition>,<error message> e.g 1.Assert using without error x = "vision" assert x == "goodbye" print("both strings are same") o/p AssertionError e.g 2.Assert using without error x = "goodbye" #if condition returns False, AssertionError is raised: assert x == "goodbye" print("both strings are same") o/p both strings are same Eg. 3 Assert using error x = "vision" #if condition returns False, AssertionError is raised: Eg.4 Assert using error x = "goodbye" #if condition returns False, AssertionError is raised:
  • 100. 100 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com assert x == "goodbye", "both strings are same'" print("both strings are same") o/p assert x == "goodbye", "both strings are not same" AssertionError: both strings are not same assert x == "goodbye", "both strings are not same" print("both strings are same") o/p both strings are same
  • 101. 101 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) 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 person1={ "name": "om", "age": 22, "country": "india" }
  • 102. 102 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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 from mymodule import person1 print (person1["age"]) from...import * Statement
  • 103. 103 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com 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)
  • 104. 104 Vision Academy (9822506209/9823037693) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA(CA)/BCS/MCS/MCA/MCS/BE(ANY) Python Notes http://www.visionacademe.com Tkinter(GUI) Programming Python provides the standard library Tkinter for creating the graphical user interface for desktop based applications. • Tkinter top-level window can be created by using the following steps. 1. import the Tkinter module. 2. Create the main application window. 3. Add the widgets like labels, buttons, frames, etc. to the window. 4. Call the main event loop so that the actions can take place on the user's computer screen. • Creating the application main window. from tkinter import * parent = Tk() parent.mainloop() # It is similar to getch() or infinite loop