0% found this document useful (0 votes)
28 views41 pages

Python Notes

The document provides an introduction to Python, covering its features, data types, and programming concepts such as object-oriented programming, exception handling, and GUI development. It highlights Python's versatility, ease of learning, and capabilities in various applications, including mathematics, text processing, and database interaction. Additionally, it discusses Python's historical development and its compatibility with different operating systems.

Uploaded by

vinay21swami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views41 pages

Python Notes

The document provides an introduction to Python, covering its features, data types, and programming concepts such as object-oriented programming, exception handling, and GUI development. It highlights Python's versatility, ease of learning, and capabilities in various applications, including mathematics, text processing, and database interaction. Additionally, it discusses Python's historical development and its compatibility with different operating systems.

Uploaded by

vinay21swami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit - I Introduction

1.1 Introduction to Python


1.1 Introduction to Python 1.2 Features of - Python is a general-purpose interpreted,
python interactive, object-oriented, and high-level
1.3 What Can I Do with Python? 1.4 Python programming language.
Interpreter - It was created by Guido van Rossum during
1.5 Data types, Variables, Comments, Operators, 1985- 1990.
expressions; input, processing and output statements - Like Perl, Python source code is also available
1.6 Control Structures: loops and decision under the GNU General Public License (GPL).
Unit – II String Handling, Classes, Modules and - Python is designed as highly readable language as
Package it uses many english keywords frequently.
2.1 Strings, String operations and String Slicing - It uses PVM (Python Virtual Machine) to
2.2 Defining Classes translates phyton script into bytecodes.
2.3 Defining and calling functions passing arguments - Thus python code becomes platform and
to functions operating system independent
2.4 Python and OOP – Inheritance, polymorphism - Python also supports RAD on different OS
2.5 Modules – datetime, math platforms like MacOS, Windows, Unix, etc as well
2.6 Packages as python can also be executed on MS-DOS, OS/2
Unit – III - Exception Handling and Collections and other operating systems.
3.1 Exception in python 3.2 Exception roles [python name taken from Comedy group named
3.3 Exception Handling 3.4 Collections in Monty Python, this group was having many
Python – List, Tuples, Dictionaries, Sets popular comedians as members].
Unit – IV - GUI Programming and Database - Python as prog language shows following imp
Connectivity Using Python characteristics:-
4.1 Graphical User Interfaces 4.2 Using the tkinter o It supports functional and structured
Module programming methods.
4.3 Creating Label, Text, Button, info Dialog Boxes, o It supports OOP programming methods.
Radiobutton, Checkbutton o It can be used as scripting language to
4.4 Getting Input build large applications.
4.5 Importing MySQL for Python o Supports high-level dynamic data types
4.6 Connecting with a database and supports dynamic type checking.
4.7 Forming a query in MySQL o It supports automatic garbage
4.8 Passing a query to MySQL collection.

Unit - I Introduction
1
o It can be easily integrated with other o Python 1.5.2 – Released in April-1999.
languages like C, C++, COM, ActiveX, It includes most the functionalities
java, etc required in Modern Prog language.
- Python provides many benefits like- o Python 1.6. – Released in Sep-2000. In
o Easy to learn – as it uses few keywords, this new features like list objects,
simple structure and simple syntax. socket and string number conversion
o Easy to read – as it uses many English tools are included.
keywords hence easy to read o Python 2.0 – Oct-2000 – in this old
o Easy to maintain – due to structured Java-based python interpreter is
programming, python code is easy to renewed to hybrid interpreter ie. Jython
maintain. hybrid.
o Collection of std library – to performs o Python 3000 – still under development
different operations it provides many as Python 3000 code name.
std lib to make the code easy. 1.2 Features of python
o Interactive mode - supports interactive 1. Python is Free – Python can be implemented
way of testing and debugging of python without purchase of any software or there is no
code. licensing issues.
o Portable – it can run on any hardware or 2. Portable – python code can be developed on
OS platform. any hardware or software platform and can be
o Extendable – new modules can be easily transferred to any other hardware or
easily added to existing code so that it software platform.
can be extended. 3. Extensible – The complete python language is
o Database Interaction – Python can be written in C language and it’s original code is also
connected with any std database available, hence any one can download it, and can
application to read and write data. add new features to it, thus python language can be
o GUI Programming – Graphics extended to support new features.
interfaces can also be created using 4. Database Interaction – Python can be connected
python. with any std database application to read and write
o Scalable – python code size can be data.
changed at any time and can also 5. GUI Programming – Graphics interfaces can also
handle small as well as large size data. be created using python.
- Major historical development in Python 6. Scalable - python code size can be changed at any
language are:- time and can also handle small as well as large size
data

2
7. C/C++ Embedding – Python code can be o Scalable – python code size can be
embedded into C or C++ applications. changed at any time and can also
8. Powerful language - python library comes with handle small as well as large size data.
huge library of useful modules that supports
programmer to perform 1.3 What Can I Do with Python?
▪ Network communication - As python is high-level interactive OOP language, it
▪ Text processing helps to develop application for different areas of
▪ Regular expression matching Computer Applications like:
▪ Low-level operations of 1. Mathematics - To develop scientific and
Operating system engineering applications many mathematical
- The other features of python can be enlisted as: expressions are required in simplified form
o Easy to learn – as it uses few keywords, - Python provides extensions/library i.e NumPy
simple structure and simple syntax. which allows to interact and use mathematics
o Easy to read – as it uses many English libraries.
keywords hence easy to read - It helps to performs simple calculations as well
o Easy to maintain – due to structured as highly-complicated calculations with value
programming, python code is easy to of any digits.
maintain. 2. Text Processing –
o Collection of std library – to performs - Python provides all the
different operations it provides many functionalities/modules required for text
std lib to make the code eay. processing like
o Interactive mode - supports interactive Splitting
way of testing and debugging of python Separting &
code. Summarizing of data.
o Portable – it can run on any hardware or - With the help of data types, data collected can
OS platform. be stored for processing.
o Extendable – new modules can be - With regular expression, data validations can
easily added to existing code so that it be performed like checking of valid email id,
can be extended. contact number, etc.
o Database Interaction – Python can be - Also python allows to give output in different
connected with any std database formats like HTML, GIF, etc
application to read and write data. 3. RAD – python provides many built-in libraries
o GUI Programming – Graphics hence it allows to develop applications at high
interfaces can also be created using speed. Due to interpreter facility, every time,
python.
3
after making changes no time to spend on - As python is high level interpreted language,
compilation, directly it can be interpreted. it’s execution requires Python interpreter.
Also, due to interactive de-bugging facility, it - An interpreter is a kind of program that executes
is more easy and fast to find error and solve it. other programs.
4. Cross-Platform Development – As python is - Python code first converted into intermediate code
platform independent (portable) language, i.e. byte code (as in java language).
hence it’s code can be executed on any - This intermediate code is translated in machine
hardware and software platform. language code for execution.
This is very important when in network same
python application to be executed and in such
network systems are using different hardware
and OS platform.
5. System Utilities – python can is allowed to
access low-level functionalities of OS hence a
powerful python code can be developed to
make system utility such as Operating system - Once python code is converted into byte code,
tools e.g. Antivirus, Disk Cleanup Tool, it is saved in a file with .pyc extension.
Backup & Recovery Tools etc - Python interpreter takes raw-text source code
6. Internet Programming – python provides and executes each statement.
powerful modules that allow to communicate - Python statements can be executed in following
using network sockets at both levels : ways-
a. Basic level o Directly python statement can be given
b. Protocol level to interpreter – any executable
o Python code can read email using POP statement can be given to python
server interpreter prompt >>> as
o Can give input to web-server and get e.g. >>> print (“Hello”)
high-quality formatted output or
7. Database Programming – Python provides >>> print (‘Hello’)
many modules that helps to connect python
code to be connected with different database
like Oracle, MYSQL,Informix, MS-SQL etc. o Python statement can be saved in file
and then executed by interpreter.
Start Python Idle → go to file menu →
1.4 Python Interpreter New→ type the python code-→ File menu
→ Save → give filename
4
In Run menu → Select Run Module or Each data element is also must be associated
Press F5 with key.
e.g. Multiple value-key pair must be separated by
1.5 Data types comma and all values must be enclosed in
- Python as programming language supports data curly braces as:
types using which variable can be created. <DictName>={Key:Value,Key:value,……..}
- Python provides following standard data types which e.g. values={1:100,5:250,3:120}
decides How which value to be stored? - in same dictionary, key can be of same type
or different types.
e.g. values={1:’Abc’,5.5:250,’X’:12.90}
- In this, values can be duplicate, but keys must
be unique
- if key is repeated, then previous value of same
key is replaced by new value.
- Dictionary supports following useful
methods
i) keys() – returns only the keys used to
create dictionary items.
1) Numeric – It represents numeric value in ii) values() – returns only the values in
following different forms- dictionary.
a. Integer – numeric value without iii) clear() – deletes all the items in the
decimal point. dictionary.
e.g. a=100 -len() function can be used to count number of items
b. Complex number – it combination present in dictionary as:
multiple real or floating numbers. In print(len([Link]())
this, the number must be suffixed by j e.g
or J as a={1.8:200,7:'Abc','X':45.7}
a=1.3+3.4j print("All Keys and values=",a)
c. Float – it is a single numeric value with print("Total Number of Items",len([Link]()))
decimal point as print("All Keys are=",([Link]()))
e.g. a=12.34 print("All values are=",[Link]())

2. Dictionary – It is an associative array i.e.


collection of unordered set of data elements.

5
3. Boolean – This data type provides two built-in i) Strings – It represents sequence of
values True and False. It can be used as: character or collection of bytes in
a=True quotation marks.
print(type(a)) note: T and F of values - Python allows, string to be enclosed in single,
must be capitals, if used small, will show error. double or triple quotes.
4. Set e.g.
- Set datatype in python represents the s1='FYBCA'
unordered collection of the data type. s2="SYBCA"
- It is iterable, mutable (can modify after s3='''TYBCA'''
creation), and has unique elements. print("String-1=",s1)
- In set, the order of the elements is undefined; print("String-2=",s2)
it may return the changed sequence of the print("String-3=",s3)
element. - As like java & other languages, string indexing
- values in set can be of same or different in python also starts with zero.
types: - This indexing helps in performing different
- The set can be created in one of the string manipulations like
following ways: a) Extracting single char – a single character
at given position can be extracted as:
i) by using a built-in function set(), as:
StringName[Index]
setName=set((value1,value2,value3………)) e.g.
s1='Hello India'
a=set(('Abc',300,35.77))
print("Sub String=",s1[3])
print("All the Elements in Set=",a)
b) Extracting sub-string – to extract set of
output-
characters, start index and number of
All the Elements in Set= {35.77, 300, 'Abc'}
characters to be specified as:
ii) group of elements is passed in the
StringName[startIndex:NumberofChars]
curly braces and separated by the comma. It
s1='Hello India'
can contain various types of values.
print("Sub String=",s1[0:3])
a={44,'Abc',89.09,"Xyz",100}
c) Repeating string – same string can be
print("All the Elements in Set=",a)
repeated using * operator as
output-
StringName * int
All the Elements in Set= {100, 'Abc', 44, 89.09, 'Xyz'}
Eg
3. Sequence Type – Sequence data type
s1='Hello'
represents collection of data elements.
print("Repeated String=",s1*3)
Python supports following sequence sub-
Output –
types
Repeated String= HelloHelloHello

