0% found this document useful (0 votes)
137 views

Python: - Guido Van Rossum

Python is an interpreted, object-oriented, high-level programming language with features like easy to learn syntax, cross-platform capability, large standard library, and dynamic type system. It can be used for web development, system scripting, scientific computing, and more. The core data types in Python include numbers, strings, lists, tuples, dictionaries, sets, and booleans. Variables are used to store and reference values, and don't require explicit declaration of type.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Python: - Guido Van Rossum

Python is an interpreted, object-oriented, high-level programming language with features like easy to learn syntax, cross-platform capability, large standard library, and dynamic type system. It can be used for web development, system scripting, scientific computing, and more. The core data types in Python include numbers, strings, lists, tuples, dictionaries, sets, and booleans. Variables are used to store and reference values, and don't require explicit declaration of type.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 180

PYTHON

-- Guido van Rossum


Features
• Easy to learn – Beginner's programming language
• Interpreted language
• Clean and Elegant syntax
• Cross-platform language
• Free and Open source
• Object-Oriented programming language
• Large standard library
• Integrated – Easily integrated with C, C++,
JAVA, etc..
• Magic methods
What we can do with python?
• Web Development – Django, Flask, Web2py, Bottle, Tornado
• Graphical User Interfaces – Kivy, PyQT, Tkinter, PyGUI, PySide, WxPython
• Multimedia Programming – PyMedia, GStreamer, PyGame, Pyglet
• Database Programming – Supporting connectors for all databases
• Networking – Asyncio, Diesel, Pulsar, Twisted, NAPALM
• Automation – ANN, IOT, MicroPython, Embedded Systems
• Web Scraping – Beautiful Soup, Scrapy, Requests, Selenium
• System Administration – Fabric, Salt, Psutil, Ansible, Chef, Puppet, Blueprint,
Buildout, Shinken
• Scientific Computing – Astrophy, Biopython, Bokeh, Cubes, Dask, Matplotlib,
NetworkX, NumPy, Pandas, PyTorch, SciPy
• Text Processing – NLTK, Polyglot, TextBlob, CoreNLP, Pattern, Vocabulary, QuePy
• Image Processing – OpenCV, Pillow, Scikit-image
• Machine Learning – Scikit-learn, TensorFlow, Keras, Theano, PyTorch
• Data Analytics – NumPy, Pandas, Matplotlib, Seaborn, Plot.ly, SciPy
• Data Science – ML, DA, TensorFlow, Keras
Python Environment Setup -- Windows
• Visit :- https://www.python.org/downloads/
• Run Installer

• Click Install Now


• Click Next

• Click Install
• Set Path

• Click Advance -> Environment variables


• Edit User variable – PATH and add installation path
i.e., C:\Program Files (x86)\Python37-32
Python Environment Setup -- Linux

• Update the APT Repository


– $sudo apt-get update
• Update the APT Repository
– $sudo apt-get install python3.8
Verify Installation
First Python Program
• Python provides us the two ways to run a program:
– Using Interactive interpreter prompt
– Using a script file
•Using Interactive interpreter prompt :-
 Open Terminal or Command Prompt
 Type command – python or python3 (in case you have python2
and python3 both installed)
 Type print(“Hello World!”) and press ENTER key
 You will get a message in console showing Hello World!
• Using a Script File :-
 Open your favorite code editor
 Type the following code
print(“Hello World!”)
 Save the file using <name>.py Let’s save it using HelloWorld.py.
 Now open a Terminal or Command Prompt.
 Navigate using cd command to the directory where you have
placed your python file.
 Now type the following command
$python <filename>.py in my case it is HelloWorld.py
How Python Works?
• Python is an interpreted language i.e., Interpreted language requires
interpreter, which takes the source code and executes one
instruction at a time.
• Now, what is an interpreter?
• An interpreter is a program that is written in some other language
and compiled into machine readable language. The interpreter itself
is the machine language program and is written to read source
programs from the interpreted language and interpret them.

Source Code Interpreter Output


Getting Output on Console
• The print() function :-
Syntax :-
print(*objects, sep=‘ ‘, end=‘\n’, file=sys.stdout, flush=False)

*objects – Objects to print (can be single or multiple).


sep – The separator string to separate two values in case of printing
multiple objects.
end – String to be printed after all objects are printed.
file – The location where we want to print our output.
flush – Normally output to a file or the console is buffered, with text
output at least until you print a newline. The flush makes sure that
any output that is buffered goes to the destination.
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
• Comments starts with a #, and Python will ignore them :-
#This is a comment
print("Hello, World!")
print("Hello, World!") #This is a comment
• We can use multi line comments also using triple quoted string :-
"“”This is a comment
Multiline comment""“
‘’’This is also a
multiline comment’’’
print("Hello, World!")
Python Comments Cntd…
• Example demonstrating comments :-

#This is single line comment


‘’’Comments can not be
executed by the interpretor’’’
print(“Pretty Cool! Isn’t it?”)
Python Variables
• Variable is a name used to refer memory locations because we can’t
remember memory addresses and used to hold values.
• In Python, we don’t need to specify type of the variable because Python is
smart enough to get variable type.
• Variables can be named using combination of letters, digits and
underscore (_) . No other special symbol can be used.
• Variables can begin with letter or underscore but not with digit.
• Python is case sensitive language.
• Variables can also be called as identifiers.
• Valid identifiers:- a123, _n, n_9
• Invalid identifiers:- 1a, n%4, n 9
• The equal (=) operator is used to assign value to a variable.
• Python doesn’t bound us to declare variables before use. It allows us to
create variable at required time.
• Example:- a=10
name=“Python Developer”
Python Variables Cntd…
• Python support Multiple Assignments
x=y=z=50 (Here, x,y,z have same value i.e., 50)
x,y=20,42 (Here, x =20 and y=42)
• Example to demonstrate the variables:-
a=10
b,c=20,30
x=y=z=50
print(a)
print(b)
print(c)
print(x)
print(y)
print(z)
Python Data Types
• Variables can hold values of different data types.
• Python is a dynamically typed language hence we need not define
the type of the variable while declaring it.
• The interpreter implicitly binds the value with its type.
• We can check type of a variable using type() function.
• Example:-
A=10
print(type(A))
Python Data Types Cntd…
• Standard Data Types
– Numbers  int, float, complex
– String  str
– Sequence  list, tuple, range
– Mapping  dict
– Set  set, frozenset
– Boolean  bool
Python Data Types Cntd…
• Setting the Data Type to a variable
– x=“Hello World” str
– x=20 int
– x=20.5 float
– x=1j complex
– x=[‘apple’,’banana’] list
– x=(‘apple’,’banana’) tuple
– x=range(6) range
– x={‘name’:’python’,’age’:29} dict
– x={1,2,3,4} set
– x=frozenset({1,2,3,4}) frozenset
– x=True bool
Python Data Types Cntd…
• list, dictionary and set are mutable objects.
• frozenset, string, tuple are immutable objects.
• frozenset objects are mainly used as key in dictionary or elements of
other sets.
• Example :-
Student = {"name": “Python", "age": 29,  “created by": “Guido
van Rossum “}
k=frozenset(Student)
print(k)
Python Keywords
• Python Keywords are special reserved words which convey a special
meaning to the interpreter.
• These keywords can't be used as variable.
• They are as follows :-

