Python Final Print Vision 22
Python Final Print Vision 22
(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
Q.Python Features
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
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.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application
http://www.visionacademe.com
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
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 C++ was developed by Python was created by Guido
the year 1969 and 1973 at Bjarne Stroustrup in van Rossum, and released in
AT&T Bell Labs. 1979. 1991.
Longer lines of code as Longer lines of code as 3-5 times shorter than
compared to python. compared to python. equivalent C/C++ programs.
C++ contains 52
C contains 32 keywords. keywords. Python contains 33 keywords.
http://www.visionacademe.com
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
C C++ Python
Q.Application of Phyton
http://www.visionacademe.com
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
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,
Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python
provides many useful frameworks, and these are given below:
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.
http://www.visionacademe.com
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
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.
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.
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.
http://www.visionacademe.com
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
o Gstreamer
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.
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
http://www.visionacademe.com
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
Python is not memory efficient and it has slow processing power as compared to other
languages.
4. Database Access
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.
http://www.visionacademe.com
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
OR
Q. Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
5. Python is a case-sensitive language. This means, Variable and variable are not the same.
Valid Identifier
Q.Python Keywords
http://www.visionacademe.com
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
• 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.
http://www.visionacademe.com
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
Q.Python Comments
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.
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
http://www.visionacademe.com
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
if condtion:
statement
statement
Multi-Line Statements
• 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
Q.Variables
x=5
http://www.visionacademe.com
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
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
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
http://www.visionacademe.com
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
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
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
• Python Arithmetic Operators
Arithmetic operators
Name Example
Operator
+ Addition x+y
http://www.visionacademe.com
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
- Subtraction x-y
* Multiplication x * y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
Example Same As
Operator
= 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
http://www.visionacademe.com
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
Comparison Operators
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
Not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
• 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:
http://www.visionacademe.com
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
Example
Operator Description
is not Returns true if both variables are not the same object x is not y
Example
Operator Description
Operator Name
& AND
| OR
^ XOR
http://www.visionacademe.com
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
~ NOT
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.
http://www.visionacademe.com
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
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.
http://www.visionacademe.com
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
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
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)
http://www.visionacademe.com
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
e.g
2.c=4
3.b = "for"
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
http://www.visionacademe.com
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
input(prompt)
Where
prompt=>A string, representing default message before input
e.g
x = input('”enter value'”)
print('”Hello”,x)
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")
http://www.visionacademe.com
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
2.if-else statement
Syntax
if boolean-expression:
#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:
http://www.visionacademe.com
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
print(“bismax”)
elif a==b:
print("aandbareequal")
else:
print("a is greater than b")
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:
http://www.visionacademe.com
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
statements(s)
e.g
for ch in 'vision':
print 'Current Letter :', ch
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
x= range(3, 6)
for n in x:
print(n)
http://www.visionacademe.com
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
o/p 3 4 5
x= range(3, 10, 2)
for n in x:
print(n)
o/p 3 5 7 9
for x in range(6):
print(x)
else:
print("Fi+inally finished!")
o/p 0 1 2 3 4 5
finallyfinished
1.
i= 1
while i< 6:
print(i)
if i== 3:
break
i = i+1
2.
i= 0
while i< 6:
http://www.visionacademe.com
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
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.
e.g
1.
a = 33
b = 200
if b > a:
pass
print("pass statement")
2.
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.
http://www.visionacademe.com
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
Q.Math Function
Function Description
http://www.visionacademe.com
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
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
import math
print(math.pi)
Q.String
http://www.visionacademe.com
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
String declaration
1.Using Double quotes
a=”Hello”
print(a)
2.UsingSingleQuotes
a=’hello’
print(a)
2.Multiline Strings
a= """visionacademy,
classesforbcs/bca/bba."""
print(a)
a= '''visionacademy,classesforbcs/bca/bba.'''
print(a)
Representations of String
• 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……..
http://www.visionacademe.com
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
Escape Characters
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
e.g
txt = "Hello\nWorld!"
print(txt)
http://www.visionacademe.com
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
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
S=' A B C D E F G H I '
print(S[2:7]) # C D E F G
http://www.visionacademe.com
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
S=' A B C D E F G H I '
print(S[-7:-2]) # C D E F G
You can specify both positive and negative indices at the same time.
S=' A B C D E F G H I '
print(S[2:-5]) # C D
You can specify the step of the slicing using step parameter. The step parameter is optional
and by default 1.
http://www.visionacademe.com
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
Omitting the start index starts the slice from the index 0. Meaning, S[:stop] is equivalent
to S[0:stop]
Whereas, omitting the stop index extends the slice to the end of the string.
Meaning, S[start:] is equivalent to S[start:len(S)]
Note:
Rules of slicing
==============================
http://www.visionacademe.com
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
String operator
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
[] Slice - Gives the character from the given index a[1] will give e
http://www.visionacademe.com
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
[:] 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
not in Membership - Returns true if a character does not exist in M not in a =>1
the given string
Method Description
http://www.visionacademe.com
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
txt= "Iloveapples,applearemyfavoritefruit"
x=txt.count("apple")
print(x)
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of
where it was found
txt= "Hello,welcometomyworld."
x=txt.find("welcome")
print(x)
index() Searches the string for a specified value and returns the position of
where it was found
isalpha() Returns True if all characters in the string are in the alphabet
txt= "50800"
x=txt.isdigit()
print(x)
islower() Returns True if all characters in the string are lower case
http://www.visionacademe.com
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
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
rfind() Searches the string for a specified value and returns the last position
of where it was found
rindex() Searches the string for a specified value and returns the last position
of where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
txt= "welcometothejungle"
x=txt.split()
print(x)
http://www.visionacademe.com
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
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Q List
Syntax
Listname=[value1, value2,…..valuen]
e.g
list1 = ["apple", "banana", "cherry", "apple", "cherry"]
list2 = ["abc", 34, True, 40, "male"]
print(list1)
print(list2)
http://www.visionacademe.com
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
o/p
["apple", "banana", "cherry", "apple", "cherry"]
[‘abc’, 34, True, 40, ‘male’]
OR
list = ["apple", "banana", "cherry"]
for x in list:
print(x)
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’]
http://www.visionacademe.com
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
print(thislist[2:]) o/p=>[‘cherry’,’kiwi’,’melon’,’msngo’]
print(thislist[-4:-1]) o/p=>[‘orange’,’kiwi’,’melon’]
Inserting Item
Updating List
list[2] = 2001;
http://www.visionacademe.com
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
Remove Item
o/p [‘apple’,’cherry’]
o/p [‘apple’,’cherry’]
If you do not specify the index, the pop() method removes the last item.
http://www.visionacademe.com
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
o/p [‘banana’,’cherry’]
Method Description
append() Adds an element at the end of the list fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(x)
http://www.visionacademe.com
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
print(x)
count() Returns the number of elements with fruits = ["apple", "banana", "cherry"]
the specified value x = fruits.count("cherry")
print(x)
extend() Add the elements of a list (or any fruits = ['apple', 'banana', 'cherry']
iterable), to the end of the current list cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
index() Returns the index of the first element fruits = ['apple', 'banana', 'cherry']
with the specified value x = fruits.index("cherry")
print(x)
o/p 2
reverse() Reverses the order of the list fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
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
http://www.visionacademe.com
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
print(newlist)
e.g 2
newlist = [x for x in range(10)]
print(newlist)
o/p
[0,1,2,3,4,5,6,7,8,9]
Q Python Tuple
Syntax
tupleame=(value1, value2,…..valuen)
e.g
tuple=("apple", "banana", "cherry")
print(tuple)
o/p
(‘apple’, ‘banana’, ‘cherry’)
http://www.visionacademe.com
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
Or
t = ("apple", "banana", "cherry")
for x in t:
print(x)
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
http://www.visionacademe.com
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
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
Update Items
x=("apple", "banana", "cherry")
y= list(x)
y[1]= "kiwi"
x= tuple(y)
print(x)
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
http://www.visionacademe.com
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
Unpacking Tuple
It allowed to extract the values back into variables. This is called "unpacking"
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.
http://www.visionacademe.com
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
Iteration The for loop is used to iterate over the for i in T1:
tuple elements. print(i)
Output
1
2
3
4
5
Build In function
2 len(tuple) t(1,2,3)
print len(t) o/p 3
Gives the total length of the tuple.
http://www.visionacademe.com
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
3 max(tuple) t(1,2,3)
Returns item from the tuple with max print max(t) o/p 3
value.
4 min(tuple) t(1,2,3)
Returns item from the tuple with min print min(t) o/p 1
value.
Q.Set
Syntax
tupleame={value1, value2,…..valuen}
http://www.visionacademe.com
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
Update Set
1.Add Item
2.To add items from another set into the current set, use the update() method.
thisset={"apple", "banana", "cherry"}
tropical={"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
http://www.visionacademe.com
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
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
0,6,8,1,3,5
o/p
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
Symmetric difference : {0, 1, 3, 5, 6, 8}
Q.Dictionaries
http://www.visionacademe.com
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
• It is changeable(mutable)
• Dictionaries are written with curly brackets{}, and have keys and values
Syntax
Dictionary name = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
e.g
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
o/p
{ "brand": "Ford", "model": "Mustang", "year": 1964}
http://www.visionacademe.com
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
print(x)
Update Dictionary
http://www.visionacademe.com
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
1.Add a Item
thisdict ={ "brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
2.Update Item
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
3.Remove Item
1.Using del method
thisdict= {
"brand": "Ford", "model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
http://www.visionacademe.com
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
thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict)
3. The pop() method removes the item with the specified key name
Thisdict {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
http://www.visionacademe.com
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
"year": 1964
}
thisdict.popitem()
print(thisdict)
copy()
Returns a copy of the dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
items()
get()
Returns the value of the specified key
http://www.visionacademe.com
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
car={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x=car.get("model")
print(x)
setdefault()
Returns the value of the specified key. If the key does not exist: insert the key, with the specified
value
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
keys()
http://www.visionacademe.com
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
for x in car.keys():
print(x)
values()
Returns a list of all the values in the dictionary
car={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x=car.values()
print(x)
OR
for x in thisdict.values():
print(x)
Q.Python Functions
Syntax
Python provides the def keyword to define the function
def functionname(parameters):
function_block
return expression
http://www.visionacademe.com
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
e.g 1
def display():
print("hello world")
e.g 3
def sum(a,b):
c=a+b;
return c;
a = 10
b = 20
Scope of variables
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.
http://www.visionacademe.com
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
def myfunc():
x= 300
print(x)
myfunc()
Anonymous Function
• A function without name known as anonymous function.
• A lambda function can take any number of arguments, but can only have one
expression.
Syntax
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))
Syntax
http://www.visionacademe.com
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
print(x(5)
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)
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)
http://www.visionacademe.com
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
o/p
[5, 7, 97, 77, 23, 73, 61]
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])
Q.Python Classes/Objects
http://www.visionacademe.com
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
o Polymorphism
o Data Abstraction
o Encapsulation
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Syntax
Objectname=classname(aguments)
e.g 1
class Person:
def __init__(self):#constrcutor
self.name=“amol”
self.age = 36
def myfunc(self):
print("name is " + self.name)
print("age is " + self.age)
p1=Person() #instance_creation
print(p1.name)
print(p1.age)
e.g 2
class Person:
def __init__(self,name,age): #constrcutor
self.name=name
self.age = age
http://www.visionacademe.com
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
def myfunc(self):
print("name is " + self.name)
print("age is " + self.age)
print(p1.name)
print(p1.age)
self parameter
• The self parameter is a reference to the current instance of the class and It is used
to access attribute of the class.
• It has to be the first parameter of any function in the class.
• Python will automatically send a reference to the instance. It can capture the of the
instance with any variable name(self).
Constructor
http://www.visionacademe.com
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
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
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.
http://www.visionacademe.com
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
Destructor
Syntax
def __del__(self):
# body of destructor
class SomeObj:
def __init__(self):
print('The object is created.')
def __del__(self):
print('The object is destroyed.')
obj1 = SomeObj()
obj2 = obj1
obj3 = obj1
print("Set obj1 to None...")
obj1 = None
print("Set obj2 to None...")
obj2 = None
print("Set obj3 to None...")
obj3 = None
Method Overloading
http://www.visionacademe.com
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
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.
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)
http://www.visionacademe.com
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
return Point(x, y)
p1 = Point(1, 2)
p2 = Point(2, 3)
p3=p1+p2 #p3=p1.__add__(p2)
print(p3)
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 .
http://www.visionacademe.com
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
Syntax
class derived-class(base class):
<class-suite>
e.g
class A:
def disp1(self):
print("disp1 method in base")
class B(A):
def disp2(self):
print("disp2 method in derived")
ob = B()
ob.disp1()
ob.disp2()
def disp(self):
print("a is",self.a)
print("b is",self.b)
ob=B(1,2)
ob.disp()
http://www.visionacademe.com
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
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
e.g
class A:
def disp1(self):
print("disp1 method in base")
class B(A):
def disp2(self):
print("disp2 method in derived1")
class C(B):
def disp3(self):
print("disp3 method in derived2")
ob = C()
ob.disp1()
ob.disp2()
ob.disp3()
3.Multiple inheritance: To inherit multiple base classes in the child class known as multiple
inheritance.
Syntax
class Base1:
<class-suite>
class Base2:
http://www.visionacademe.com
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
<class-suite>
class 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.
B C
class A:
def disp1(self):
http://www.visionacademe.com
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
class C(A):
def disp3(self):
print("disp3 method in derived2")
ob1 = B()
ob1.disp1()
ob1.disp2()
ob2=C()
ob2.disp1()
ob2.disp3()
Access Specifier
http://www.visionacademe.com
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
ob=Result(1,"om")
ob.disp()
__(Double The members class Student:
Private underscore) declared as def __init__(self,rollno,name):
to a variable Protected are self.__rollno=rollno
name makes accessible from self.__name=name
it private outside the class
but only in a class class Result(Student):
derived from it def disp(self):
that is in the child print("rollno is ",self.__rollno)
or subclass print("name is ",self.__name)
ob=Result(1,"om")
ob.disp()
o/p error
ob=Result(1,"om")
ob.disp()
http://www.visionacademe.com
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
Method Overriding
When the parent class method is redefined in their child class with same name with same
prototype, then the concept is called method overriding.
class A:
def func1(self):
print("this is function 1")
class B(A):
def func1(self):
super().func1()
print("this is function 2")
ob = B()
ob.func1()
Python Exception
Definition:
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.
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.
http://www.visionacademe.com
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
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric
types.
9 AssertionError
Raised in case of failure of the Assert statement.
10 AttributeError
Raised in case of failure of attribute reference or assignment.
11 EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12 ImportError
Raised when an import statement fails.
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
14 LookupError
Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
16 KeyError
Raised when the specified key is not found in the dictionary.
http://www.visionacademe.com
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
17 NameError
Raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or method
but no value has been assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python
environment.
20 IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that does
not exist.
21 IOError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.
24 SystemError
Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function.
If not handled in the code, causes the interpreter to exit.
26 TypeError
Raised when an operation or function is attempted that is invalid for
the specified data type.
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.
http://www.visionacademe.com
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
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.
Handling an exception
The try: block contains one or more statements which are likely to encounter an exception.
If the statements in this block are executed without an exception, the subsequent except:
block is skipped.
If the exception does occur, the program flow is transferred to the except: block.
The else keyword to define a block of code to be executed if no errors were raised
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
e.g
try:
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
http://www.visionacademe.com
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
Syntax
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
e.g
try:
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except (ArithmeticError,ZeroDivisionError):
print("Division by 0 not accepted")
else:
print("else block")
Finally Block
The finally block, if specified, will be executed regardless if the try block raises an error or not.
http://www.visionacademe.com
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
Syntax
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
e.g
try:
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("Division by 0 not accepted")
finally:
print("finally block")
Raise an exception
Python also provides the raise keyword to be used throw an exception to be explicitly.
Syntax
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")
http://www.visionacademe.com
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
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)
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>
http://www.visionacademe.com
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
e.g 1.Assert using without error e.g 2.Assert using without error
x = "vision"
assert x == "goodbye" x = "goodbye"
print("both strings are same")
#if condition returns False, AssertionError is
o/p AssertionError raised:
assert x == "goodbye"
print("both strings are same")
x = "vision" x = "goodbye"
#if condition returns False, AssertionError is
raised: #if condition returns False, AssertionError is
raised:
assert x == "goodbye", "both strings are assert x == "goodbye", "both strings are not
same'" same"
print("both strings are same") print("both strings are same")
o/p
o/p both strings are same
assert x == "goodbye", "both strings are not
same"
AssertionError: both strings are not same
http://www.visionacademe.com
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
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
def show(name):
print("Hello, " + name)
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")
person1={
"name": "om",
"age": 22,
http://www.visionacademe.com
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
"country": "india"
}
import mymodule
a=mymodule.person1["age"]
print(a)
It can choose to import only parts from a module, by using the from keyword.
def show(name):
print("Hello," +name)
person1={
"name": "om",
"age": 22,
"country": "india"
}
print (person1["age"])
http://www.visionacademe.com
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
from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement
from mymodule import *
print (person1["age"])
show("om")
Re-naming a Module
import mymodule as mx
a=mx.person1["age"]
print(a)
import calendar
cal = calendar.month(2021, 1)
print ("Here is the calendar:")
print (cal)
http://www.visionacademe.com
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
Tkinter(GUI) Programming
Python provides the standard library Tkinter for creating the graphical user interface for
desktop based applications.
http://www.visionacademe.com
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
• Geometry Management
All Tkinter widgets have access to specific geometry management methods, which
have the purpose of organizing widgets throughout the parent widget area. Tkinter
exposes the following geometry manager classes: pack, grid, and place.
1.Pack()
This geometry manager organizes widgets in blocks before placing them in the parent widget.
Syntax
widget.pack(options )
Here is the list of possible options −
• expand − When set to true, widget expands to fill any space not otherwise used in
widget's parent.
• fill − Determines whether widget fills any extra space allocated to it by the packer, or
keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill
only vertically), or BOTH (fill both horizontally and vertically).
• side − Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.
e.g
http://www.visionacademe.com
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
2.grid method
The grid() geometry manager organizes the widgets in the tabular form. We can specify the
rows and columns as the options in the method call. We can also specify the column span
(width) or rowspan(height) of a widget.
Syntax
widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
o Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to which, the column
is expanded.
o ipadx,ipady
It represents the number of pixels to pad the widget inside the widget's border.
o padx,pady
It represents the number of pixels to pad the widget outside the widget's border.
o row
The row number in which the widget is to be placed. The topmost row is represented
by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the widget is expanded.
http://www.visionacademe.com
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
o Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the widget
inside the cell. It may be the concatenation of the sticky letters representing the position
of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
b=0
for r in range(6):
for c in range(6):
b=b+1
Button(parent, text = str(b), borderwidth = 1 ).grid(row = r,column = c)
3.place() method
The place() geometry manager organizes the widgets to the specific x and y coordinates.
Syntax
widget.place(options)
o Anchor: It represents the exact position of the widget within the container. The default
value (direction) is NW (the upper left corner)
http://www.visionacademe.com
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
o bordermode: The default value of the border type is INSIDE that refers to ignore the
parent's inside the border. The other option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the
fraction of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the
horizontal and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.
• Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to
build the python GUI applications.
1.Label
The Label is used to specify the container box where we can place the text or images. This
widget is used to provide the message to the user about other widgets used in the python
application.
Syntax
http://www.visionacademe.com
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
SN Option Description
1 anchor It specifies the exact position of the text within the size provided to
the widget. The default value is CENTER, which is used to center
the text within the specified space.
3 bitmap It is used to set the bitmap to the graphical object specified so that,
the label can represent the graphics instead of text.
5 cursor The mouse pointer will be changed to the type of the cursor
specified, i.e., arrow, dot, etc.
6 font The font type of the text written inside the widget.
10 justify It is used to represent the orientation of the text if the text contains
multiple lines. It can be set to LEFT for left justification, RIGHT for
right justification, and CENTER for center justification.
14 text This is set to the string variable which may contain one or more line
of text.
http://www.visionacademe.com
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
15 textvariable The text written inside the widget is set to the control variable
StringVar so that it can be accessed and changed accordingly.
16 underline We can display a line under the specified letter of the text. Set this
option to the number of the letter under which the line will be
displayed.
18 wraplength Instead of having only one line as the label text, we can break it to
the number of lines where each line has the number of characters
specified to this option.
2. Entry
The Entry widget is used to provde the single line text-box to the user to accept a value from
the user. We can use the Entry widget to accept the text strings from the user. It can only be
used for one line of text from the user. For multiple lines of text, we must use the text widget.
Syntax
w = Entry (parent, options)
SN Option Description
http://www.visionacademe.com
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
3 Cursor The mouse pointer will be changed to the cursor type set to the
arrow, dot, etc.
4 Exportselection The text written inside the entry box will be automatically
copied to the clipboard by default. We can set the
exportselection to 0 to not copy this.
8 Highlightcolor It represents the color to use for the traversal highlight rectangle
that is drawn around the widget when it has the input focus.
14 Insertwidth It represents the value indicating the total width of the insertion
cursor. The value may have any of the forms acceptable to
Tk_GetPixels.
http://www.visionacademe.com
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
15 Justify It specifies how the text is organized if the text contains multiple
lines.
16 Relief It specifies the type of the border. Its default value is FLAT.
18 Selectborderwidth The width of the border to display around the selected task.
20 show It is used to show the entry text of some other type instead of the
string. For example, the password is typed using stars (*).
21 textvariable It is set to the instance of the StringVar to retrieve the text from
the entry.
Methods
SN Method Description
1 delete(first, last = none) It is used to delete the specified characters inside the widget.
http://www.visionacademe.com
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
3.Button
The button widget is used to add various types of buttons to the python application.
Syntax
W = Button(parent, options)
http://www.visionacademe.com
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
SN Option Description
1 activebackground It represents the background of the button when the mouse hover the
button.
2 activeforeground It represents the font color of the button when the mouse hover the
button.
5 Command It is set to the function call which is scheduled when the function is
called.
8 Height The height of the button. The height is represented in the number of
text lines for the textual lines or the number of pixels for the images.
10 Highlightcolor The color of the highlight when the button has the focus.
12 justify It illustrates the way by which the multiple text lines are represented.
It is set to LEFT for left justification, RIGHT for the right
justification, and CENTER for the center.
http://www.visionacademe.com
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
19 Width The width of the button. It exists as a number of letters for textual
buttons or pixels for image buttons.
20 Wraplength If the value is set to a positive number, the text lines will be wrapped
to fit within this length.
e.g 1.
b = Button(parent,text = "OK").place(x=80,y=50)
e.g2
from tkinter import *
parent = Tk()
parent.geometry("400x250")
def fun():
msg=Message(parent, text = "Welcome").pack()
e.g3
Addition of two number
parent = Tk()
parent.geometry('400x200+100+200')
http://www.visionacademe.com
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
parent.title('Calculator')
number1 = StringVar()
number2 = StringVar()
labelResult = Label(parent)
labelResult.grid(row=7, column=2)
parent.mainloop()
Note: In command ,yu can’t calling function using arguments, so it used lemda
or partial function.
3. Frame
Python Tkinter Frame widget is used to organize the group of widgets. It acts like a container
which can be used to hold the other widgets. The rectangular areas of the screen are used to
organize the widgets to the python application.
Syntax
w = Frame(parent, options)
SN Option Description
http://www.visionacademe.com
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
3 Cursor The mouse pointer is changed to the cursor type set to different
values like an arrow, dot, etc.
7 highlightthickness It specifies the thickness around the border when the widget is
under the focus.
8 Relief It specifies the type of the border. The default value if FLAT.
parent = Tk()
frame = Frame(parent)
frame.pack()
bottomframe = Frame(parent)
bottomframe.pack( side = BOTTOM )
http://www.visionacademe.com
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
parent.mainloop()
4.messagebox
The messagebox module is used to display the message boxes in the python applications. There
are the various functions which are used to display the relevant messages depending upon the
application requirements.
Syntax
messagebox.function_name(title, message [, options])
Parameters
o function_name: It represents an appropriate message box function.
o title: It is a string which is shown as a title of a message box.
o message: It is the string to be displayed as a message on the message box.
o options: There are various options which can be used to configure the message dialog
box.
The two options that can be used are default and parent.
1. default
http://www.visionacademe.com
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
o The default option is used to mention the types of the default button, i.e. ABORT,
RETRY, or IGNORE in the message box.
2. parent
o The parent option specifies the parent window on top of which, the message box is to
be displayed.
You could use one of the following functions with dialogue box .
1. showinfo()
2. showwarning()
3. showerror()
4. askquestion()
5. askokcancel()
6. askyesno()
7. askretrycancel()
e.g
from tkinter import *
from tkinter import messagebox
parent = Tk()
parent.geometry("100x100")
messagebox.showinfo("information","Information")
parent.mainloop()
5.Checkbutton
http://www.visionacademe.com
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
The Checkbutton widget is used to display a number of options to a user as toggle buttons.
The user can then select one or more options by clicking the button corresponding to each
option.
Syntax
w = checkbutton(master, options)
SN Option Description
7 Cursor The mouse pointer will be changed to the cursor name when it
is over the checkbutton.
12 Highlightcolor The color of the focus highlight when the checkbutton is under
focus.
http://www.visionacademe.com
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
14 Justify This specifies the justification of the text if the text contains
multiple lines.
25 Variable It represents the associated variable that tracks the state of the
checkbutton.
27 Wraplength If this option is set to an integer number, the text will be broken
into the number of pieces.
Methods
The methods that can be called with the Checkbuttons are described in the following table.
http://www.visionacademe.com
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
SN Method Description
3 invoke() This will invoke the method associated with the checkbutton.
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue = 0,
height = 2, width = 10)
chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1, offvalue = 0,
height = 2, width = 10)
chkbtn1.pack()
chkbtn2.pack()
top.mainloop()
6. Radiobutton
The Radiobutton widget is used to implement one-of-many selection in the python application.
It shows multiple choices to the user out of which, the user can select only one out of them.
Syntax
w = Radiobutton(top, options)
http://www.visionacademe.com
105 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
SN Option Description
1 activebackground The background color of the widget when it has the focus.
2 activeforeground The font color of the widget text when it has the focus.
13 highlightbackground The color of the focus highlight when the widget is not
having the focus.
http://www.visionacademe.com
106 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
21 State It represents the state of the radio button. The default state
of the Radiobutton is NORMAL. However, we can set
this to DISABLED to make the radiobutton
unresponsive.
24 underline The default value of this option is -1, however, we can set
this option to the number of character which is to be
underlined.
http://www.visionacademe.com
107 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
SN Method Description
2 flash() It is used to flash the radiobutton between its active and normal colors few
times.
3 invoke() It is used to call any procedure associated when the state of a Radiobutton is
changed.
e.g
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
parent = Tk()
parent.geometry("200x200")
var = IntVar()
R1 = Radiobutton(parent, text="BCS", variable=var, value=1,command=sel)
R1.pack()
R2 = Radiobutton(parent, text="BBA", variable=var, value=2,command=sel)
R2.pack()
R3 = Radiobutton(parent, text="BCA", variable=var, value=3,command=sel)
R3.pack()
label = Label(parent)
label.pack()
http://www.visionacademe.com
108 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
parent.mainloop()
7.Listbox
The Listbox widget is used to display the list items to the user. We can place only text items in
the Listbox and all text items contain the same font and color.
The user can choose one or more items from the list depending upon the configuration.
Syntax
w = Listbox(parent, options)
SN Option Description
3 cursor The mouse pointer will look like the cursor type like dot, arrow, etc.
6 height It represents the count of the lines shown in the Listbox. The default
value is 10.
7 highlightcolor The color of the Listbox items when the widget is under focus.
10 selectbackground The background color that is used to display the selected text.
11 selectmode It is used to determine the number of items that can be selected from
the list. It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED.
http://www.visionacademe.com
109 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
Methods
SN Method Description
3 delete(first, last = None) It is used to delete the lines which exist in the given range.
4 get(first, last = None) It is used to get the list items that exist in the given range.
5 index(i) It is used to place the line with the specified index at the
top of the widget.
6 insert(index, *elements) It is used to insert the new lines with the specified number
of elements before the specified index.
http://www.visionacademe.com
110 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
parent = Tk()
parent.geometry("200x250")
listbox = Listbox(parent)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
parent.mainloop()
8.Message
The Message widget is used to show the message to the user regarding the behaviour of the
python application. The message widget shows the text messages to the user which can not be
edited.
http://www.visionacademe.com
111 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
Syntax
w = Message(parent, options)
SN Option Description
1 anchor It is used to decide the exact position of the text within the space
provided to the widget if the widget contains more space than
the need of the text. The default is CENTER.
4 bd It represents the size of the border in the pixel. The default size
is 2 pixel.
5 cursor The mouse pointer is changed to the specified cursor type. The
cursor type can be an arrow, dot, etc.
9 image We can set this option to a static image to show that onto the
widget.
http://www.visionacademe.com
112 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
13 relief It represents the type of the border. The default type is FLAT.
14 text We can set this option to the string so that the widget can
represent the specified text.
15 textvariable This is used to control the text represented by the widget. The
textvariable can be set to the text that is shown in the widget.
18 wraplength We can wrap the text to the number of lines by setting this
option to the desired number so that each line contains only that
number of characters.
top = Tk()
top.geometry("100x100")
var = StringVar()
msg = Message( top, text = "Welcome to Javatpoint")
msg.pack()
top.mainloop()
http://www.visionacademe.com