6
ii) List – It represents “list” class type data1=["Abc",1001,1.11,'Z']
of python language. print (data1*2)
- Python list is similar to array of C, C++ and output
java like languages i.e. to store collection of ['Abc', 1001, 1.11, 'Z', 'Abc', 1001, 1.11, 'Z']
data elements. - List is dynamic data structure, hence allows to
- But it also can contain multiple elements of add new elements as well as removes existing
same as well as different data types. elements from list at runtime
- To store data items in list, items to be separated - For this, it supports following methods
by comma and enclosed in brackets [] o append(DataItem) – it add new
e.g. element at the end of existing list as
data=["Abc",1001,78.99,'A'] e.g. [Link](100)
print ("Current Data=",data) o insert(index,value) – it inserts new
output element at the given index by
Current Data= ['Abc', 1001, shifting existing element forward
78.99, 'A'] e.g. [Link](1,’Demo’)
- On list following different operations are o remove() - it removes existing data
supported: element from list with backward
o : (Slicing) - it is used to shift.
slice or separate list data items as: e.g. [Link](1001)
print(data1[2:]) – it will print all from elements from if given value/item not exiting, then
2nd index as generates error - ValueError:
[78.99, 'A'] [Link](x): x not in list
print(data1[1:3]) – it will print all from elements from e.g.
index 1 to 3-1 data1=["Abc",1001,1.11,'Z']
[1001, 78.99] print ("Current Data
o + (Concatenation) - it is Elements=",data1)
used to concatenate items of multiple [Link](100)
list as: print ("After Appending=",data1)
data1=["Abc",1001,1.11,'Z'] [Link](1,'DEMO')
data2=["Xyz",2001,2.22,'Z'] print ("After Insert",data1)
print (data1+data2) [Link](1001)
output – print ("AFter removing",data1)Tuple
['Abc', 1001, 1.11, 'Z', 'Xyz', 2001, 2.22, 'Z'] output
o *(Repetition) - to repeat each data Current Data Elements= ['Abc', 1001, 1.11, 'Z']
items in list for given number of times: After Appending= ['Abc', 1001, 1.11, 'Z', 100]
7
After Insert ['Abc', 'DEMO', 1001, 1.11, 'Z', 100] o *(Repetition) - to repeat each data
AFter removing ['Abc', 'DEMO', 1.11, 'Z', 100] items in list for given number of times:
iii) Tuple – It is one sequence type in Python language data1=("Abc",1001,1.11,'Z')
and it represents “tuple” lib class of java lang. print (data1*2)
- It represents collection of data items of same as output
well as different types. ['Abc', 1001, 1.11, 'Z', 'Abc', 1001, 1.11, 'Z']
- It is alike list, but with imp difference that – it
is read-only data structure i.e. the data items *Variables
in list can not be added or removed at run- - Python program may needs data element for it’s
time execution.
- The items of the tuple are separated with a - Such data element can be stored using variable so
comma (,) and enclosed in parentheses (). that it can be processed any time.
e.g. - Variable is reserved memory location to hold/store
data1=("Abc",1001,1.11,'Z') required value.
print ("Current Tuple Values=",data1) - For which variable, how much memory is required is
output – decided on the basis of data type of that variable.
Current Tuple Values= ('Abc', 1001, 1.11, 'Z') - as per the datatype or type of value stored in variable,
- As like list, Tuple also supports following interpreter decides and allocates memory to variable.
operations - A python prog may uses single or multiple variables.
o : (Slicing) - it is used to - As oppose to C,C++,Java languages, Python does
slice or separate list data items as: not needs explicit declaration for variable & to
print(data1[2:]) – it will print all from elements from reserve memory space.
2nd index as - Based on the data type of a variable, Therefore, by
[1.11, 'Z'] assigning different data types to variables, you can
print(data1[1:3]) – it will print all from elements from store integers, decimals or characters in these
index 1 to 3-1 variables.
[1001, 1.11] - While creating variable, a valid variable name must
o + (Concatenation) - it is be assigned as per variable naming conventions.
used to concatenate items of multiple - Value to any variable can be assigned in two ways:
list as: 1) Static assignment 2) Dynamic assignment
data1=("Abc",1001,1.11,'Z') 1) Static assignment – in this, value to any
data2=("Xyz",2001,2.22,'Z') variable can be assigned directly in prog code using =
print (data1+data2) operator as:
output – VariableName=value
['Abc', 1001, 1.11, 'Z', 'Xyz', 2001, 2.22, 'Z'] e.g. ctr=100
8
Prog code- print("Type of variable a=",type(a),"value in
a=12 a=",a)
b=15.67 a=input("Enter a value==")
c='A' print("Type of variable a=",type(a),"value in
d='Abc Xyz' a=",a)
print("Type of variable a=",type(a),"value in a=input("Enter a value==")
a=",a) print("Type of variable a=",type(a),"value in
print("Type of variable a=",type(b),"value in a=",a)
a=",b) a=input("Enter a value==")
print("Type of variable a=",type(c),"value in print("Type of variable a=",type(a),"value in
a=",c) a=",a)
print("Type of variable a=",type(d),"value in Output-
a=",d) Enter a value=="Abc"
Output – ('Type of variable a=', < class 'str'>, 'value in a=',
('Type of variable a=', <class 'int'>, 'Abc')
'value in a=', 12) Enter a value==35.7
('Type of variable a=', < class 'float'>, ('Type of variable a=', < class 'float'>,
'value in a=', 15.67) 'value in a=', 35.7)
('Type of variable a=', < class 'str'>, Enter a value=='A'
'value in a=', 'A') ('Type of variable a=', < class 'str'>,
('Type of variable a=', < class 'str'>, 'value in a=', 'A')
'value in a=', 'Abc Xyz') Enter a value==12
2) Dynamic assignment – value to variable cn ('Type of variable a=', < class 'int'>,
be assigned dynamically at runtime using input() 'value in a=', 12)
method as:
VariableName=input(“Dummy Msg”) Comments- Prog may contain simple as well as
num=input(“Enter a number=”) complex code to complete given task.
- Based on input value, datatype of variable will - Also in many cases, it is possible that, code
be decided. created by one programmer is to be modified
- Only one input is possible using one input() by other programmer.
statement, hence prog can use any number of - In such case, the prog code must be easy to
input statements. understand for any programmer.
e.g. - For this, it is recommended that, in prog at
a=input("Enter a value==") required places comment is used.

9
- Comment is one read-only statement which is operations on given operands. These
neither compiled nor executed. operators are like:
- It helps to enhance program readability for any + →addition - →subtraction
programmer. * → Multiplication / → Division
- In C,C++,Java like languages, comment can be % → modulo / remainder
either ** → Exponent
o single line using // // → floor division
o or multi-line using /* ….*/ 2) Relational or Comparison – These
- But python supports only single line comment operators are used to check the relation
using # symbol. between two operands by comparison.
- Any statement in python if pre-fixed with # o These operators returns Boolean value
symbol will become comment which is neither true or false after comparison. These
compiled nor executed as: operators are:
# statement == → equality != → Not Equal
e.g. <= → Less than or equal
#python uses variable >=→ Greater than or equal
# python variable demo < → less than > → Greater than
A=10 These operators are mostly used to
print(“Value in A=”+A) compose conditional statements in prog
* Operators- code.
- It is one type of token used by any programming 3) Assignment – these operators are used
language. to assign right-hand side value to left-
- Operator is one special character or symbol hand side operand as
associated with pre-defined operation and when used = → simple assignment += →
performs it’s pre-defined operations. Addition/increase and then assignment
- Operator to complete it’s operation always uses -= → subtraction/decrease then assignment
operand which any value or variable. *= → multiply & then assignment
- Operators as one of the basic/fundamental entity of /= →Division & then assignment
programming language helps to apply required logic in %= → remainder assignment
prog code. **= → Exponent and then assignment
- python supports following different types of //= → Floor Division
operators – e.g.
1) Arithmetic operators – these are used 4) Bitwise – these operators are used to operate on low
to perform arithmetic/mathematical level or binary values.