True False None and as


asset def class continue break
else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda
Python Strings
• Strings are arrays of bytes representing Unicode characters.
• A String is a sequence of characters.
• A single character is simply a string with a length of 1.
• A string is always defined in between single or double quotes (‘ or
“).
• Strings are immutable.
• To create multiline strings use triple quotes (‘’’ or “””)
• Strings can be accessed via three methods:
– Indexing
– Slicing
– Loops
Python Strings Cntd…
• Example to create String variable :-
a=“This is Single line string”
b=“””This is Multliline
string”””
print(type(a),type(b))
print(a,’\n’,b)
Accessing Strings using Indexing
• Index of strings starts with 0 and ends with (n-1). Here, n stands for
the total number of characters in the string i.e., length of string.
“Hello World!”

0 1 2 3 4 5 6 7 8 9 10 11
H e l l o W o r l d !

• To access string character by character use index number enclosed


by square braces.
• Example :-
a=“Hello World!”
print(a[0])
print(a[6])
Accessing Strings using Slicing
• Syntax :-
str[start:stop:step]
• start – start index number (included)
• stop – stop index number (excluded)
• step – spacing between values
• Example :-
a=“Hello World!”
print(a[0:3:1])
print(a[1:8:2])
print(a[:3])
print(a[3:])
print(a[::])
print(a[8:1:-1])
print(a[::-1])
Strings - Escape Sequences
• \<newline> Ex:- print(“Hello \
World”)
• \\ Backslash Ex:- print(“2020\\01\\01”)
• \’ Single quote Ex:- print(“Monty\’s Python”)
• \” Double quote Ex:- print(“The \” for\” loop”)
• \a ASCII Bell Ex:- print(“\a”)
• \b ASCII Backspace Ex:- print(“Hello \b World”)
• \n ASCII Linefeed Ex:- print(“Hello\nWorld”)
• \r Carriage Return Ex:- print(“Hello\rWorld“)
• \t Horizontal TAB Ex:- print(“Hello\tWorld”)
• \v Vertical TAB Ex:- print(“Hello\vWorld”)

Monty Python are a British surreal comedy group who created the sketch comedy television show Monty
Python's Flying Circus, which first aired on the BBC in 1969.
Escape Sequences - Example
Python String Functions
• capitalize()  Return a copy of the string with its first character
capitalized and the rest lowercased.
• center(width[,fillchar])  Return centered in a string of length width.
Padding is done using the specified fillchar.
• count(sub[,start[,end]])  Return number of occurrences of substring
sub in range[start,end].
• endswith(sub[,start[,end]])  Return True if string ends with specified
substring sub in range[start,end].
• find(sub[,start[,end]])  Return lowest index in the string where
substring sub is found in range[start,end] else return -1.
• rfind(sub,[,start[,end]])  Return highest index in the string where
substring sub is found in range[start,end] else return -1.
• index(sub,[,start[,end]])  Return lowest index in the string where
substring sub is found in range[start,end] else raise ValueError.
• rindex(sub,[,start[,end]])  Return highest index in the string where
substring sub is found in range[start,end] else raise ValueError.
Python String Functions Cntd…
• lower()  Convert all upper case letters to lower case in the string.
• split(sep[,maxsplit])  Return a list of substrings of the string splitted on
the basis of sep and length of maxsplit.
• join(words)  Concatenate a list or tuple of words separating with sep.
• lstrip()  Return a string with leading white spaces removed.
• rstrip()  Return a string with trailing white spaces removed.
• strip()  Return a string with leading and trailing both white spaces
removed.
• swapcase()  Return copy of string after converting lowercase letters to
uppercase letters and vice versa.
• upper()  Return copy of string after converting all characters to
uppercase letters.
• replace(old,new)  Return a copy of string with all occurrences of
substring old replaced by new.
• len(string)  Return length of the string i.e., number of characters in the
string.
Python String Examples…
Python Lists
• Lists are just like the arrays.
• Lists may contain Homogenous or Heterogeneous data i.e., A list may
contain integer data as well as float, string, list or any other type of
data unlike arrays.
• Lists are mutable objects.
• A List is always defined in between braces([ ]).
• Lists can be accessed via three methods:
– Indexing
– Slicing
– Loops
Python Lists Cntd…
• Example to create a List object :-