10
5) Membership – These operators helps to find given ▪ Value in A variable will be 25.
data element is present or is member of given - Operator precedence can be changed using
sequence. Python supports following membership parenthesis ( ) as:
operators:- o A=(10+5)*3
i) IN – It returns TRUE if given entity is ▪ In above case first, + will be
present in sequence else FALSE. evaluated & then *, hence Value
ii) NOT IN - It returns FALSE if given entity in A variable will be 45.
is present in sequence else TRUE. * Expressions
6) Identity operators – These operators are used - It is one of the common programming entity used in
to compare: prog code of any programming language.
i. Memory locations & - It is a prog code line / statement in which operators,
ii. Contents of memory locations. operands or both are used properly to make a
- Under this category, two operators are meaningful statement.
supported as: - Python supports following different types of
i) is – returns true if both variables points same expressions:-
memory location else returns false. i. Constant Expression – expression which is using
ii) is not - returns false if both variables points constant value e.g. a=90
same memory location else returns true. ii. Arithmetic Expressions – expression using any or
suppose there are two variables with values like all arithmetic operators like
a=10 a=10+20
b=10 a=10*5+3
if we check these two as : iii. integral expression – expression that generates /
a is b → it will return true produces only integer value e.g. a=10+20
a is not b→ it will return false iv. floating expression - expression that generates /
- Operators helps to compose an expression in produces only floating value e.g. a=10/3 returns 3.33
prog code like: v. Relational Expression – expression which is
o A=10+20 composed using relational operators (<, >, <=, etc)
- All operators also have their pre-defined v. Logical Expression - expression which is
precedence and always follows the precedence composed using logical operators (&&, or, not , etc)
rule like vi. bitwise expression - expression which is composed
o When + (Addition) and * using bitwise(<<<, >>>) operators .
(Multiplication) operators are used in vi. combinational expression – when in a single
same expression then, * will be expression, other types of expressions are combined, it
evaluated first & then + like make combinational expression as
o A=10+5*3
11
a=10+(5/3) - combination of constant ii. printing with escape sequence characters
expression, arithmetic and floating expressions. - as like C, python also allows to use following escape
input Statements – the programming statement which sequence chars
is useful to get input from user during prog execution \n – new line
time is called input statement. \t – tab space
- For this python supports input() function as: print(‘Any message \t Any message \n Any Message’)
VariableName=input(“Message”) iii. printing defined output or variable output
Sname=input(“Enter Student Name=”) print(VariableName)
- The input taken using input statement is by a=10
default is of string type, hence if numerical print(a)
value is taken as input and if arithmetic iii. printing combined output – undefined and
operations to be performed on it, then it must defined output can be printed, for this comma (,) can
be type casted as : be used as separator
- E.g. num1=int(input(“Enter a number=”)) a=10
- Num2=float(input(“Enter a number=”)) print(‘Value of a=’,a)
e.g iv. Printing with format character –As like C lang,
import math python also allows to use format chars such as
a=int(input("Enter a number=")) %d – for integer
print ("Sq Root=", [Link](a)) %f – for float
Output Statements %c – for char
- The statement in programming code which completes As
the job to print or write output on any output location. print(‘ any message %char’ %VariableName)
- Python uses print( ) lib function to give output at A=10
specified output location. print(‘int value=%d’ %A)
- Python code can use following output destinations :- v. printing selected number of digits in real value
1. Std Output Device n=234.6754327
2. File print('Float value %0.2f' %n)
1. Std Output Device – print( ) by default writes output vi. printing without new line
on std output device as: - By default print( ) gives new line after writing
print(“Hello) the output on output screen.
- This Std output can be given in following different - To avoid new line, the “end” parameter can be
forms as:- used as
i. printing dummy message print(‘output’,end=’ ‘) – prints with space
print(‘Any message’) print(‘output’,end=’\t’) – print with tab space
print(“Any message”) print(101,end=’\t’)
12
print(‘Abc’) ---
output- - enclosing condition in parenthesis is
101 Abc optional.
1.6 Control Structures: loops and decision - In this, prog uses only true block which is
- Program code to complete its job get executed in a executed when the given condition is true or
defined style. satisfied.
- After if statement the true block must be
- The style or pattern in which prog code executed is
indented.
called control structure or control flow.

- control structure or control flow in programming can


be of following types –

1) Sequential flow
2) Conditional flow
3) Selection flow
4) Loop flow
1. Sequential flow – in this flow, line by line program
gets executed.
- It is also called as default flow used by any program.
- In this order of program code and order of execution
E.g. – program to get input of one number, check
is same.
and display is it positive number.
e.g. program to get input of two number, display
a=int(input('Enter a Number='))
original and swapped numbers.
if (a>0):
2. Conditional Flow /selection flow/ Decision
print( "Yes")
Making – In this, program code executed on the basis
ii) if….else – it is used to implement two-way
of given condition or expression.
branching or decision making during program
- Following conditional statements can be used in
execution.
python code-
- It uses two separate block of code, one as true
i) simple if – it is used to implement one-way
block and other is false block.
branching or decision making during program
- When the condition is satisfied, true block
execution.
executes, when it is fail, false block executed
Syntax
as:
if (<exp/condition>):
----
--- true block----

13
---true block1---
elif<condition2/exp>:
---true block2---
elif<condition3/exp>:
---true block3---
else:
---else / false block---

- Program always evaluates condition 1, when it


is satisfied, its true block executed else it go to
next condition and so on.
Syntax - When none of the condition is true, it executes
if<condition/exp>: else block.
------ e.g. program to get input of one number, check and
---true block--- display is it positive,negative or neutral number.
----------- a=int(input("Enter a number"))
else: if(a>0):
print("+Ve")
------ elif (a<0):
---false block--- print("-Ve")
else:
----------- print("Neutral")
- The statements in if or else block must be
iv) Nested if
properly indented. - In existing if block other if block enclosed it is called
- E.g. – program to get input of one number, as nested if.
- in simple words, if…with in …if is also called as
check and display is it positive or negative Nested if.
number. - In this, there will be one outer or parent condition
and one inner condition.
a=int(input('Enter a Number=')) - First outer condition will be tested, and when this
if(a>0): condition is true/satisfied then only it will go for inner
print(‘Number is Positive’) condition.
else: - Thus it helps to define blocks of inter-dependent
print(‘Number is Negative’) conditions.
Syntax:
iii) if..elif statement –it is used to apply multi-way if(<Condtion1>): #outer condition
branching during program execution. ------
------
- In this series of conditions are arranged in if(<Condition1>):#inner condition
sequence which are evaluated sequentially. ---------
else: #inner else block
Syntax: ------
if<condition1/exp>: else:#outer else block

14
-------- a=int(input("Enter a number="))
if(a>0):
- When outer condition is true, control enters in it’s print("+ve")
block, then it will check inner condition. else:
- When inner condition is true, it executes it’s true pass
block otherwise executes inner else block.
-In case, outer condition is fail, it will execute outer * switch …case replacement
else block. - python does not support case statement as like in
e.g. C,C++ or java like languages.
prog to get input of one number, check is it Positive or - Instead, python supports alternate technique to
Negative, and if it is positive check is it ODD or implement switch-case.
EVEN. - In python, switcher{} block can be used to
a=int(input("Enter a number=")) implement switch case.
if(a>0): - In switcher block labeled block to be defined. This
print("+Ve") label can be int, char, string or float value as:
if(a % 2 ==0):
print("EVEN")
else: switcher={
print("ODD") label1:---statement----,
else: label2:---statement----,
print("-VE") .
.
v) using pass statement .
- In some cases, if statement to be kept empty, but as }
per syntax rules, it can not be kept. return [Link](<exp>,"msg")
- When if statement to be defined with no content or - In single switcher block, label of different data types
block, it will generate error. can be used..
- To avoid this, python supports use of “pass” - return statement is used to return invalid choice.
statement. - To use switcher following steps are needed:
- “pass” statement can be used either with if statement →define a function with argument
or with else statement. → define switcher block
- whenever it is used, that block is skipped for → from interpreter call above function with parameter.
execution. e.g.
syntax: def f1(ch):
if(Condtion): switcher={
pass 1:'This is case1',
else: 1.5:'This is case2',
--- else block---- 'a':'This is case3',
"xyz":'This is case4'
e.g.1 }
a=int(input("Enter a number=")) return [Link](ch,'Invalid Choice')
if(a>0): - To call above code use following statement
pass >>>f1(1.5)
else: output
print(“Value is Negative”) This is case2

OR 3. Looping or Iteration Flow


if(Condtion): - Looping is the programming technique by which
---true block--- block of code can be repeatedly executed for fixed
else: number of time.
pass - python supports following looping statements.
e.g.1 1) while statement 2) for statement
15
1) While statement – This loop statement is used to - for loop statement can be used to in following
design general loop codes. different forms
- The Python while loop allows a part of the code to be i) using range() – this function provides list of fixed
executed until the given condition returns false. range values to execute the loop as:
- It is also known as a pre-tested loop. for <var> in range([start],stop,[step]):
- with while statement, expression or condition is ---- loop body---
given which will be tested repeatedly. --
e.g.2
- range() functions uses
for i in range(1,3):
following different
print(i)
parameters:
i) start – it is optional
output -
parameter and it is used
1
as initializing value.
2
- If not given, by default
zero is considered.
ii) stop – it is
terminating value which
- The syntax is given below. decide when loop to be e.g.4- Rev for loop
While <exp>: stopped. Loop executed for i in range(5,0,-1):
---- loop body--- till stop-1 value. print(i)
e.g. program to display Hello message 5 times iii) step – it decides the output -
i=1 incrementing value of 5
while i<=5: loop. It can be either 4
print('Hello') positive or negative 3
i=i+1 value. 2
- Forward order loop – 1
2) for statement – Positive value.
- for statement in python is used to repeat execution of - Reverse Order loop - negative value
given code block. - It is optional parameter, if not given, by default it is
- As oppose to other languages like C, C++, etc it is incremented by 1.
used to iterate over a sequence (list, tuple, string) or e.g.1
other iterable objects. for i in range(3):
- Iterating over a sequence is called traversal. print(i)

output -
0
1
2

e.g.3
for i in range(1,10,2):
print(i)
output -
1
3
5
7
9

16
e.g.5 for with dict if <exp>:
dict={101:'Abc',99.5:'Xyz','aaa':200} break
for k in [Link]():
print('Data Item at key',k,'=',dict[k]) e.g.1- prog to repeatedly get input of int numbers
output- below 100 , store in list, as soon as value entered is
Data Item at key 101 = Abc >=100, loop should stop and display all the values.
Data Item at key 99.5 = Xyz lst=[]
Data Item at key aaa = 200 while True:
n=int(input("Enter a value="))
e.g.6 for with string if(n<100):
s=’Hello’ print('Ok')
for i in s: [Link](n)
print(i) else:
output - break
H print(lst)
e
l e.g- Prog to find given number is Prime or Non-Prime
l
o
* Loop control statements
- To control the current executing loop, python as like
other programming languages C,C++,Java, etc,
supports following loop control keywords of
statements-
1) continue 2) break
1) continue – this statement is used to skip the current
loop iteration and control is jumped to next iteration.
- It is used in those cases when some iterations in loop
to be skipped.
- it can be used with conditional statements as:
for <exp>:
[--- some code----]
if <exp>:
continue
e.g.1
prog to show 1-10 series except 4 & 7 values
for i in range(1,11,1):
if i==4 or i==7:
continue
print(I,end=’ ‘)

e.g.2 prog to show all small and capital alphabets


using single loop
for i in range(65,122,1):
if i>=91 and i<=96:
continue
print(chr(i),end=' ')

2) break – this loop control statement is used to exit


the from loop execution based on given condition.
for <exp>:
[--- some code----]
17
Unit – II String Handling, Classes, Modules and print("Original String=",s)
Package
Output-
2.1 Strings, String operations and Slicing New String= Abc Xyz
Original String= abc xyz
- As like other languages, python also supports string type
data. 3) casefold( ), lower() – it returns the new string with
- String is collection of character enclosed in single, double all characters in small case.
or triple quotes.
s='ABC XYZ'
- python doesn’t supports char type, but the single char #print("New String=",[Link]())
is also stored and processed as string. print("New String=",[Link]())
- string can be created in following different forms:
s=’Abc’ Output-
s=”Abc” New String= abc xyz
- Triple quoted string is to create multiline string value
as 4) upper( ) – it returns the new string with all
s=’’’This is python language which is portable, characters in upper/capital case.
extensible and dynamic language’’’. s='abc xyz'
e.g. print("New String=",[Link]())
s1='A'
s2="Computer Language" Output-
s3='''[Link] is Free – Python can be implemented New String= ABC XYZ
without purchase of any software or there is no -the lower() function returns the new string with all
licensing issues. characters in lower/small case.
2. Portable – python code can be developed on any s='ABC'
hardware or software platform and can be easily print("New String=",[Link]())
transferred to any other hardware or software platform.
3. Extensible''' Output-
print("String1=",s1) New String= ABC XYZ
print("String2=",s2)
print("String3=",s3) 5) swapcase( ) – it returns a new string by swapping
- String in memory is stored as char array with starting case of each alphabet in given string, small will be
index as zero. converted to capital and capital to small.
e.g. s='Abc Xyz'
s=’Hello’ print('Swap Case String=',[Link]())
01234 → index Output-
*String operations Swap Case String= aBC xYZ
- Python allows to perform different operations on
string using following built-in methods:- 6) isupper( ) – it returns True if all the characters in
1) capitalize() – it will convert only the first character of
string are in upper case else False.
string to capital & return as new string (original string not
s='ABC XYZ'
changed)
print("String is in Upper case?=",[Link]())
s='Abc Xyz'
print(“New String=”,[Link]())
Output-
print(“Original String=”.s)
String is in Upper case?= True
Output-
New String= Abc xyz
7) islower( ) – it returns True if all the characters in
Original String= Abc Xyz
string are in lower case else False.
2) title() – it converts first character of each word to
s='ABC XYZ'
capital and returns a new string as -
print("String is in Upper case?=",[Link]())
s='abc xyz'
print("New String=",[Link]())
Output-
18
String is in Upper case?= False print(s,' is Alphabetical=',[Link]())
s='bc$yz'
8) find( ) – searches the given string in parent string, if print(s,' is Alphabetical=',[Link]())
present returns index position else returns -1 s='TTy79'
print(s,' is Alphabetical=',[Link]())
s='ABC XYZ' output
print("Find result=",[Link]('Y')) bcyz is Alphabetical= True
print("Find result=",[Link]('T') 9876 is Alphabetical= False
output bc yz is Alphabetical= False
Find result= 5 bc$yz is Alphabetical= False
Find result= -1 TTy79 is Alphabetical= False

9) index( ) – searches the given string in parent string, 12) isdigit() - it returns True, only if string contains
if present returns index position else generates error - digits or numbers, else returns false.

ValueError: substring not found e.g.

s='bcyz'
s='ABC XYZ' print(s,' having only digits=',[Link]())
print("Find result=",[Link]('Y')) s='9876'
print("Find result=",[Link]('T') print(s,' having only digits=',[Link]())
output s='bc yz'
index result= 5 print(s,' having only digits=',[Link]())
ValueError: substring not found s='bc$yz'
print(s,' having only digits=',[Link]())
10) isalnum – it returns True, only if string contains s='TTy79'
either alphabets, digits or both else returns false. print(s,' having only digits=',[Link]())
s='bcyz' output
print('String ',s,' is Alphnumeric=',[Link]()) bcyz having only digits= False
s='9876' 9876 having only digits= True
print('String ',s,' is Alphnumeric=',[Link]()) bc yz having only digits= False
s='bc yz' bc$yz having only digits= False
print('String ',s,' is Alphnumeric=',[Link]()) TTy79 having only digits= False
s='bc$yz'
print('String ',s,' is Alphnumeric=',[Link]()) ❖ String Slicing
Output- - Python string supports string slicing operation which
String bcyz is Alphnumeric= True is to break down string in small parts to make sub-
String 9876 is Alphnumeric= True string.
String bc yz is Alphnumeric= False - This slicing is done between given start to end
String bc$yz is Alphnumeric= False position.
11) isalpha() - it returns True, only if string contains - For this, python supports slicing operator [] which
alphabets, else returns false. uses following parameters:
[start:stop:step]
e.g. - Start - Select chars from given start index
- stop – select chars upto stop-1 index
s='bcyz' - step – optional, decides increment step, by
print(s,' is Alphabetical=',[Link]()) default 1.
s='9876' which can be used in following forms-
print(s,' is Alphabetical=',[Link]()) i) string[start:] – by this, from given start index till
s='bc yz' last char, substring is formed.

19
e.g.
1. Built-in
s='ABCDE' Functions
print('Substring=',s[2:])
output- 2. User Defined
Functions
Functions
('Substring=', 'CDE')
ii) string[:end] – by this substring is formed by 3. Lambda
function
extracting chars from 0th index till given index-1
position. 1) Built-in functions – these are the functions are
e.g. which are already defined, compiled and stored
s='ABCDE' in respective library.e.g sqrt() – from math
print('Substring=',s[:2]) library.
output- 2) User Defined Functions – These are functions
('Subsring=', 'AB') created for a specific user application.
iii) string[start:end] – by this substring is formed by - UDF can be created using def keyword, a
extracting chars from given start index till given end function can be defined with or without
index-1 position. parameter and also with or without return as:
e.g. def FunName([parm]):
s='ABCDE' --- block---
print('Substring=',s[1:4]) [return]
output- - When return keyword not used, by default it
('Subsring=', 'BCD') returns none object.
iv) string[start:end:step] – by this substring is - Once a function is created, it can be called any
formed by extracting chars from given start index till time as:
given end index-1 position with incrementing chars. funcName([arg])
e.g. e.g.1 function with-out parameter
s='Maharashtra' def fun1():
print('Substring=',s[Link]) print("Function Without argument")
output- - To call above functions, on python interpreter
('Substring=', 'hrs') following statement can be used:
v) string[::step] – by this reverse string generated >>>fun1()
with step value as -1. e.g.2 function with one parameter
e.g. def fun2(a):
s='Maharashtra' print("Value in a=",a)
print('Substring=',s[::-1]) - To call above functions, on python interpreter
output- following statement can be used:
('Substring=', 'hrs') >>>fun1(10)
e.g.3 function with multiple parameters
2.2 Defining and calling functions, passing def fun1(a,b,c):
print("Value in a=",a)
arguments to functions print("Value in b=",b)
- one of the fundamental criteria of any programming print("Value in c=",c)
language is to support the concept of function. To call above functions, on python interpreter
- function is self-contained block of instructions to following statement can be used:
complete a special task. >>> fun1(99,'Abc',96.7)
- Functions in python are broadly classified as: ('Value in a=', 99)
('Value in b=', 'Abc')
('Value in c=', 96.7)
e.g.4 function with single return
def fun1(a):
return a*a
To call above functions, on python interpreter
following statement can be used:
20
>>> n=fun1(10) ('value=', 33)
>>> print (‘Square=’,n) ('value=', 44)

e.g.5 function with multiple return >>> fun1(23,'abc',8.9,True)