a=[1,2,3,4]
print(type(a)
print(a)
b=[1,2.5,”Hello”,3+3j]
print(type(b))
print(b)
Accessing Lists using Indexing
• Index of lists starts with 0 and ends with (n-1). Here, n stands for the
total number of elements in the list i.e., length of list.
[1,2.5,’Hello’,3+3j]

0 1 2 3
1 2.5 ‘Hello’ 3+3j
• To access list element by element use index number enclosed by
square braces.
• Example :-
a= [1,2.5,’Hello’,3+3j]
print(a[0])
print(a[2])
Accessing Lists using Slicing
• Syntax :-
list[start:stop:step]
• start – start index number (included)
• stop – stop index number (excluded)
• step – spacing between values
• All rules of slicing we have seen in strings apply on lists also.
• Example :-
a= [1j, 2, 4, 4, “Python is easy!”,3, 3.5, 3, 6, 5]
print(a[0:3:1])
print(a[1:8:2])
print(a[:3])
Python Lists Operations
• Change Value of Item in a List :-
To change the value of specific item in a list, use index number
and assign a value to it. Example:-
ls=[‘apple’,’banana’,’cherry’]
print(ls)
ls[1]=‘strawberry’
print(ls)
Python Lists Operations Cntd…
• Check Item if Exist in a list :-
To determine if a specified item is present in in a list or not, use
the in and not in keyword. Example:-
ls=[‘apple’,’banana’,’cherry’]
print(‘apple’ in ls)
print(‘python‘ in ls)
print(‘apple’ not in ls)
print(‘python‘ not in ls)
Python Lists Functions
• len(list)  Return length i.e., number of elements in a list.
• append(x)  Adds an item (x) to the end of the list.
• extend(iterable)  Extend the list by appending all the items from
the iterable.
• insert(i,x)  Inserts an item (x) at a given index i.
• remove(x)  Removes the first item from the list that has a value of
x. Returns an error if there is no such item.
• pop([i])  Remove and return the item at the given index in the list.
If no index is specified, pop() removes and returns the last item in list.
• clear()  Removes all items from the list.
• index(x[,start[,end]])  Returns the position of the first list item that
has a value of x. Raise a ValueError if there is no such item. The start
and end arguments are used to limit the search for the item in a
particular subsequence. Returned index is computed relative to the
beginning of the full sequence.
Python Lists Functions Cntd…
• count(x)  Returns the number of times x appears in the list.
• sort([key=None,reverse=False)  Sorts the items of the list in place.
key specifies a function of one argument that is used to extract a
comparison key from each list element. The default value is None
(compares the elements directly). reverse Boolean value. If set to
True, then the list elements are stored as if each comparison were
reversed.
• reverse()  Reverses the elements of the list in place.
• copy()  Returns a shallow copy of the list.
• list([iterable])  list() constructor returns a mutable list of elements.
• max(iterable,*,key,default)  Returns the largest item in inerrable
or largest of two arguments.
• min(iterable,*,key,default)  Returns the smallest item in inerrable
or smallest of two arguments.
• del(x)  Deletes the value or object specified by x.
Python List Examples…
Python Tuple
• Tuple is just like the arrays.
• Tuple may contain Homogenous or Heterogeneous data i.e., A Tuple
may contain integer data as well as float, string, list or any other type
of data unlike arrays.
• Tuple is immutable object.
• A tuple is always defined in between braces(( )).
• Tuple can be accessed via three methods:
– Indexing
– Slicing
– Loops
Python Tuple Cntd…
• Example to create a Tuple object :-

a=(1,2,3,4)
print(type(a))
print(a)
b=(1,2.5,”Hello”,3+3j)
print(type(b))
print(b)
Accessing Tuple using Indexing
• Index of tuple starts with 0 and ends with (n-1). Here, n stands for
the total number of elements in the tuple i.e., length of tuple.
(1,2.5,’Hello’,3+3j)

0 1 2 3
1 2.5 ‘Hello’ 3+3j
• To access tuple element by element use index number enclosed by
square braces.
• Example :-
a= (1,2.5,’Hello’,3+3j)
print(a[0])
print(a[2])
Accessing Tuple using Slicing
• Syntax :-
tuple[start:stop:step]
• start – start index number (included)
• stop – stop index number (excluded)
• step – spacing between values
• All rules of slicing we have seen in strings apply on tuple also.
• Example :-
a= (1j, 2, 4, 4, “Python is easy!”,3, 3.5, 3, 6, 5)
print(a[0:3:1])
print(a[1:8:2])
print(a[:3])
Python Tuple Operations
• Check Item if Exist in a tuple :-
To determine if a specified item is present in in a tuple or not,
use the in and not in keyword. Example:-
t=(‘apple’,’banana’,’cherry’)
print(‘apple’ in t)
print(‘python‘ in t)
print(‘apple’ not in t)
print(‘python‘ not in t)
Python Tuple Functions
• len(tuple)  Return length i.e., number of elements in a tuple.
• del(x)  Deletes the value or object specified by x.
• tuple([iterable])  tuple() constructor returns a immutable tuple of
elements.
• count(x)  Returns the number of times x appears in the tuple.
• index(x[,start[,end]])  Returns the position of the first tuple item
that has a value of x. Raise a ValueError if there is no such item. The
start and end arguments are used to limit the search for the item in a
particular subsequence. Returned index is computed relative to the
beginning of the full sequence.
• max(iterable,*,key,default)  Returns the largest item in inerrable
or largest of two arguments.
• min(iterable,*,key,default)  Returns the smallest item in inerrable
or smallest of two arguments.
Python Tuple Examples…
Python Set
• A set is a collection which is unordered and unindexed. Set is
mutable object.
• A set is always defined in between braces({ }).
• A set eliminates all repeated values and keeps a single copy of all
elements.
• Set can be accessed via one methods:
– Loops
– Does not support indexing and slicing
• Example to create a Set object :-
a={1,2,3,4,4,5,3,6,7}
print(type(a))
print(a)
Python Set Operations
• Check Item if Exist in a set :-
To determine if a specified item is present in in a set or not, use
the in and not in keyword. Example:-
t={‘apple’,’banana’,’cherry’}
print(‘apple’ in t)
print(‘python‘ in t)
print(‘apple’ not in t)
print(‘python‘ not in t)
Python Set Functions
• len(set)  Return length i.e., number of elements in a set.
• del(x)  Deletes the value or object specified by x.
• set([iterable])  set() constructor returns a mutable set of elements.
• max(iterable,*,key,default)  Returns the largest item in iterable or
largest of two arguments.
• min(iterable,*,key,default)  Returns the smallest item in iterable or
smallest of two arguments.
• add(x)  Adds value x in set.
• update([iterable])  Adds more than one items in set.
• remove(x)  Removes element x from set. If x not exists in set then
it raises ValueError.
Python Set Functions Cntd…
• clear()  It empties the set.
• set1.union(set2)  Return a new set with all items in both sets set1
and set2.
• set1.intersection(set2)  Return a set that contains the items
common in set1 and set2.
• set1.intersection_update(set2)  Remove items that are not
present in both set1 and set2 from set1.
• discard(x)  Removes element x from set. If x not exists in set then
does not raises ValueError.
• pop()  Remove the last item from set and return it. Since sets are
unordered So we cannot decide which element gets removed.
Python Set Examples…
Python Dictionaries

• Dictionary is a collection which is unordered, mutable and indexed.


• Dictionary may contain Homogenous or Heterogeneous data i.e., A
dictionary may contain integer data as well as float, string, list or any
other type of data unlike arrays.
• A dictionary is always defined in between braces({key:value}).
• A dictionary contain key value pair relationships just like our ordinary
oxford dictionary. A key can have multiple values in form of iterable
associated with it.
• dictionary can be accessed via three methods:
– Specifying key
– Using functions (get(), values(), keys())
– Loops
Python Dictionaries Cntd…
• Example to create a List object :-

d= {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(d))
print(d)
Accessing Dictionaries Specifying Key
• To access dictionary value use key enclosed by square braces.
• Example :-
d= {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(d[‘brand’])
print(d[‘year’])
Accessing Dictionaries using Functions
• get(key)  Used to access value of the key specified.
d= {
   "brand": "Ford",
   "model": "Mustang",
   "year": 1964
}
print(d.get(‘model’))

• values()  Return iterable object containing all values of dictionary.


• keys()  Return iterable object containing all keys of dictionary.
d= { "brand": "Ford“,
"model": "Mustang",
   "year": 1964}
print(d.values())
print(d.keys())
Python Dictionaries Operations
• Change Value of Item in a dictionary :-To change the value of specific
item in a dictionary, use key and assign a value to it.
• Adding new key value pair in dictionary :- Just create a new key and
assign a value to it.
d= { "brand": "Ford“,
"model": "Mustang",
"year": 1964
}
print(d)
d[‘year’]=1985
print(d)
d[‘sales’]=1000
print(d)
Python Dictionaries Operations Cntd…
• Check Item if Exist in a dictionary:-To determine if a specified key is
present in a dictionary or not, use the in and not in keyword.
d= {
"brand": "Ford“,
"model": "Mustang",
"year": 1964
}
print(‘brand’ in d)
print(‘sales‘ in d)
print(‘brand’ not in d)
print(‘sales‘ not in d)
Python Dictionaries Functions
• len(dict)  Return length i.e., number of elements in a dictionary.
• pop(key)  Remove and return the value at the given key in the
dictionary. If no key is specified, pop() removes and returns the value
in dictionary.
• popitem ()  Remove last inserted item from dictionary.
• del(x)  Deletes the value or object specified by x.
• clear()  Removes all items from the dictionary.
• copy()  Returns a shallow copy of the dictionary.
• dict(key=value[,key=value…])  Return a dictionary made up of
specified key value pairs.
• items()  Returns a list containing a tuple for each key value pair.
Python Dictionary Example
Python Operators
• A mathematical operation is divided into following two objects :-
– Operands  The address or data in instruction to be operated
on.
– Operators  The operation being performed on the operands.
Example :- 2+4 (here, 2 & 4 are operands in form of data and + is
operator)
Example :- a+b (here, a & b are operands in form of address and
+ is operator)
• Types of Operators :-
– Arithmetic operators
– Assignment operators
– Comparison operators
– Logical operators
– Identity operators
– Membership operators
– Bitwise operators
Arithmetic Operators

Operator Name Example Output


+ Addition 2+3 5

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/2 2.5

// Floor Division 5//2 2

% Modulus 5%2 1

** Exponentiation 5**2 25
Assignment Operators
Operator Example Same As
= X=5 X=5
+= X+=3 X=X+3
-= X-=3 X=X-3
*= X*=3 X=X*3
/= X/=3 X=X/3
%= X%=3 X=X%3
//= X//=3 X=X//3
**= X**=3 X=X**3
&= X&=3 X=X&3
|= X|=3 X=X|3
^= X^=3 X=X^3
>>= X>>=3 X=X>>3
<<= X<<=3 X=X<<3
Comparison Operators
Operator Name Example Output

== Equal 5==2 False

!= Not Equal 5!=2 True

> Greater Than 5>2 True

< Less Than 5<2 False

>= Greater Than or Equal To 5>=2 True

<= Less Than or Equal To 5<=2 False


Logical Operators

Operator Name Example Output


and Logical And 2<5 and 2<10 True
or Logical Or 2<5 or 2<1 True
not Logical Not not(2<5 and 2<10) False

Identity Operators
Operator Description Example
is Returns True if both variables are same object x is y
is not Returns True if both variables are not same x in not y
object
Membership Operators
Operator Description Example
in Returns True if a sequence have the specified value x in y
not in Returns True if a sequence do not have the specified value x not in y

Bitwise Operators
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of the two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Left Shift Shift bits to left pushing zeros in right
>> Right Shift Shift bits to right pushing zeros in left
Python Type Casting
• To specify one type of variable to other type we use type casting.
• For type casting we use constructor of the type class in which we
want to cast the variable. This is due to the fact that Python is OOP,
so it uses classes even for its primitive types.
– int()  To cast a variable to integer.
– float()  To cast a variable to float.
– str()  To cast a variable to string.
– list()  To cast a variable or iterable to list.
– dict()  To cast a variable or iterable to dictionary.
– tuple()  To cast a variable or iterable to tuple.
– set()  To cast a variable or iterable to set.
– frozenset()  To cast a variable or iterable to frozenset.
Getting Input From Console
• The input() function :-
Syntax :-
input([prompt])
prompt – If specified, it is written to standard output without a
trailing newline.
– The function then reads a line from input.
– Then converts it to string (stripping a trailing newline) and returns
that.
– When EOF is read, EOFError is raised.
– Example :-
a=input(“Enter something in console”)
print(type(a))
print(a)
Python Conditional statements
• We need the ability to check conditions and change the behavior of
the program accordingly.
• So, we use Conditional statements in a programming language.
• Here is the flow diagram how they works.

START

NO
Condition False Block

YES

True Block

EXIT
Python Conditional Statements Cntd…

A=28

NO
If A is Even Print Odd

YES

Print Even

EXIT
Python Conditional Statements Cntd…
• When any type of block is being created it introduces us to
indentations.
• Indentations are whitespaces at the beginning of a line.
• It is used to define scope of the code block.
• Other programming languages use curly-braces for this purpose.
• Syntax if - else statement :-
if expression: #colon (:) defines the block
Statement for true block #proper indented region eliminate error
else: #in original scope indicates true block end
Statement for false block
• Short Hand Notation :-
[True Statement] if expression else [False statement]
Python Conditional Statements Cntd…
• Example :-
a=int(input(“Enter a number”))
if a%2 == 0:
print(“Even Number”)
else:
print(“Odd Number”)
Python Conditional Statements Cntd…
• Syntax if - else statement :-
if expression1:
True block1
elif expression2:
True block2
else:
False block
• Short Hand Notation :-
[True Statement1] if expression1 else [True Statement2] if
expression1 else [False Statement]
Python Conditional Statements Cntd…
• Example :-
Python Iteration
• We need the ability to repeatedly execute a code block on a
specified condition. Also called as loops.
• So, we use Iteration statements in a programming language.
• Here is the flow diagram how they works.

START

NO
Condition

YES

True Block

EXIT
Python Iteration Cntd…
• The “range” function  It is used to generate numbers within the
specified range arguments. It is immutable sequence type.
• Syntax :-
range(start,stop,step)
start  The starting value from which we want to generate
numbers.
stop  The stop value where you want to end your generator (will
work upto stop-1).
step  The difference between two numbers being generated.
• To extract values from range function we use for loop.
• Example :-
Python Iteration Cntd…
• We have Two types of iterative statements :-
• for
• while
• The “while” loop  It repeat as long as a certain condition met.
• Syntax :-
[initialization of loop counter]
while expression:
block statements
[change in loop counter]
• The “for” loop  It iterates over a iterator object (sequence).
• Syntax :-
for [variable] in [iterator]:
block statements
Python Iteration Cntd…
Example of “while” Loop 
Python Iteration Cntd…
Example of “for” Loop 
Dictionaries and Loops
• To Access data from dictionary using loop we can use “for” loop and
its builtin function items() or values() or keys().
Python Break and Continue
• The “break” statement :- The “break” statement is used to exit from
a loop on a specified condition.
• The “continue” statement :- The “continue” statement is used to skip
the current block and return to the first statement of the loop on a
specified condition.
• Example :-
else clause in Loops
• When condition in loop fails then else gets executed.
• If break statement is executed in loop then else part is skipped.
• If continue statement executed in loop then else part isn’t skipped.
• Example :-
List and Set Comprehensions
• List comprehension is an elegant way to define and create list in
python.
• For list use [], for tuple use () and for sets use {}.
• Syntax :-
[expression for item in iterator if condition]
[True statement if condition else False statement for item in
iterator]
• Example :-
Dictionary Comprehensions
• Syntax :-
{key:val for key,val in iterable if condition}
• Example :-
Python Functions
• A block of code which only runs when it is called.
• Enables code reusability.
• We can pass data, known as parameters.
• A function can return data as a result.
• We use def keyword to create a function.
• A block is created, So pay attention to Indentations.
• Build to perform a specific task.
• Types of Functions :-
• Parameterized and Non Parameterized functions
• Default Arguments in function
• Keyword Arguments in function
• Variable Length Arguments
• Lambda Functions
• Generator Functions
• Decorator Functions
Non Parameterized Functions
• Does not accept any parameters or arguments.
• Simply called using their name to perform the specific task.
• Example :- clear() function clears contents of a iterable.
• Syntax :-
def <FunctionName>(): #Block is created, Need Indentations
Body #body of the functions to execute
[return values] #return value if any

FunctionName()#calling the function

• Example not returning any value :-


Non Parameterized Functions Cntd…
• Example function returning a value :-
Parameterized Functions
• Accept any number of parameters or arguments.
• Simply called using their name and passing required parameters in function.
• Example :- insert(i,x) function insert x in list at index i.
• Syntax :-
def <FunctionName>(para1[,paraN]):
Body
[return values]

FunctionName(val1[,valN])

• Example not returning any value :-


Parameterized Functions Cntd…
• Example function returning a value :-
Default Arguments in Functions
• Accept any number of parameters or arguments and can have their default values.
• It is not compulsory to set values of default parameters.
• Example :- pop(i=-1) function delete value from last if i not provided in a list.
• Syntax :-
def <FunctionName>(para1[,paraN],defalutPara1=val[, defalutParaN=val]):
Body
[return values]

FunctionName(val1[,valN],[defalutVal1[,defaultValN]])

• Example not returning any value :-


Default Arguments in Functions Cntd…
• Example function returning a value :-
Keyword Arguments in Functions
• While calling a function we can pass arguments as keyword=value pair.
• So that we can pass our arguments in any order.
• Example :- print(*obj,sep=‘’,end=‘\n’) while calling we can pass value in any order.
• Syntax :-
def <FunctionName>(para1[,paraN]): #parameters can be default also
Body
[return values]

FunctionName(kwrd1=val1[,kwrdN=valN])

• Example :-
Variable Length Arguments in Functions
• In these types of functions we can pass any number of arguments. They will store in a tuple in
the function amd keyword arguments stored in a dictionary.
• Example :- print(*obj) while calling we can pass any number of values to print.
• Syntax :-
def <FunctionName>(*args,**kargs):
Body
[return values]

FunctionName(arg1[,argN],[karg1=val1[,kargN=valN]])

• Example :-
Lambda Functions
• Anonymous function without a name.
• lambda keyword is used to define lambda functions.
• Have any number of arguments but have only one expression.
• Always return an expression.
• Syntax :-
lambda arguments: expression
• Example :-
Generator Functions
• Generators are iterable functions.
• Generate values once at a time from a given sequence, instead of
giving entire sequence.
• yield keyword is used to return values from generator functions.
• We need to call next() function in order to get values one by one
from generator functions.
• After returning all values one by one next() function raises
StopIteration error, indicating all values are taken out.
• Example :-
Decorator Functions
• Functions are objects, they can be referenced to, passed to a variable
and returned from other functions as well.
• Functions can be defined inside another function and can also be
passed as argument to another function.
• Decorators allow programmers to modify the behavior of function or
class.
• Decorators allow us to wrap another function in order to extend
behavior of wrapped function, without permanently modifying it.
• Syntax :-
@funcDcrtr #It is equivalent to
def dcrtrFunc(): def dcrtrFunc():
print(“func”) print(“func”)
dcrtrFunc = funcDcrtr(dcrtrFunc)
Decorator Functions Cntd…
• In above codes, funcDcrtr is a callable function, will add some code
on the top of some another callable function, dcrtrFunc and return a
wrapper function.
• Example1 :-
Python Modules
• Module is a collection of functions, classes and variables packaged in
a file.
• Enables code reusability.
• Can be created using import, from, as keywords.
• Syntax1 :-
import <ModuleName>
#this will import the source file ModuleName in another file.
• Syntax2 :-
from <ModuleName> import name1[,name2[,nameN]]
#this will import specific attributes from a ModuleName into
current file.
• Syntax3 :-
import <ModuleName> as <NewName>
#this will import ModuleName renamed as NewName.
Modules - import
• With help of import statement, we can use any Python source file as
a module in some other source file.
• It imports the module if the module is present in the search path.
• Example :-
Modules – from, import
• With help of from, import statement, we can import specific
attributes from a module in current file.
• It does not import the entire module, rather it imports the attributes
we specified.
• from <module> import * imports all the attributes from the module.
• Example :-
Modules – import, as
• from, import statement helps us to import a module with other
name (renaming), later we can use this name to use that module.
Example :-
Python Exception Handling
• An exception can be defined as an abnormal condition in a program
resulting in the flow of the program.
• It causes the program to halt the execution.
• So exception handling is a way to deal with this problem. So that
other part of the code can be executed without any disruption.
• Common Exception :-
– ZeroDivisionError – Occurs when a number is divided by 0.
– NameError – Occurs when a name is not found (local or global).
– IndentationError – Occurs when incorrect indentation is given.
– IOError – Occurs when Input Output operation fails.
– EOFError – Occurs when end of file is reached, and yet operations
are being performed.
Python Exception Handling Cntd…
• Problem without handling exception :-

• Here, we have entered b=0.


• It raises ZeroDivisionError at c = a/b.
• It causes program to entered in halt condition.
• So in order to handle this situation, We have exception handling.
Python Exception Handling Cntd…
• We have following keywords to handle exceptions, so that we can
deal with exceptions in several ways :-
• try
• except
• else
• finally
• raise
• The try and except keywords :-
try:
Test This Code For An Exception
except:
Run This Code If An Exception Occurs

• We can have multiple except blocks associated with one try block.
Python Exception Handling Cntd…
• Syntax :-
try:
#test block
except Exception:
#handle the exception
• Example :-
Python Exception Handling Cntd…
• The else keyword :-
try:
#test code
except Exception:
#handle exception, if any
else:
#do this if no exception raised
• Example :-
Python Exception Handling Cntd…
• The finally keyword :-
try:
#test code
except Exception:
#handle exception, if any
finally:
#always run this code
• Example :-
Python Exception Handling Cntd…
• The raise keyword :- Exception can be raised using following syntax-
raise Exception_class, <value>
• Example :-
Object Oriented Programming
• Allows writing of programs with help of certain real-time objects.
• The states and behaviors of real-world objects are to be considered.
• Has following features :-
– Classes
– Objects
– Inheritance
– Polymorphism
– Encapsulation
– Abstraction
• Consider a Pen object, It can have several properties and functions
(like color, type, ink filling method etc…)
• Many different types of pens are present and they are all be in pen
category.
• So to deal with this scenario we need OOP.
Object Oriented Programming Cntd…
• Advantages :-
– Easy to understand.
– We can model a real-world concept using OOP.
– Offers reusability of the code.
– Parallel development of classes implies quick development.
– Easier to maintain and test.
– Provide data hiding providing more security to our code.
– Provide efficient way to handle Data Redundancy.
– Data storage and management is easier.
Object Oriented Programming Cntd…
• Object  The object is the real-world entity that has some states and
behaviors (like pen, chair, table, etc…). In python everything is an object
and almost all have some attributes and behaviors (methods).
• Class  The class can be defined as a collection of objects. It can also be
defined as blueprint of object (like blueprint of a building). It is a logical
entity that contains attributes of objects.
• Inheritance  It specifies that the child object acquires all attributes of
the parent object (like we humans inherit our parents). It provides code
reusability.
• Polymorphism  Poly means Many and morphs means Forms. One task
can be performed in different ways (like all animals speak but all in
different ways).
• Encapsulation  Used to wrap code and data in a single unit (like capsules
wrap many types of medicines in a single unit).
• Abstraction  Used to provide data and internal implementation hiding
feature (like we make call from our mobile phone without worrying about
its technical aspects).
Encapsulation - Class and Objects
• Creating classes :- use class keyword
class ClassName:
#block of code
• Creating objects :-
Object-name = class-name(<arguments>)
• The self keyword :- It is used to store reference to current object. A
class can have many objects with different attribute values. So this is a
mechanism to differentiate between all objects.
• General Form of OOP approach :-
class ClassName:
#properties
#behaviors
obj = ClassName(<arguments>)
obj.properties
obj.behaviors
Class and Objects Cntd…
• Example :-
Class and Objects Cntd…
• Storage of previous Example :-

EMP1.ID 1

PQR
EMP1.NAME
EMP1

EMP2
EMP2.ID
2

EMP2.NAME XYZ
Class and Objects - Constructors
• It is a special type of method which is used to initialize the instances
of the class.
• Constructor is executed with creation of the objects.
• It also verify that there are enough resources for the object to
perform any start-up task.
• To create constructor __init__ method is used. We can pass any
number of arguments to create and initialize objects to constructor.
• Example :-
Class and Objects – Static Variables
• These type of variables are shared by all the objects.
• All variables which are assigned a value in class declaration are static
variables. And variables which are assigned values inside class
methods are instance variables.
• Static variables are also called as class variables.
• Example :- A simple object counter
Inheritance
• Provide code reusability because we can use existing class to create a
new class.
• The child class acquires properties and can access all data members
and functions in the parent.

BASE CLASS PARENT CLASS

DERIVED CLASS CHILD CLASS

• Syntax :-
class derived-class(base-class):
#block of class
Inheritance Cntd…
• Example :-
Types of Inheritance
• Single Inheritance :-
BASE CLASS
PARENT CLASS

DERIVED CLASS CHILD CLASS

• Multilevel Inheritance :-
BASE CLASS GRANDPARENT CLASS

DERIVED CLASS PARENT CLASS

DERIVED CLASS CHILD CLASS


Types of Inheritance Cntd…
• Multiple Inheritance :-
BASE CLASS 1 BASE CLASS 2

DERIVED CLASS

• Hierarchical Inheritance :-
BASE CLASS

DERIVED CLASS 1 DERIVED CLASS 1


Polymorphism
• Polymorphism can be achieved using method overriding.
• Parent class method is defined in the child class with specific
implementation.
• Example :-
Abstraction
• To make data private to that class so that it cannot be accessed
outside to the class use double underscore ( __ ) as a prefix to the
attribute which is to be hidden.
• Example :-
Python File Handling
• We can store data to local file system which is volatile and can be
accessed every time.
• Following operations can be performed on files :-
• Creating a file
• Opening a file
• Closing a file
• Reading from a file
• Writing to a file
• File pointers positions
• Renaming a file
• Removing a file
• Creating a new directory
• Deleting a directory
File Modes
MODE DESCRIPTION
r Read only mode, open text file, pointer location beginning, file must exist.
rb Read only mode, open binary file, pointer location beginning, file must exist.
r+ Read & Write mode, open text file, pointer location beginning, file must exist.
rb+ Read & Write mode, open binary file, pointer location beginning, file must exist.
w Write only mode, open text file, pointer location beginning, file created if not exist.

wb Write only mode, open binary file, pointer location beginning, file created if not exist.

w+ Write and read mode, open text file, pointer location beginning, file created if not exist.

wb+ Write and read mode, open binary file, pointer location beginning, file created if not exist.

a Append only mode, open text file, pointer location end of file, file created if not exist.

ab Append only mode, open binary file, pointer location end of file, file created if not exist.

a+ Append and read mode, open text file, pointer location end of file, file created if not exist.

ab+ Append and read mode, open binary file, pointer location end of file, file created if not exist.

x Create a new file.


Creating and Opening a File
• Use open() function :-
fp = open(filename, mode)
• File can be test or binary file.
• We can use r, r+, rb, rb+ modes to open a file but file cannot be
created. Raise FileNotFoundError.
• We can use x to create a file.
• We can use w, w+, wb, wb+, a, ab, a+, ab+ modes to open a file and if
it is not exists then it will be created first.
• Example :-
Writing to a file
• To write to a file we can use append or write modes to open the file.
• Use write() function to write contents to a file.
fp.write(content)
• Example :-
Reading from a file
• Three functions used to read content from a file.
read(count)  Read number of chars from file specified by count.
read()  Read the whole file.
readline()  Read a line from the file.
• Example :-
Reading from a file Cntd…
• We can also use loop for accessing the file contents.
• Example :-
File Pointer Positions
• To get the position of the file pointer use tell() function.
• To set the position of the file pointer use seek() function.
pos = fp.tell()
fp.seek(offset[,from])
• offset refers to new position of the file pointer within the file.
• from indicates the reference position from where the bytes are to be
moved. If it is 0, beginning of the file is considered. If it is 1, current
position is considered. If it is 2, end of the file is considered.
• Example :-
OS module
• Renaming a file :-
rename(current_file_name, new_name)
• Removing a file :-
remove(file_name)
• Creating a new Directory :-
mkdir(directory_name)
• Deleting a directory :-
rmdir(directory_name)
• Example :-
Python - Working With Databases
• To build real world applications, connecting with the databases is
necessary.
• Python allows us to connect our application to all databases using
specific driver/connector.
• Databases need SQL language to implement them.
• Steps for integrating database in our application :-
– Install the necessary connector for the database.
– Then import the necessary modules in the program.
– Create a connection object to the database.
– Create a cursor object.
– Execute the query and get the desired result.
Python – MySQL Setup
• Installation of the database and setting up :-
– Download XAMPP installer using following link
https://www.apachefriends.org/index.html
Python – MySQL Setup Cntd…
• Test for the installation :-
– Look for XAMPP Control Panel in Start Menu.
– Start the Services.
– Test in Browser
http://localhost/phpmyadmin
Python – MySQL Setup Cntd…

List of Databases
and Tables
Python – MySQL Setup Cntd…
• Now install the MySQL connector for the python :-
python –m pip install mysql-connector
• Now test the installation :-
Python – MySQL
• Import the module :-
import mysql.connector as db
• Creating the connection :-
con_obj = db.connect(host = <host-name>, user = <username>,
passwd = <password>, database = <database-name>)
• Create a cursor object :-
<my_cur> = con_obj.cursor()
• Executing queries :-
cur.execute(<query-string>)
• Closing the connection :-
con_obj.close()
Python – MySQL
• Example :-
MySQL – SQL Queries
• To create Databases :-
create database <database-name>;
• To delete Databases :-
drop database <database-name>;
• To create Tables :-
create table <table-name>{
<column1> <data-type>(<size>) <constraint>,
<column2> <data-type>(<size>) <constraint>,
.
.
PRIMARY KEY(<columns>)
};
• To delete Tables :-
drop table <table-name>;
MySQL – SQL Queries Cntd…
• To show databases :-
show databases;
• To use a database :-
use <database-name>
• To show tables :-
show tables;
• To insert data in the table :-
insert into <table-name> (col1, col2, …) values (val1, val2, …);
• To select data from the table :-
select col1, col2, … from <table-name>;
select * from <table-name>;
select distinct col1, col2, … from <table-name>;
select * from <table-name> where condition1 and/or condition2…;
select * from <table-name> order by col1, col2, … asc/desc;
MySQL – SQL Queries Cntd…
• To update record in Table :-
update <table-name> set col1=val1, col2=val2, … where condition;
• To delete record from Table :-
delete from <table-name> where condition;
• To limiting selected data :-
select col-name(s) from <table-name> where condition limit
number;
select top <number> col-name(s) from <table-name>;
select top <number> percent col-name(s) from <table-name>;
• To count, avg, and sum of records :-
select count(col), avg(col), sum(col) from <table-name>;
• To select min and maximum in records :-
select min(col), max(col) from <table-name>;
Python – MySQL Insert
• Insert Operation :-
– Execute the query using execute() function to insert a single
record.
– Execute the query using executemany() function to insert multiple
records.
– To save the transaction, commit the transaction using commit()
function.
– To undo the transaction, rollback the transaction using rollback()
function
execute(query, values)
executemany(query, values)
– Using rowcount attribute of cursor class we can show number of
rows inserted.
– Using lastrowid attribute of cursor class we can show id of last
inserted record.
Python – MySQL Insert Cntd…
• Example :-
Python – MySQL Select
• Select Operation :-
– Execute the query using execute() function to insert a single
record.
execute(query, values)
– Use fetchone() or fetchall() functions to retrieve data from the
cursor.
– Using rowcount attribute of cursor class we can count the number
of records fetched from the database.
– Use loop to fetch and print the data.
– Data will be in list of tuple and in order we retrieved the data from
the database.
Python – MySQL Select Cntd…
• Example :-
Python GUI - Tkinter
• Tkinter  Tk interface, written by Fredrik Lundh
• Tkinter is the easiest way to get started with GUI.
• Tkinter offers native look and feel on all platforms.
• Steps to develop GUI using Tkinter :-
– Import the Tkinter module.
– Create the main application window.
– Add the widgets like labels, buttons, frames, etc. to the window.
– Call the main event loop so that the actions can take place.
• To import Tkinter module :-
import tkinter
from tkinter import *
Hello Tkinter

• from tkinter import * imports the Tkinter module in our current file.
• root=Tk() initializes the root widget (window).
• l=Label(root,text=“Hello World!”) creates a label widget as child to
the root window with text specified. It can displays text, icon and
image.
• l.pack() is a layout manager and is used to place the widget in the
root window. It fits the given text in the widget and make its size
according to the text.
• root.mainloop() used to enter in the Tkinter event loop.
Tkinter Classes
• Widget classes :- Widget Description
Button Simple button, used to execute commands.
Canvas Used to draw structured custom graphics.
Checkbutton Used to create selection list using checkbox.
Entry A text entry field.
Frame Container for grouping widgets.
Label Displays a text, icon and a image.
Listbox Displays a list of alternatives.
Menu Implement pulldown and popup menus.
Menubutton Implement pulldown menus.
Message Displays the text similar to the label widget.
Radiobutton Just like Checkbutton but represent only one value.
Scale Allows us to set value by dragging a slider.
Scrollbar Add scrolling in canvas, entry, list and text widgets.
Text Formatted text display with advance functionality.
Toplevel Container displayed as a separate top level window.
Tkinter Layout Managers
• They can be used to place various widgets in the top level window
and control their layout.

Manager Description
Grid Used to create table like layout. grid() method is used to create the grid.
Pack Used to pack widgets in parent window. pack() method is used.
• Syntax
Place :- Let us to place widget in a given position. place() method is used.
widget.pack(side=[LEFT,RIGHT,TOP,BOTTOM])
widget.grid(row,column,columnspan,rowspan,ipadx,ipady,padx,
pady,sticky=[N,E,W,S,NE,NW,NS,EW,ES])
widget.place(x,y,relx,rely,relheight,relwidth, anchor=
[N,E,W,S,NE,NW,NS,EW,ES])
Tkinter Layout Managers – pack()
• side specify side of the parent window to which the widget is to be
placed on the window.
Tkinter Layout Managers – grid()
• column and row specify column and row number in which widget is
to be placed. Leftmost column or row is represented by 0.
• rowspan and columnspan specify expansion of the widget.
• ipadx and ipady specify no. of pixels to pad inside widget’s border.
• padx and pady specify no. of pixels to pad outside widget’s border.
• sticky specify position in any direction inside the cell.
Tkinter Layout Managers – place()
• anchor specify exact direction of the widget within the container.
• height, width specify height and width in pixels.
• relheight, relwidth specify fraction of parent’s height and width (0.0 -
1.0) (rel indicates relative to parent).
• relx, rely specify offset in horizontal and vertical direction (0.0 - 1.0).
• X, y specify horizontal and vertical offset in pixels.
Tkinter - Button
• Button(parent,options) used to create a button.
Option Description

activebackground Background color of button when mouse hover the button.

activeforeground Foreground (font) color of button when mouse hover the button.

bd Border of width in pixels.

bg Background color of button.

fg Foreground color of button.

command Set to function call on a click event on the button.

font Font of the button text.

height Height of button in number of text lines.

highlightcolor Color of highlight when the button has the focus.

image Set to the image displayed on the button.


Tkinter – Button Cntd…
• Options continued…

Option Description

justify Way by which multiple text lines are represented. (LEFT, RIGHT, CENTER)

padx Padding to the button in the horizontal direction.

pady Padding to the button in the vertical direction.

relief Type of the border. (SUNKEN, RAISED, GROOVE, RIDGE)

state Set button to responsive or not. (DISABLED, ACTIVE)

underline Make button text underlined.

width Width of the button in number of letters for text or pixels for image.

wraplength If set to positive number, text lines will be wrapped to fit the length.
Tkinter – Button Cntd…
• Example :-
Tkinter - Checkbutton
• Used to track user’s choice.
• Checkbutton(parent,options) used to create a checkbutton.
Option Description

activebackground Background color of button when mouse hover the CB.

activeforeground Foreground (font) color of button when mouse hover the CB.

bd Border of width in pixels.

bg Background color of CB.

fg Foreground color of CB.

command Set to function call on a click event on the CB.

font Font of the CB text.

height Height of CB in number of text lines.

highlightcolor Color of highlight when the CB has the focus.

image Set to the image displayed on the CB.


Tkinter – Checkbutton Cntd…
• Options continued…
Option Description
justify Way by which multiple text lines are represented. (LEFT, RIGHT, CENTER)
padx Padding to the CB in the horizontal direction.
pady Padding to the CB in the vertical direction.
relief Type of the border. (SUNKEN, RAISED, GROOVE, RIDGE)
state Set CB to responsive or not. (DISABLED, ACTIVE)
underline Make CB text underlined.
width Width of the CB in number of letters for text or pixels for image.
wraplength If set to positive number, text lines will be wrapped to fit the length.
offvalue Value of the variable when the CB is unchecked.
onvalue Value of the variable when the CB is checked.
selectimage Image shown in the CB when it is set.
variable Represents associated value that tracks the state of the CB.
selectcolor Color of the CB when it is set. Default is red.
Tkinter – Checkbutton Cntd…
• Example :-
Tkinter - Entry
• Used to provide single line text box to accept a value from the user.
• Entry(parent,options) used to create a entry field.
Option Description

bg It represents the color of the background.

bd It represents the border of the entry field.

fg It represents the color of the text.

font It represents the font type of the text.

insertbackground Color to use for the cursor.

selectbackground The background color of the selected text.

selectforeground The font color of the selected text.

show Used to show the entry text of some other type ex:- * for password.

textvariable It is set to the instance of StringVar to retrieve the text from the entry.

width The width of the displayed text or image.


Tkinter – Entry Cntd…
• Entry field methods :-
Method Description

delete(first,last=None) Used to delete the specified characters from the field.

get() Used to get the text from the field.

insert(index,s) Used to insert the specified string before the character at index.
• Example :-
Tkinter - Frame
• Used to organize the group of widgets.
• Act like container, can hold other widgets.
• Frame(parent,options) used to create a frame.

Option Description

bg It represents the color of the background.

bd It represents the border width of the frame.

height It represents height of the frame.

highlightcolor Text color when the widget is under focus.

width It represents width of the frame.


Tkinter – Frame Cntd…
• Example :-
Tkinter - Label
• Used to specify container box where we can place text and images.
• Label(parent,options) used to create a label.
Option Description

bg It represents the color of the background.

bd It represents the border width. Default is 2 pixels.

font The font of the text written inside the label.

fg The foreground color of the text written inside the widget.

height The height of the widget.

image The image that is to be shown as the label.

padx The horizontal padding of the text.

pady The vertical padding of the text.

text String to be shown as the label text.


Tkinter – Label Contd…
Option Description

textvariable It is set to the instance of StringVar to acsess the text from the label.

width The width of the widget.

label.config(text=) Method to set the attributes of any widget dynamically.


Tkinter - Listbox
• Used to display the list of items to the user. All text items in the
Listbox contain the same font and color.
• Listbox (parent,options) used to create a listbox.
Option Description

bg It represents the color of the background.

bd It represents the border width. Default is 2 pixels.

font The font of the text written inside the listbox.

fg The foreground color of the text written inside the widget.

height The height of the widget.

width The width of the widget.

highlightcolor The color of the Listbox items when the widget is under focus.

highlightthickness The thickness of the highlight.

selectbackground The background color that is used to display the selected text.
Tkinter – Listbox Contd…
Option Description

selectmode BROWSE, SINGLE, MULTIPLE, EXTENDED.

xscrollcommand It is used to let the user scroll the Listbox horizontally.

yscrollcommand It is used to let the user scroll the Listbox vertically.

curselection() Used to get indices of the selected items.

delete() Used to delete the selected item. Delete one by one as index
decreases after deletion of each item.
get() Used to get all selected the values from the list.

insert(I,*elements) Used to inset new values in the listbox at index i.

highlightthickness The thickness of the highlight.

selectbackground The background color that is used to display the selected text.
Tkinter – Listbox Contd…
• Example :-
Tkinter - Menu
• Used to create various types of menus.
• Menu (parent,options) used to create a Menu.
Option Description

activebackground It represents the color of the background when widget is under focus.

bg It represents the color of the background .

bd It represents the size of the border. Default is 2 pixels.

activeforeground The foreground color of the text written inside the widget under focus.

height The height of the widget.

width The width of the widget.

fg It represents the color of the foreground.

image The image displayed on the widget.

font The font of the widget.


Tkinter – Menu Contd…
Option Description

title Title of the window.

addcommand() Method to add commands to menu addcommand(label, command).

addcascade() Method to create hierarchichal menu addcascade(label, menu)

add_separator() Method to add the separator line to the menu.

Note:- Menu is top level component so we can’t use layout manager


to place the component in the window.

Use following syntax:-

root.config(menu=menubar)

Here, menubar is menu object.


Tkinter – Menu Contd…
• Example :-
Tkinter - Radiobutton
• Used to implement one-of-many selection.
• Radiobutton(parent,options) used to create a Radiobutton.
Option Description

activebackground Background color of button when mouse hover the RB.

activeforeground Foreground (font) color of button when mouse hover the RB.

borderwidth Border of width in pixels.

bg Background color of RB.

fg Foreground color of RB.

command Set to function call on a click event on the RB.

font Font of the RB text.

height Height of RB in number of text lines.

highlightcolor Color of highlight when the RB has the focus.

image Set to the image displayed on the RB.


Tkinter – Radiobutton Cntd…
• Options continued…
Option Description
justify Way by which multiple text lines are represented. (LEFT, RIGHT, CENTER)
padx Padding to the RB in the horizontal direction.
pady Padding to the RB in the vertical direction.
text Text to be displayed on the RB.
state Set RB to responsive or not. (DISABLED, ACTIVE)
underline Make RB text underlined.
width Width of the RB in number of letters for text or pixels for image.
wraplength If set to positive number, text lines will be wrapped to fit the length.
value Value of the RB.
variable Represents associated value that tracks the state of the RB.
selectcolor Color of the RB when it is set. Default is red.
get() Get the value from the RB.
Tkinter – Radiobutton Cntd…
• Example :-
Tkinter - Scale
• Used to implement graphical slider to slide over a range of values.
• Scale(parent,options) used to create a Scale.
Option Description

activebackground Background color of button when mouse hover the widget.

digits Used to specify no. of digits.

bd Border of width in pixels.

bg Background color of widget.

fg Foreground color of widget.

from_ Used to represent one end of the widget range.

font Font of the RB text.

label Set to some text which can be shown as a label with the scale.

length Represent length of the widget.

orient Orientation (HORIZONTAL or VERTICAL)


Tkinter – Scale Cntd…
• Options continued…
Option Description
resolution Set to smallest change which is to be made to the scale value.
showvalue The value of the scale is shown in the text form by default.
sliderlength Length of the slider window along the length of the scale. Default 30px.
tickinterval The scale values are displayed on the multiple of the specified tick interval. Default is 0.

variable It represents the control variable for the scale.


width It represents the width of the through part of the widget.
set(value) It is used to set the value of the scale.
get() It is used to get the current value of the scale.
Tkinter – Scale Cntd…
• Example :-
Tkinter - Scrollbar
• Used to scroll down the content of the other widgets.
• Scrollbar(parent,options) used to create a Scale.

Option Description

activebackground Background color of button when mouse hover the widget.

command Procedure to be called each time when the scrollbar is moved.

bd Border of width in pixels.

bg Background color of widget.

orient Orientation (HORIZONTAL or VERTICAL)

width It represents the width of the scrollbar.


Tkinter – Scrollbar Cntd…
• Example :-
Tkinter - messagebox
• Used to display the message boxes.
• messagebox.function_name(title, message [, options]) .

Option Description

showinfo() Show some relevant information to the user.

showwarning() Display the warning to the user.

showerror() Display the error message to the user.

askquestion() Ask some question to user which can be answered in yes or no.

askokcancel() Used to confirm the user's action in some application activity.

askyesno() Ask about some action to which, the user can answer in yes or no.

askretrycancel() Ask the user about doing a particular task again or not.
Tkinter –messagebox Cntd…
• Example :-

You might also like