def fun1(a): ('value=', 23)
return (a,a*a) ('value=', 'abc')
To call above functions, on python interpreter ('value=', 8.9)
following statement can be used: ('value=', True)
>>> num,sq=fun1(7) 3) Lambda function – generally a function is defined
>>> print (‘Number=’,num,’Square=’,sq) by giving proper name, but python also allows to
Output create a function without name.
Number=7 Square=49 - Such function without name or anonymous function
- Alternatively above function can be called is called lambda function.
from interpreter using single receiving variable - A function with-name defined with “def” keyword,
as: but a lambda function is defined with “lambda”
n=fun1(9) keyword.
print(n) - This function to define uses 3 parts
output- i) lambda keyword
(9, 81) ii) single or multiple arguments
e.g.6 function with default argument iii) expression – single line executable
- In this type, function is defined with parameter and a statement.
default value is assigned. - a lambda function can return only 1 value, but it does
- Such function can be called by passing argument or not uses “return” keyword.
without argument. syntax
- If argument is passed, it is stored in parameter and lambda arg1,arg2… : expression
processed. e.g.1
- If argument not passed, the default value is used for >>> x=lambda a:a+5
processing. >>> print(“Expression value=”,a(5))
e.g. Output
def fun1(a,b=2): Expression value= 10
print("Addition=",a+b) e.g.2
>>> x=lambda a,b:a*b
e.g.7 function with variable number arguments:- >>> print("Multiplication=",x(3,5))
- In some cases, function to be defined to receive Output
arguments, but number of arguments to be passed are Multiplication= 15
not fixed.
- In such case, a function is defined with single 2.3 Defining Classes
argument but preceded by * (asterisk) symbol as:
def funName(*ArgName): - As python is OOP language hence it supports all the
---- block--- features of OOP concepts.
- such argument get created as collection in memory
and stores multiple values which can be accessed using - Class is one such most fundamental concept of OOP
any loop statement. supported by every OOP lang.
e.g.
def fun1(*args): - Class is single security unit which allows to combine
for i in args: data as well as function member.
print("value=",i)
- In python program, class can be created using “class”
- Above function can be called by passing multiple keyword as:
arguments of same or different types:
>>> fun1(99,33,44) class <ClassName>:
('value=', 99) [data member]
21
[function member] print(n)
- A class can enclose data as well as function - To call above function,
members, but both are always not compulsory. >>> ob=A()
- while giving the class body, following rules must to >>>[Link](89)
be followed: Output
i) when a function member to be defined, it Value of n=89
must have at least one parameter i.e. self. - Python class supports following access specifiers:
ii) when a function member needs to access, i) private – when the any member of is
class data member, this self keyword must be used as: declared as private, it is accessible only with-in class.
[Link] - To make any member private, it must starts
- Once class definition is over, it’s member can be with double underscore as:
accessed using object. __rollno=0
- Object is one runtime entity or instance which ii) protected – when the any member of class
represents the class. is declared as protected, it is accessible in same class
- Object is memory block, which reserves space of & only from it’s derived classes.
data and function member. - to make any member protected, it must starts
- Object can be declared as: with single underscore as:
ObjName=ClassName() _rollno=0
e.g. ob1=ClassA() iii) public – by default member of class in
- This object with Member accessing operator (.) is python is public. If any member is public can be
used to access member of class. accessible within the class and also outside the class.
Eg.1 - to make any member public, no underscore is
class A: used as:
n=0 #initalizing class member Rollno=0
def display(self): ❖ Constructor & Destructor
self.n=100 - Every class created in OOP language supports two
print(“Value of n=”,self.n) special member functions i.e. Constructor and
- To call above function, Destructor.
>>> ob=A() Constructor – The special member function of class
>>>[Link]() that performs the task of allocation and initialization
Output is called constructor.
Value of n=100 - It shows following special features in python
e.g. 2 function with argument programming:
class A: i) it is implicitly created as well as called.
def display(self,n):
22
ii) constructor in python class can be created >>> del ob
using def keyword with name __init__(self) as: Destructor Called, Object Deleted
def __init__(self): 2.4 Python and OOP –
---- code block ---- - As python is OOP language, hence it supports all the
iii) constructor get called whenever object of class is features of OOP and gives all it, benefits.
created. - To most common features of OOP are:
Destructor – The special member function of class Inheritance,
that performs the task of de-initialization and de- polymorphism
allocation is called destructor.
- It performs the task opposite and in reverse as of ❖ Inheritance
constructo. - Inheritance is one of the feature of OOP language.
- It shows following special features in python - This OOP technique by which from an existing class
programming: a new class is created.
i) it is implicitly created as well as called. - The existing class is called Base/Parent/Super class
ii) Destructor in python class can be created and the newly created class called as
using def keyword with name __del__(self) as: Derived/Child/Sub class.
def __del__(self): -When inheritance is applied, it shows following
---- code block ---- effects:
iii) Destructor get called whenever object of class is i) Copy of data member is transferred from
deleted using ‘del’ keyword as: base to derived class &
del <objectName> ii) permission given to child class to call base
e.g. of constructor & destructor class function without object.
class A: - Inheritance gives biggest advantage of reusability.
n=0; - In Python, following types of inheritances are
def __init__(self): supported:
self.n=10 1) Single 2) Multi-level 3) Multiple
def display(self): 4) Hierarchical 5) Hybrid
print("Value to n initialized by 1) Single – In this inheritance, only one base class and
constructor=",self.n) only one derived class is involved:
def __del__(self):
Base
print("Destructor Called, Object Deleted")
class
- To execute above
>>> ob=A() Derived
>>> [Link]() class

('Value to n initialized by constructor=', 10) Syntax : Class DerivedClassName(BaseClsName):


23
----- class definition ----- def display(self):
e.g. self.n=input("Enter any Value=")
class A: print("in Base Class A, n=",self.n)
n=0; class B(A):
def display(self): def show(self):
self.n=input("Enter any Value=") print("in Derived Class B, n=",self.n)
print("in Base Class n=",self.n) class C(B):
class B(A): def output(self):
def show(self): [Link]()
[Link]() [Link]()
print("in Derived Class n=",self.n) print("in Derived Class C, n=",self.n)
==== To Execute==== ==== To Execute====
>>> ob=B() >>> ob=C()
>>> [Link]() >>> [Link]()
Enter any Value=123 Enter any Value='Abc'
('in Base Class n=', 123) ('in Base Class A, n=', 'Abc')
('in Derived Class n=', 123) ('in Derived Class B, n=', 'Abc')
2) Multi-level – In this inheritance, from an existing ('in Derived Class C, n=', 'Abc')
child/derived class a new class is created: 3) Multiple/Multipath – In this inheritance, two or
more base classes are use to create a child class.
A- Base
class - The child class inherits properties from each base
class and also can call member function of each base
B-Derived class.
class
A- Base B- Base C- Base
class class class
C-Derived
class
D- Derived class

- Thus in above eg. From A Base class, B derived class


is created, and from this B Derived class, another class A:
derived class is created i.e. C n=0
Syntax : Class DerivedClassName(BaseClsName): def getIn1(self):
----- class definition ----- self.n=int(input("Enter Ist Value="))
e.g. class B:
class A: m=0
n=0; def getIn2(self):
24
self.m=int(input("Enter IInd Value=")) class D(A):
class C(A,B): def f3(self):
def display(self): print("Sq Root=",[Link](self.n))
self.getIn1() ob1=B()
self.getIn2() ob1.f1()
print("Addition=",self.n+self.m) ob2=C()
========= to execute =========== ob2.f2()
>>> ob=C() ob3=D()
>>> [Link]() ob3.f3()
Enter Ist Value=12 del ob1
Enter IInd Value=23 del ob2
('Addition=', 35) del ob3
4) Hierarchical – In this inheritance, from single base ======output===========
class, multiple derived classes are created. Enter a Value=12
- It is used to provide common features to all derived ('Square=', 144)
classes. Enter a Value=5
- Such common features are available in base class and ('Cube=', 125)
inherited by all derived class. Enter a Value=7
A- Base ('Sq Root=', 2.6457513110645907)
class 5) Hybrid – In this inheritance, other inheritance types
are combinedly used.
B-Derived B- Derived C- Derived
- It is used to get combined benefits of other
class class class
inheritance types:
e.g.
import math
class A:
n=0
def __init__(self):
self.n=int(input("Enter a Value="))
class B(A):
def f1(self):
print("Square=",self.n*self.n)
class C(A):
e.g.
def f2(self):
import math
print("Cube=",self.n*self.n*self.n)
25
class A: e.g.1 print() function can be used to show value of int,
n=0 float, char, string, Boolean, list, tupple, set, dictionary ,
class B(A): etc.
def __init__(self): function can be to calculate length of different types of
self.n=int(input("Enter a Value=")) values like, string, list, set, dictionary.
class C(B): print("String Len=",len('abcd'))
def f1(self): lst=[101,'abc',8.9]
print("Cube=",self.n*self.n*self.n) st={100,200,300,'Abc','Xyz'}
class D(B): dct={1:100,2:200,3:300}
def f2(self): print("List Len=",len(lst))
print("Sq Root=",[Link](self.n)) print("Set Len=",len(st))
ob1=C() print("Dict Len=",len(dct))
ob1.f1()
ob2=D() 2.5 Modules – Python interpreter allows to creates
ob2.f2() functions, declarations or other executable statements
del ob1 on interpreter prompt(>>>).
del ob2 - It is easy to create, but these are available for
==========output======== temporary purpose, as soon as the interpreter is closed,
Enter a Value=7 it get removed from memory.
('Cube=', 343) - In many cases, a lengthy function is necessary to be
Enter a Value=9 repeatedly executed.
('Sq Root=', 3.0) - If such function is not stored, then repeatedly it needs
❖ Polymorphism to be created and then called, which very
- Polymorphism word is made up of two words i.e. Time consuming
Poly=many, morhps=types or forms. Error prone – chances of generating errors
- This OOP technique is to make a programming entity - To solve this, python supports the concept of module.
available in multiple forms. - Module is a file which can contain, classes,
- The programming entity which is available in declarations, executable statements or functions
multiple form is said to be polymorphic. definitions.
- It can be implemented in python language in - Once it is saved, it can be called any number of
following ways- times.
1) Using built-in functions- many library functions of - Python supports many built-in modules and also
Python language shows polymorphism i.e. same allows to create user defined module.
function can be used in different forms. - Commonly used built-in modules in python are
Datetime
26
Math from datetime import datetime
❖ datetime - Python Datetime module supplies now = [Link]()
classes to work with date and time.
- These classes provide a number of functions to print(now)
deal with dates, times and time intervals. ==========output==========
- Date and datetime are an object in Python, so 2022-05-14 [Link].453000
when you manipulate them, you are actually - to print formatted time string
manipulating objects and not string or from datetime import datetime
timestamps. now = [Link]()
- Commonly used classes in the datetime module current_time = [Link]("%H-%M-%S")
are: print("Current Time =", current_time)
I. date Class – object is this class represents =======output======
year, month and day. ('Current Time =', '14-08-33')
- The current date and all date parts can be III. timedelta Class – this class represents date and
extracted. time manipulations by calculating difference
- Current date can be displayed as: between two date and time.
>>> import datetime - by using “+” symbol date or time values can be
>>> print([Link]()) added and “-“ symbol used to subtract values to
2022-05-14 return new date or time value.
- Date parts can be extracted by creating date e.g from datetime import datetime,timedelta
object as: time_obj = [Link]()
<obName>=[Link]() d1=time_obj.strftime("%d/%m/%Y")
E.g.
from datetime import date print("Current Date=",d1)
ob=[Link]() d2=time_obj+timedelta(days=2)
print("Year=",[Link]) d2=[Link]("%d/%m/%Y")
print("Month=",[Link]) print("New Date=",d2)
print("Day=",[Link]) t1 = time_obj.strftime("%H-%M-%S")
===output======== print("Current Time =", t1)
('Year=', 2022) t2=time_obj + timedelta(hours=3)
('Month=', 5) t2=[Link]("%H-%M-%S")
('Day=', 14) print("new Time=",t2)
II. time Class – it represents time values like ==========output=======
hours, minutes, seconds and miliseconds ('Current Date=', '14/05/2022')
e.g. ('New Date=', '16/05/2022')
27
('Current Time =', '14-34-41') vi)[Link]()-returns sum of all items from lists,
('new Time=', '17-34-41') tuple, set etc only if all items are numeric else
shows TypeError
❖ math – python provides math as built-in lst=[2,5,5,10]
module to complete different mathematical [Link](lst) → 17.5
task. vii) [Link]() – returns down integer of floating
- it consist of many built-in methods and constants square root value as:
to complete mathematical operations. print('Only Sq root=',[Link](8))- 2.8284271247
- to use this module & it’s methods, it must be print('int sq root=',[Link](8)) – 2
imported using import keyword as: viii) [Link](x,y) – return power of x raised to y
import math as:
- Any method of math module can be called as: [Link](3,3) → 27.0
[Link]([arg]) ix) [Link]() – returns multiplication value of
- Following are the few built-in functions of math all items in tuple, list,set etc if all items are
module: numeric.
i) [Link]() – it takes one float argument and lst=[2,3,5.5]
returns it’s next nearest value as: print('Prod of All Items=',[Link](lst))→33.0
import math x) [Link]()- returns only the int part by
print("Ceil value=",[Link](7.6))→8.0 truncating fractional part of given float value
print("Ceil value=",[Link](7.1))→8.0 [Link](9.9)→9
ii) [Link]() – it returns the absolute value in the ❖ User defined module
form of float number: - Python also allows to create and use user-defined
print("Abs value=",[Link](3))→3.0 module in following steps;
print("Abs value=",[Link](-3))→3.0 → create required number functions and save
iii) [Link]()- it returns factorial of given in a file with .py extension.
number: → the file name is considered as module name.
print([Link](5)) →120 → import the above file/module
iv) [Link]() -it returns nears down floating → call the function with module name
value by eliminating fractional part e.g.
[Link](8.99) →8.0 def display(a,b):
v) [Link](x,y) – it returns the remainder by print("Addition=",a+b)
dividing x by y print("Subtn=",a-b)
[Link](5,3) → 2.0 print("Div=",a/b)
print("Mult=",a*b)
→ save above file as [Link]
28
→ import this module as i) create a folder in current python installation
import arith folder
→ call module function as e.g. MyPack1
[Link](9,8) ii) in this package, create & modules
2.6 Packages – Python allows to organize all the containing class, functions, etc
related classes, function etc in same module like e.g. mod1
Date class, time class, datetime class is in datetime def display():
package, all mathematical functions are in math print(“This is user Def
module. Package”)
- similarly, it is also possible that, their might be group - The above module to saved and compiled
of related modules to be organized properly. iii) create, save and compile empty __init__.py
- Group of related modules organized in same file
location/folder is called package. iv) to call/access above package import the
- Suppose you have developed a very large application package in one of the following forms
that includes many modules. a) using import – by this the entire
- As the number of modules grows, it becomes library can be loaded and become accessible
difficult to keep track of them all if they are dumped e.g.
into one location. import MyPack
- This is particularly so if they have similar names or import datetime
functionality. You might wish for a means of grouping b) using from…import statement – by
and organizing them. this only the requires modules can be imported
- Packages allow for a hierarchical structuring of the as
module namespace using dot notation. from MyPack import Billing
- In the same way that modules help avoid collisions e.g
between global variable names, packages help avoid >>> from MyPack1 import mod1
collisions between module names. >>> [Link]()
- Python supports both types of packages –
i) Built-in packages – these are the packages
which come by default with every python installation.
- all these are stored in lib folder after installation e.g.
collections, html, http, sqlite3, etc.
ii) user defined packages – the package created
for a specific user application.
- To create and use user-defined package,
following steps to considered
29
Unit – III - Exception Handling and Collections
3.1 Exception in python 3.3 Exception Handling
3.2 Exception roles 3.4 Collections in Python – List, Tuples, Dictionaries,
- In Python programming, exception are used for Sets
following different purposes, hence exception plays [this part is already discussed in Chap-1 under data
important role in following cases: type heading]
1. Error Handling – Python interpreter raises
exception whenever their occurs runtime error.
- In such case following are the possibilities:-
i) Ignore the error, if error ignored, pythons
default exception handler will be called, it will show
the corresponding message and terminates program
execution.
ii) handle the error using try and catch
statements, by this successfully error will be handled
and program will complete it’s normal execution.
2. Event Notification – Many times entry of invalid
data or invalid operation needs to explicitly checked,
which is very time consuming. Hence exception can be
used to notify such invalid condition.
3. Termination actions – Some times, a software uses
such special operation code which must be executed in
any case before closing the program called as House
Keeping operations like Closing DB Connection ,
Closing DB, Closing File, etc.
- the try/finally block when used, ensures such action
is taken before termination of program in any case,
whether exception occurs or not.
4. Unusual control flows – Other languages like C or
C++ supports jumping statement i.e. goto, by which
program control can be transferred from one part to
other.
But as like java, python also don’t support goto,
instead exception with raise keyword can be used for
same purpose.
30
Unit – IV - GUI Programming and Database Note that Tkinter is a set of wrappers that implement
Connectivity Using Python the Tk widgets as Python classes.
4.1 Graphical User Interfaces 2) wxPython:
- The working environment provided by any software This is basically an open-source, cross-platform GUI
code or OS is called interface by which user interacts toolkit that is written in C++.
with hardware & other components. Also an alternative to Tkinter.
- Based on their working environment, interfaces are 3) JPython:
classified as: JPython is a Python platform for Java that is providing
1) CLI – Command Line Interface - In this, to Python scripts seamless access to Java class
complete each task, correct command in proper form Libraries for the local machine.
and syntax t be entered.
-Adv – Such interface is easy to create. 4.2 Using the tkinter Module
Minimum Hardware requirements. Tkinter is Python's default GUI module and also the
Dis-Adv – Difficult to use, understand, error most common way that is used for GUI
prone and time consuming. programming in Python.
2) GUI – Graphical User Interface – In this, - Tkinter stands for TookKit interface. Toolkit as like
to complete each task, corresponding commands or in java is built-in library.
actions are presented on screen. -This toolkit in Python provides modules to design
- Such interface also called, point-n-click or Point-n- GUI using python.
select interface. - this module in older version of python interpreter i.e.
- It uses different graphical components like, menus, before 3.0 is available as TKinter and now it is
controls (Label, Button, Textfield, radio button, etc), renamed to tkinter.
image, icons, etc. - The GUI once created provides a parent or container
Adv – More easy to understand and use, less chances window in which other controls can be added.
of errors and time saving. - In Python, the GUI controls are called widgets &
Dis-Adv – More complex to design for programmer. different such widgets can be used are :
Requires extra hardware. Text, Button, info Dialog Boxes, Radiobutton,
- Python provides different library modules to design Checkbutton , etc
GUI such as:
1) Tkinter is a standard GUI (graphical user interface) - Steps to create GUI using tkinter module
package. i) import tkinter module as
Tkinter is Python's default GUI module and also the from tkinter import tkinter
most common way that is used for GUI or
programming in Python. from tkinter import *

31
ii) create object of by calling it’s constructor Tk() to [Link]("100x100")
create window as: #[Link](bg=#120,67,89)
objName=Tk() #gui['bg']='red'
e.g. gui['bg']='#628784'
import tkinter
top=[Link]()
- Above statement will create and show a window with
Default size
4.3 Creating Label – Label is one GUI widget used as
Default backcolor
text control.
Default title as tk
- It is used to show static as well as dynamic text as
well as image on gui.
- Steps to create and use Label widget:
i) create and initialize label object as:
<objName>=Label() – it will create an empty label
with default properties.
- To this GUI, some basic properties can be applied as: Or
i) Setting title – <obj>.title(“any title”) <objName>=Label(ParenWindowObj,text=” any
ii) setting window size - <ob>.geometry(“int width x text”,bg=’ColorName’,fg=’ColorName’, font=”Font
int height”) attributes”)
iii) setting background color – background color can ii) To show/ load label in window, use one of the
be applied in one of the following ways: following method
a) using configure function with bg attribute- a) pack() – this method adds label object at
<ob>.configure(bg=’ColorNam’) default location on GUI.
[Link](bg=’Red’) b) place(Co(x)=int, row(y)=int)
b) directly using bg property - e.g.
<ob>[‘bg’]=’ColorName’ from tkinter import *
ob[‘bg’]=’Red’ gui=Tk()
or [Link]("Label Demo")
<ob>[‘bg’]=’#ColorCode’ [Link]("100x200")
ob[‘bg’]=’#127744’ gui['bg']='#209970'
e.g. lb1=Label(gui,text="Demo1",bg='red',fg='yellow',font
from tkinter import * ='Script 40 bold underline')
gui=Tk() #[Link](x=00,y=50)
[Link]("Demo Window") [Link]()

32
- To add image in Python GUI, following
supporting components are needed:
o Canvas – class
o PhotoImage – function
- Label widget also allows to handle key as well as - The steps to add image in GUI using Label are:
mouse events. i) Create & initialize Canvas object.
- To handle label event use following steps: ii) Add canvas object in GUI.
i) create a U.D. function with at least one arg as: iii) Create and initialize image object using
def MouseClick(arg): PhotoImage().
----- code---- iv) Call create_image() of Canvas class to
ii) link the event to label object using bind() as: display the image.
<labObj>.bind(“<Event>”, FnName) e.g.
- python provides many built-in event names like for following e.g. [Link] file is stored in current
Button folder of python program.
Key , etc
e.g. from tkinter import *
from tkinter import * gui=Tk()
def mouseClick(arg): [Link]("Label Demo")
print('Mouse Clicked') [Link]("200x200")
gui=Tk() canvas=Canvas(gui,width=300,height=300)
[Link]("Label Demo") [Link]()
[Link]("200x200") img=PhotoImage(file="[Link]")
gui['bg']='#209970' canvas.create_image(20,20,image=img)
lb1=Label(gui,text="Demo1",bg='red',fg='yellow',font
='Script 40 bold underline') Text – This python gui widget from tkinter library is
#[Link](x=00,y=50) used to create dynamic text entry control so that user
[Link]() can provide text input.
[Link]("<Button>",mouseClick) - To create and use Text widget following steps are
required:
i) Create and initialize Text object as:
<objName>=Text(ParentWindow,[height=int,width=in
t,bg=’colorname’,fg=’colorname’,font=’properties’])
- By default, text widget works in multi-line mode, to
- Label widget can also be used to show image
make it single line, height property must be set to 1.
in gui.
ii) add object in GUI
33
- - This widget of python tkinter library is used to create
- Text class for different manipulations, supports command button or push button control to be
following functions:- displayed on GUI.
i) insert(Position,”text”) – by this method any text can - This button helps to take necessary action to user as
be inserted in text widget using INSERT as it’s per the given execution flow.
position constant. - Button can be created and used in following steps:
[Link](INSERT,”Abc Xyz”) i) create button object as:
ii) get(start,end) –by this method, current value from BtnObj=Button(ParentWindow,text=’text’,[fg=’color
text control can be read as: name’,bg=’colorname’,activebackgroun=’color
x=[Link](1.0,”end”) – by this from first to last char all name’,command=functionName])
contents are read in x variable. - There are many optional parameter used like:
iii) delete(start,end) – by this method, current value fg- to specify foreground color
of text control can be deleted as: bg- to specify background color
[Link](1.0,”end”) activebackground – helps to set the color which is
e.g. displayed whenever button is pressed.
from tkinter import * Command – is used to link the button event with a
def fn(): function which get called whenever button is clicked.
x=[Link](1.0,"end") ii) Add the button object in GUI using pack() or
[Link](1.0,"end") place() method.
[Link](INSERT,x) e.g.
gui=Tk() from tkinter import *
[Link]("300x300") from datetime import *
t1=Text(gui,height=1) def fn():
t2=Text(gui,height=1) dt=[Link]()
btn=Button(gui,text="Copy Text",command=fn) [Link](INSERT,str(dt))
[Link]() gui=Tk()
[Link]() [Link]("300x300")
[Link]() lb=Label(gui,text="Current Date & Time=")
t1=Text(gui,height=1)
btn=Button(gui,text="Show Date and
Time",command=fn)
[Link]()
[Link]()
[Link]()

Button, -
34
[Link]()

info Dialog Boxes – one of the important feature of


and standard GUI is, it must communicate/interact
with it’s user. ii) [Link](title,”messageText”) –
- For this purpose, GUI supports dialog box controls. this dialog box is used to show warning msg to user, it
- dialog box is a small fixed sized window which is comes with default “OK” button and yellow colored
used to get input from user, give output to user or both. warning icon.
- Dialog boxes are child window which are always - When the Ok button is pressed, it returns “ok”.
displayed in parent window. e.g.
- tkinter library of Python supports many built dialog from tkinter import *
boxes which can be activated by calling their from tkinter import messagebox
respective functions. def fn():
- The older version of python interpreter support x=[Link]("Demo","This is Info
tkMessageBox module and the newer version supports Dialog Box")
messagebox module. print(x)
- These modules supports following built-in functions gui=Tk()
to show dialog boxes. [Link]("300x300")
i) [Link](title,”messageText”) – this btn=Button(gui,text="Click Here",command=fn)
dialog box is used to show information msg to user, it [Link]()
comes with default “OK” button and information icon.
- When the Ok button is pressed, it returns “ok”.
e.g.
from tkinter import *
from tkinter import messagebox
def fn():
x=[Link]("Demo","This is Info
Dialog Box")
print(x)
iii) [Link](title,”messageText”) –
gui=Tk()
this dialog box is used to show error msg to user, it
[Link]("300x300")
btn=Button(gui,text="Click Here",command=fn)
35
comes with default “OK” button and red colored error x=[Link]("Demo","This is
icon. Question Dialog Box")
- when the Ok button is clicked, it returns “ok” as print(x)
string. gui=Tk()
e.g. [Link]("300x200")
from tkinter import * btn=Button(gui,text="Click Here",command=fn)
from tkinter import messagebox [Link]()
def fn():
x=[Link]("Demo","This is Info
Dialog Box")
print(x)
gui=Tk()
[Link]("300x300")
btn=Button(gui,text="Click Here",command=fn)
[Link]()

v) [Link](title,”messageText”) –
this dialog box is used to show Ok Cancel Dialog box
to user, it comes with default “Ok” and “Cancel”
button and red question mark icon.
- when the Ok button is clicked, it returns “True” as,
when the Cancel button is clicked, it returns “False”.
E,g,
from tkinter import *
iv) [Link](title,”messageText”) –
from tkinter import messagebox
this dialog box is used to show question msg to user, it
def fn():
comes with default “Yes” and “No” button and red
x=[Link]("Demo","This is Ok
question mark icon.
Cancel Dialog Box")
- when the Yes button is clicked, it returns “yes” as
print(x)
string, when the No button is clicked, it returns “no” as
gui=Tk()
string,
[Link]("300x200")
e.g.
btn=Button(gui,text="Click Here",command=fn)
from tkinter import *
[Link]()
from tkinter import messagebox
def fn():

36
to user, it comes with default “Retry” and “Cancel”
button and red question mark icon.
- when the Retry button is clicked, it returns “True” as,
when the Cancel button is clicked, it returns “False”.
e.g.
from tkinter import *
from tkinter import messagebox
vi) [Link](title,”messageText”) – this def fn():
dialog box is used to show Yes No dialog box to user, x=[Link]("Demo","This is
it comes with default “Ok” and “Cancel” button and Retry Cancel Dialog Box")
red question mark icon. print(x)
- when the Yes button is clicked, it returns “True” as, gui=Tk()
when the No button is clicked, it returns “False”. [Link]("300x200")
from tkinter import * btn=Button(gui,text="Click Here",command=fn)
from tkinter import messagebox [Link]()
def fn():
x=[Link]("Demo","This is Yes No
Dialog Box")
print(x)
gui=Tk()
[Link]("300x200")
btn=Button(gui,text="Click Here",command=fn)
Radiobutton,
[Link]()
- One of the important use of any GUI is as data
collection form.
- For data collection, two possible techniques are used:
i) direct entry – When uncertain data to be
collected from user like Student Name, employee
name, etc, this technique is used.
It is easy to use but time consuming and also
error prone.
ii) Selection entry – in this user is provided
with selectable option to collect certain or known data
vii)
like Blood group. Gender, HSC boards of Maharashtra
[Link](title,”messageText”) –
State, etc.
this dialog box is used to show retry cancel dialog box
37
- By this data collection is easy, time saving and rb2=Radiobutton(gui,text="Option 2",variable=v1,
also error-free. value=2,command=fn)
- For this, GUI supports selectable controls. rb3=Radiobutton(gui,text="Option 3",variable=v1,
- This widget of tkinter library helps to provide value=3,command=fn)
set of selectable options to user. [Link]()
- It allows single selection from one group. [Link]()
- It appears as circle shaped widget on screen [Link]()
and shows dot as selection mode. [Link]()
- It works only in toggle mode i.e. either
ON/True or OFF/False mode.
- Steps to create and use radio button widget in
GUI
➔ Create one int variable using IntVar() function.
➔ Create and initialize Radiobutton object with
above variable associated as:
Obj=Radiobutton(ParentWindow, text=”any text”,
Checkbutton
Variable=VarName, value=value,
- One of the important use of any GUI is as data
command=FunctionName)
collection form.
➔ Use value property and assign value for
- For data collection, two possible techniques are used:
execution.
i) direct entry – When uncertain data to be
➔ To handle the radio button event, define
collected from user like Student Name, employee
function and bind using command attribute.
name, etc, this technique is used.
➔ Add radiobutton object in gui using pack() or
It is easy to use but time consuming and also
place() method.
error prone.
e.g.
ii) Selection entry – in this user is provided
from tkinter import *
with selectable option to collect certain or known data
def fn():
like Blood group. Gender, HSC boards of Maharashtra
[Link](text="Option Selected="+str([Link]()))
State, etc.
gui=Tk()
- By this data collection is easy, time saving and
[Link]("300x200")
also error-free.
lb=Label(gui)
- For this, GUI supports selectable controls.
v1=IntVar()
- This widget of tkinter library helps to provide
rb1=Radiobutton(gui,text="Option 1",variable=v1,
set of selectable options to user.
value=1,command=fn)
- It allows multiple selection from one group.

38
- It appears as square shaped widget on screen
and shows ✓ mark as selection mode.
- It works only in toggle mode i.e. either
ON/True or OFF/False mode.
- Steps to create and use radio button widget in
GUI
➔ Create one int variable using IntVar() function. 4.4 Getting Input
➔ Create and initialize Checkbutton object with - One of the important feature of and standard GUI is,
above variable associated as: it must communicate/interact with it’s user.
Obj=Checkbutton(ParentWindow, text=”any text”, - For this purpose, GUI supports dialog box controls.
Variable=VarName, command=FunctionName) - dialog box is a small fixed sized window which is
➔ Use value property and assign value for used to get input from user, give output to user or both.
execution. - tkinter library of Python supports Entry widget
➔ To handle the checkbutton event, define which is used to create input control in gui.
function and bind using command attribute. - entry widget show one text entry control on gui in
Add checkbutton object in gui using pack() or place() which use can enter the required input.
method. - to read the value of entry object, it support get( )
e.g. method.
from tkinter import * - input widget can be created in following steps:
def fn(): → create Canvas Object
[Link](text="Status: → add canvas object in GUI.
CB1="+str([Link]())+"\tCB2="+str([Link]())) → Create Label object and add in Canvas using
gui=Tk() create_window()
[Link]("300x200") → create Entry object and add in Canvas using
lb=Label(gui,font="bold") create_window()
v1=IntVar() → create button object and add in canvas using
v2=IntVar() create_window()
cb1=Checkbutton(gui,text="Option → define a function to handle button event and
1",variable=v1,command=fn) link with button using command property.
cb2=Checkbutton(gui,text="Option e.g.
2",variable=v2,command=fn) from tkinter import *
[Link]() def fn():
[Link]() x=[Link]()
[Link]() [Link](text="Hello..."+str(x))
gui=Tk()
39
[Link]("300x200") → Goto script location of python installation folder,
goto scripts folder and run pip (Package Installer for
canObj=Canvas(gui) Python) command as:
lb1=Label(gui,text="Enter Your Name") C:\Users\admin\AppData\Local\Programs\Python\Python
37-32\Scripts>pip install mysql-connector-python
canObj.create_window(80,20,window=lb1)
entryObj=Entry(gui) - if the system is having active internet connection, the
[Link] will be installed & it will show the
canObj.create_window(70,40,window=entryObj) status as: Successfully installed.
btn=Button(gui,text="Submit",command=fn)
4.6 Connecting with a database
canObj.create_window(90,70,window=btn) 4.7 Forming a query in MySQL
4.8 Passing a query to MySQL
[ for above 3 headings use following common
lb2=Label(gui,font="bold")
explanation]
canObj.create_window(80,100,window=lb2)
- - Python programming language supports many
[Link]() features, one such important feature is, Database
programming.
- Python code can be connected with any backend
database and can perform read as well as write
operations.
- MySQL is a relational database management system
(RDBMS) developed by Oracle based on structured
query language (SQL).
- To implement DB programming in Python with
MYSQl following are necessary components:
4.5 Importing MySQL for Python
- Python programming language supports many features, i) MySQL server
one such important feature is, Database programming. ii) mysql connector for Python
- Python code can be connected with any backend - If above two components are ready, python code can be
database and can perform read as well as write
operations. connected with MySQL Database in following steps
- MySQL is a relational database management system → import mysql connector as:
(RDBMS) developed by Oracle based on structured
query language (SQL). import [Link]
- To implement DB programming in Python with → create and initialize connection object using connect()
MYSQl following are necessary components:
method of [Link] as:
i) MySQL server – ensure MySQL server 5.5 or onwards ConObj=[Link](host,user,password,da
version is installed on system.
ii) mysql connector for Python – Python code to be tabase)
connected with MySQL needs a special component or - this connect method uses 4 parameters as:
driver i.e. mysql connecter.
- mostly, by default, to check whether it is installed or i) host – value of this parameter use to specify physical
not, use following command on python interpreter location of MySql server or the computer on which it is
>>> import [Link]
- if it is not installed, above command shows following installed.
error - if it is on same machine, “localhost” value can be used
ModuleNotFoundError: No module named 'mysql'
- to solve this use following steps: also IP address can be specified for other machine in
→ Goto command prompt network like host=”[Link]”

40
ii) user – Value of this parameter use to specify user id e.g.1 python code to read a record
required to connect with mysql server, by default it is import [Link]
“root” con=[Link](host=”localhost”,user=”ro
iii) password - Value of this parameter use to specify ot”,password=”abc#123”,database=”MyDB1”)
password which is set during MySQL server installation. cur=[Link]() # creating cursor object
iv) database - Value of this parameter use to specify [Link](“select * from StudInfo”) # executing sql stmt
which particular database to be connected as MySQL rst=[Link]() # extracting all records in record set
server might having many databases. print(rst) # it will print first record
Forming Query & Passing query
- Once the connection is established with MySQL output
database, Python code can perform read, write or both [(1001,’David’,’BCA’)]
operations.
- to complete any such operation, sql query to be e.g.2 python code to read all records
composed & executed. import [Link]
- for this, MySQL, as like Oracle uses concept of Cursor con=[Link](host=”localhost”,user=”ro
which is temporary memory location used internally for ot”,password=”abc#123”,database=”MyDB1”)
SQL operations by server. cur=[Link]() # creating cursor object
- Hence, in python code also Cursor object to be created [Link](“select * from StudInfo”) # executing sql stmt
using connection object as: rst=[Link]() # extracting all records in record set
CurObj=[Link]() print(“Stud ID\t\tStud Name\t\tCourse”)
- with this cursor object, execute() method can be called print(“================================”)
to which SQL statement must be passed as parameter for x in rst:
like: print(x[0]+”\t\t”+x[1]+”\t\t”+x[2])
[Link](“sql stmt”)
- Cursor also supports another useful method i.e. output
fetchall() by which record set (all records) can be Stud ID Stud Name Course
extracted in python variable as: ===================================
1001 ’David’, ’BCA’
RecordSetObj=[Link]()
1002 ’Peter’, ’BCA’
e.g. 1003 ’John’, ’BBA’
-Consider on MySQL server MyDB1 database is
available with following table and records
StudInfo
StudID StudName Course
1001 David BCA
1002 Peter BCA
1003 John BBA

41

Common questions

Powered by AI

The 'continue' statement in a Python loop is used to skip the current iteration and move control to the next iteration of the loop. Unlike 'break', which exits the loop entirely, 'continue' only skips the remaining code in the present iteration and re-evaluates the loop condition for the next iteration. An effective scenario for using 'continue' is when certain conditions should result in no action. For instance, in a loop printing numbers from 1 to 10, you may want to skip printing the numbers 4 and 7. This can be achieved by checking if the current number is either 4 or 7, and if so, using 'continue' to skip printing .

The messagebox module in Python's Tkinter library provides a set of standard dialog boxes to enhance interactivity in a GUI application. It includes various functions such as 'showinfo', 'showwarning', 'showerror', 'askquestion', 'askokcancel', 'askyesno', and 'askretrycancel', each displaying a dialog box with the appropriate buttons and icons. These dialog boxes can be used for notifying users of information, warnings, errors, or for obtaining user input in a straightforward manner. For example, 'askyesno' returns a boolean value based on user selection, allowing the application to proceed differently based on the input. This capability facilitates clearer communication and interaction within the user interface .

A Radiobutton widget in Python's Tkinter library is used to allow users a selection choice among many exclusive options. It is suitable for this purpose due to its toggle nature, where only one option can be selected at any time. This is implemented by associating each Radiobutton in a group with the same control variable using the IntVar() function. Each Radiobutton is then given a unique value. Selecting a Radiobutton assigns its value to the variable, enabling the application logic to determine which option is chosen. This setup is efficient for gathering predefined inputs, such as a user's choice from a list of categories or preferences .

A 'while' loop in Python is a control structure that repeatedly executes a block of code as long as the loop's condition remains true. It is particularly well-suited for situations where the number of iterations is not known beforehand, as it relies on a boolean condition for continuation. In contrast, a 'for' loop is used when the number of iterations is predetermined, typically iterating over a sequence like a list or a range. You might choose a 'while' loop over a 'for' loop when you need to iterate until a particular condition changes—such as reading data until the end of a file or user input until a valid response is received. Conversely, a 'for' loop is preferred when the number of iterations is fixed or when iterating over iterable objects .

The 'switcher' block in Python differs from traditional switch-case statements because Python does not have a built-in switch-case construct like other languages such as C or Java. Instead, Python uses dictionaries as a workaround for implementing switch-case behavior. A 'switcher' block in Python is essentially a dictionary that maps keys to values. The key serves as the case label, and the value is the statement or function to execute. You can use any data type as a label, which adds flexibility not typically found in traditional switch-case statements. The return statement is used to provide a default case in the absence of a match, which would be the equivalent of a 'default' case in other languages .

To add an image to a Python Tkinter GUI application using a Label widget, the following steps are followed: first, create a Canvas object to display the image. Next, initialize the Canvas object within the GUI. Then, use the PhotoImage function to create and initialize an image object from a file. Finally, call the create_image method of the Canvas class to render the image in the GUI. Using the Canvas class provides more flexibility for manipulating the placement and size of the image compared to directly placing it in the Label .

Python's for loop offers enhanced functionality compared to traditional for loops in languages like C or Java because it is designed to iterate directly over elements of a sequence such as lists, tuples, and strings, or any iterable object. This means that Python doesn't require an explicit statement to declare the loop variable, set a condition, or update the loop index manually, which are typically needed in C or Java. This succinct form of iteration is made possible by Python's built-in range() function, which can also handle starting points, stopping points, and step values. Additionally, Python's for loop can traverse dicts using the keys() or items() methods without requiring conversion or manipulation of indices .

Python's Tkinter library handles mouse events using the 'bind' method to associate an event, like a mouse click, with a specific function. To implement mouse event handling, first, create a user-defined function that takes an event argument and contains the desired event handling code. Next, instantiate a widget, such as a Label, within the Tkinter application. Use the 'bind' method on this widget, specifying both the event type (e.g., '<Button>') and the callback function to be executed when the event occurs. With this setup, the application can respond dynamically to user interactions .

Using synthetic loop structures like Python's 'for' statement with 'range' offers several advantages over traditional indexed loops. Python's 'for' loop automatically handles the loop variable initialization and assignment, reducing potential errors in loop setup and making code cleaner and easier to read. The 'range' function abstracts the iteration process, providing an easy method to specify start, stop, and step parameters without manually managing loop counters. Moreover, 'for' loops in Python naturally iterate over various data structures, facilitating direct traversal over elements without the need for individual indexing, which helps prevent common off-by-one errors and simplifies the codebase .

Python's Tkinter library provides several methods to add text to a widget. One common method is using the Label widget, which allows static text to be displayed with optional formatting such as font and color settings. In contrast, the Text widget allows for dynamic text entry and editing. Additionally, Text widgets can support multi-line input and more complex manipulations such as inserting and deleting text programmatically. Methods like 'insert' and 'get' for Text widgets allow text insertion at specific positions and retrieval of contents, making them more versatile for interactive applications .

You might also like