Python Complete Course Material
Python Complete Course Material
Introduction to Python...................................................................................................... 8
Installing Python: ..................................................................................................................... 8
Step 1: Download the Python 3 Installer ................................................................................... 8
Step 2: Run the Installer ........................................................................................................... 8
Features of Python: .................................................................................................................. 9
Python- Easy to Learn and Use .................................................................................................................. 9
Python - Expressive Language ................................................................................................................... 9
Python - Interpreted Language.................................................................................................................. 9
Python - Cross-platform Language ............................................................................................................ 9
Python - Free and Open Source ............................................................................................................... 10
Python - Large Standard Library .............................................................................................................. 10
Python - Extensible .................................................................................................................................. 10
Python -GUI Programming Support ......................................................................................................... 10
Python - Object-Oriented Language ........................................................................................................ 10
Python - Dynamically Typed .................................................................................................................... 10
Lists ....................................................................................................................................... 67
Creating a List .......................................................................................................................................... 67
Adding Elements to a List ........................................................................................................................ 68
Accessing elements from the List ............................................................................................................ 70
Removing Elements from the List ............................................................................................................ 71
Slicing of a List ......................................................................................................................................... 73
Basic List Operations ............................................................................................................................... 74
Built-in List Functions and Methods ........................................................................................................ 75
List len( ) method ................................................................................................................................ 75
List max( ) method .............................................................................................................................. 75
List min( ) method ............................................................................................................................... 76
List list( ) method ................................................................................................................................ 76
List append( ) method ......................................................................................................................... 77
List count( ) method ............................................................................................................................ 77
List extend ( ) method ......................................................................................................................... 78
List index ( ) method............................................................................................................................ 78
List insert ( ) method ........................................................................................................................... 79
List pop( ) method ............................................................................................................................... 79
List remove ( ) method ........................................................................................................................ 80
List reverse ( ) method ........................................................................................................................ 80
List sort ( ) method .............................................................................................................................. 81
Tuples .................................................................................................................................... 82
Creating a Tuple ....................................................................................................................................... 82
Concatenation of Tuples .......................................................................................................................... 83
Slicing of Tuple......................................................................................................................................... 84
Deleting a Tuple ....................................................................................................................................... 85
Built-in tuple Methods ............................................................................................................................. 86
Tuple len( ) method ............................................................................................................................. 86
Tuple max( ) method ........................................................................................................................... 86
Tuple min( ) method ........................................................................................................................... 87
Tuple tuple( ) method ......................................................................................................................... 87
Dictionary .............................................................................................................................. 88
Creating a Dictionary ............................................................................................................................... 88
Adding Elements to a Dictionary ............................................................................................................. 89
Accessing elements from a Dictionary .................................................................................................... 90
Removing Elements from Dictionary ....................................................................................................... 91
Properties of Dictionary Keys .................................................................................................................. 92
Built-in Dictionary Functions & Methods ................................................................................................ 93
Dictionary len() Method ...................................................................................................................... 93
Dictionary str() Method....................................................................................................................... 93
Dictionary copy() Method ................................................................................................................... 94
Dictionary get() Method ...................................................................................................................... 94
Dictionary items() Method .................................................................................................................. 95
Dictionary keys() Method .................................................................................................................... 95
Dictionary update() Method ............................................................................................................... 96
Dictionary values() Method................................................................................................................. 96
Introduction to Python
Installing Python:
Then just click Install Now. That should be all there is to it. A few minutes later you should
have a working Python 3 installation on your system.
Features of Python:
By interpretation we mean that the source code is executed line by line, and not all at once.
take a code and run it on any machine, it is not necessary to write a different code for different
machines. This makes Python a portable language.
Python - Extensible
We can write some of our Python codes in other languages such as C, C ++. This makes
Python an extensible language, which means, it can be extended to other languages.
print(“Hello Python”)
Hello Python
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python
is a case sensitive programming language. Thus, Newhorizon and newhorizon are two
different identifiers in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strong private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language defined
special name.
These are reserved words and you cannot use them as constants or variables or any other
identifier names. All the Python keywords contain lowercase letters only.
Indentation:
# Python program showing indentation
Multi-Line Statements:
Statements in Python typically end with a new line. Python, however, allows the use of the line
continuation character (\) to denote that the line should continue.
For example:
total = a + \
b+\
c
The statements contained within the [], {}, or () brackets do not need to use the line continuation
character.
For example:
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long
as the same type of quote starts and ends the string. The triple quotes are used to span the string
across multiple lines.
For example, all the following are legal:
word = 'word'
Comments in Python
To write a comment in Python, simply put the hash mark # before your desired comment:
# This is a comment
Because comments do not execute, when you run a program you will not see any indication of
the comment there. Comments are in the source code for humans to read, not for computers to
execute.
[Link]
# Print “Hello, World!” to console
print("Hello, World!")
# So you can't
just do this
in python
In the above example, the first line will be ignored by the program, but the other lines will
raise a Syntax Error.
Another thing you can do is use multiline strings by wrapping your comment inside a set of
triple quotes:
"""
If I really hate pressing `enter` and
typing all those hash marks, I could
just do this instead
"""
This is like multiline comments in Java, where everything enclosed in the triple quotes will
function as a comment.
a = 5; b = 6; print(a); print(b)
36
96.9
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example-
Here, one integer object, one floating object with values 36 and 96.9 are assigned to the
variables regNo and avg_marks respectively, and one string object with the value "john" is
assigned to the variable name.
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value
to them.
For example:
a=1
b=2
c=3
You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is –
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement.
For example:
del var
del var_a, var_b
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows either pair of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string
and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays
in C. One of the differences between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator.
For example:
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.
The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot
be updated. Tuples can be thought of as read-only lists.
For example:
The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists :
Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
For example:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.
Functions Description
float(x) Converts x to a floating-point number
str(x) Converts object x to a string representation.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
hex(x) Converts an integer to a hexadecimal string.
The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.
In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.
Let's see an example where Python promotes conversion of lower datatype (integer) to higher
data type (float) to avoid data loss.
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Let's see another example where Python Addition of string(higher) data type and integer(lower)
datatype
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)
In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.
This type conversion is also called typecasting because the user casts (change) the data type of
the objects.
Syntax :
(required_datatype)(expression)
Let's see an example where Python Addition of string and integer using explicit conversion.
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
Example:
These operators compare the values on either side of them and decide the relation among
Example:
if ( a != b ):
else:
if ( a < b ):
else:
print ("Line 3 - a is not less than b") Line 3 - a is not less than b
if ( a > b ):
if ( a <= b ): Output:
print ("Line 5 - a is either less than or equal to b")
if ( b >= a ):
else:
print ("Line 6 - b is neither greater than nor equal to b") Line 6 - b is either greater than
or equal to b
c %= a
Bitwise operator works on bits and performs bit-by-bit operation. Pyhton's built-in function bin() can
be used to obtain binary representation of an integer number.
Example:
c = a | b; # 61 = 0011 1101
c = a ^ b; # 49 = 0011 0001
-0b111101
c = a << 2; # 240 = 1111 0000
print ("result of LEFT SHIFT is ", c,':',bin(c)) result of LEFT SHIFT is 240 :
0b11110000
Python’s membership operators test for membership in a sequence, such as strings, lists,
or tuples.
Example:
a = 10;b = 20 Output:
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list") Line 1 - a is not available in the
given list
else:
if ( b not in list ):
Example:
Output:
a = 20;b = 20;
Line 1 a= 20 : 1594701888 b= 20 :
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b)) 1594701888
if ( a is b ):
print ("Line 2 - a and b have same identity") Line 2 - a and b have same identity
else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else: Line 3 - a and b have same identity
The following table lists all the operators from highest precedence to the lowest.
Example: Output:
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d )) a:20 b:10 c:15 d:5
e = (a + b) * c / d #( 30 * 15 ) / 5
e = ((a + b) * c) / d # (30 * 15 ) / 5
e = a + (b * c) / d # 20 + (150/5)
Value of a + (b * c) / d is 50.0
print ("Value of a + (b * c) / d is ", e)
IF Statement:
The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the data is compared and a decision is made based on the result of the
comparison.
Syntax:
Example:
Let’s try a guess-a-number program. The computer picks a random number, the player tries to
guess, and the program tells them if they are correct. To see if the player’s guess is correct,
we need something new, called an if statement.
IF…ELSE Statements
An else statement can be combined with an if statement. An else statement contains a block
of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.
Syntax:
if expression:
statement(s)
else:
statement(s)
The guess-a-number game works, but it is pretty simple. If the player guesses wrong,
nothing happens. We can add else to the if statement as follows:
Example : Guessing a num:
Elif statement:
The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.
Syntax: Example:
Nested IF Statements
There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested if construct. In a nested if
construct, you can have an if...elif...else construct inside another if...elif...else construct.
Syntax: Example:
if expression1: if num%2==0:
statement(s) if num%3==0:
if expression2: print ("Divisible by 3 and 2")
statement(s) else:
elif expression3: print ("divisible by 2 not divisible by 3")
statement(s) else:
else: if num%3==0:
statement(s) print ("divisible by 3 not divisible by 2")
elif expression4: else:
statement(s) print ("not Divisible by 2 not divisible by 3")
else:
statement(s)
Loops in Python
for Loop :
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax:
Example:
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
The sum is 48
# iterate over the list
for val in numbers:
sum = sum+val
# Program to illustrate
Output:
#Iterating over a list
print("List Iteration")
l = ["New", "Horizon", "BCA"] List Iteration
for i in l: New
Horizon
print(i) BCA
--------------------------------------------------------------- ---
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("New", "Horizon", "BCA") Tuple Iteration
for i in t:
New
print(i) Horizon
BCA
---------------------------------------------------------------
# Iterating over a String
print("\nString Iteration")
s = "BCA"
String Iteration
for i in s :
B
print(i) C
# Iterating over dictionary A
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i])) Dictionary Iteration
abc 345
xyz 123
else:
print ("Inside Else Block")
print(i)
# Going backwards 0
for i in range(0, -10, -2): -2
-4
print(i) -6
-8
while Loop :
Syntax:
while expression:
statement(s)
Example:
if condition:
# execute these statements
else:
# execute these statements
while condition:
# execute these statements
else:
# execute these statements
Combining else with while
else:
print("In Else Block")
In Example : Guess a num we wrote a program that played a simple random number guessing
game. The problem with that program is that the player only gets one guess.
We can, in a sense, replace the if statement in that program with a while loop to create a
program that allows the user to keep guessing until they get it right.
Nested Loops:
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax :
Infinite loops:
When working with while loops, sooner or later will accidentally send Python into a never
ending loop.
Example 1:
i=0
while i<10:
print(i)
Example 2:
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
Example 3:
List_words = ['the', 'end', 'is', 'never']
for word in List_words:
print(word)
List_words.append(word)
Loop Manipulations:
The Loop control statements change the execution from its normal sequence.
break statement:
The break statement is used for premature termination of the current loop. It brings control out of
the current loop. The break statement can be used to break out of a for or while loop before the
loop is finished.
for i in range(10):
if x == "banana":
break
continue statement
The continue statement in Python returns the control to the beginning of the current loop. When
encountered, the loop starts next iteration without executing the remaining statements in the
current iteration. The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues with the next iteration.
continue
print(num)
--------------------------------------------------------------------------------
for x in fruits:
apple
if x == "banana": cherry
continue
print(x)
pass statement
It is used when a statement is required syntactically but you do not want any command or
code to execute. The pass statement is a null operation; nothing happens when it executes.
The pass statement acts as a placeholder and usually used when there is no need of code but
a statement is still required to make a code syntactically correct. For example, we want to
declare a function in our code but we want to implement that function in future, which means
we are not yet ready to write the body of the function. In this case we cannot leave the body
of function empty as this would raise error because it is syntactically incorrect, in such cases
we can use pass statement which does nothing but makes the code syntactically correct.
# An empty loop
for letter in 'New Horion College':
Last Letter : e
pass
print ('Last Letter :', letter )
#If the number is even we are doing nothing and if it is odd then we are
displaying.
for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
11
pass 9
89
else:
print(num)
Strings
A string is a sequence of characters. Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access elements of the string.
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Creating a String
# Python Program for Creation of String
# Creating a String with single Quotes
String1 = 'Welcome to the Python World'
print("String with the use of Single Quotes: ")
print(String1)
print(String1)
# Updating a String
We can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether.
Deletion of entire string is possible with the use of del keyword. Further, if we try to print the
string, this will produce an error because String is deleted and is unavailable to be printed.
While printing Strings with single and double quotes in it causes SyntaxError
because String already contains Single and Double Quotes and hence cannot be
printed with the use of either of these. Hence, to print such a String either Triple
Quotes are used or Escape sequences are used to print such Strings.
Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and same is done for Double Quotes.
To ignore the escape sequences in a String, r or R is used, this implies that the string
is a raw string and escape sequences inside it are to be ignored.
# Python Program for Escape Sequencing in String
# Initial String
Initial String with use of Triple Quotes:
String1 = '''I'm a "Programmer"''' I'm a "Programmer"
print("Initial String with use of Triple Quotes: ")
print(String1)
print(String1)
# Using + and *
str1 + str2 = HelloWorld!
str1 = 'Hello'
str2 ='World!'
# using +
An example that repeatedly asks the user to enter a letter and builds up a string consisting of only
the vowels that the user entered.
The in operator
The in operator is used to tell if a string contains something.
#Using in
string="Hai";
if 'a' in string:
print('Your string contains the letter a.')
Your string contains the letter a.
else:
print('Your string does not contains the letter a.')
#Using not in
You can combine in with the not operator to tell if a string does not contain something:
string="Hello";
if 'e' not in string:
print('Your string does not contains the letter e.')
else: Your string contains the letter e.
print('Your string contains the letter e.')
The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contains curly braces {} as placeholders or replacement
fields which gets replaced.
# default(implicit) order
print(default_order)
print(positional_order)
Strings come with a ton of methods, functions that return information about the string or
return a new string that is a modified version of the original.
String capitalize() Method
It returns a copy of the string with only its first character capitalized.
Syntax:
[Link]()
Example:
str = "this is string example....wow!!!"
print ("[Link]() : ", [Link]())
The count() method returns the number of occurrences of substring sub in the range [start,
end]. Optional arguments start and end are interpreted as in slice notation.
Syntax:
[Link](sub, start= 0,end=len(string))
Parameters
sub - This is the substring to be searched.
start - Search starts from this index. First character starts from 0 index. By default
search starts from 0 index.
end - Search ends from this index. First character starts from 0 index. By default
search ends at the last index.
Example:
str="this is string example....wow!!!"
[Link]('i') : 3
sub='i'
[Link]('exam', 10, 40) : 1
print ("[Link]('i') : ", [Link](sub))
sub='exam'
print ("[Link]('exam', 10, 40) : ", [Link](sub,10,40))
It returns True if the string ends with the specified suffix, otherwise return False optionally
restricting the matching with the given indices start and end.
Syntax:
[Link](suffix[, start[, end]])
Parameters
suffix - This could be a string or could also be a tuple of suffixes to look for.
start - The slice begins from here.
end - The slice ends here.
Return Value
TRUE if the string ends with the specified suffix, otherwise FALSE.
Example:
Str='this is string example....wow!!!'
suffix='!!'
print ([Link](suffix))
True
print ([Link](suffix,20)) True
False
suffix='exam' True
print ([Link](suffix))
print ([Link](suffix, 0, 19))
The index() method determines if the string str occurs in string or in a substring of string, if
the starting index beg and ending index end are given. This method is same as find(), but
raises an exception if sub is not found.
Syntax:
[Link](str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
beg - This is the starting index, by default its 0.
end - This is the ending index, by default its equal to the length of the string.
Return Value
Index if found otherwise raises an exception if str is not found.
Example:
str1 = "this is string example....wow!!!" 15
str2 = "exam"; 15
Traceback (most recent call last):
print ([Link](str2)) File "[Link]", line 5, in <module>
print ([Link](str2, 40))
print ([Link](str2, 10)) ValueError: substring not found
print ([Link](str2, 40))
The find() method determines if the string str occurs in string, or in a substring of string if the
starting index beg and ending index end are given.
Syntax:
[Link](str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
beg - This is the starting index, by default its 0.
end - This is the ending index, by default its equal to the length of the string.
Return Value
Index if found and -1 otherwise.
Example:
str1 = "this is string example....wow!!!"
str2 = "exam"; 15
15
print ([Link](str2))
-1
print ([Link](str2, 10))
print ([Link](str2, 40))
The isalnum() method checks whether the string consists of alphanumeric characters.
Syntax:
str.isa1num()
Parameters
NA.
Return Value
This method returns true if all the characters in the string are alphanumeric and there is at
least one character, false otherwise.
Example:
str = "this2016" # No space in this string
True
print ([Link]()) False
str = "this is string example....wow!!!"
print ([Link]())
Parameters
NA.
Return Value
This method returns true if all the characters in the string are alphabetic and there is at least
one character, false otherwise.
Example:
str = "this"; # No space & digit in this string
True
print ([Link]())
False
str = "this is string example....wow!!!"
print ([Link]())
Parameters
NA.
Return Value
This method returns true if all characters in the string are digits and there is at least one
character, false otherwise.
Example:
str = "123456"; # Only digit in this string
True
print ([Link]())
False
str = "this is string example....wow!!!"
print ([Link]())
Parameters
NA.
Return Value
This method returns true if all cased characters in the string are lowercase and there is at least
one cased character, false otherwise.
Example:
str = "THIS is string example....wow!!!"
False
print ([Link]()) True
Parameters
NA.
Return Value
This method returns true if all characters in the string are numeric, false otherwise.
Example:
str = "this2016"
False
print ([Link]()) True
str = "23443434"
print ([Link]())
Parameters
NA.
Return Value
This method returns true if there are only whitespace characters in the string and there is at
least one character, false otherwise.
Example:
str = " "
print ([Link]()) True
False
str = "This is string example....wow!!!"
print ([Link]())
Parameters
NA.
Return Value
This method returns true if the string is a title cased string and there is at least one character,
for example uppercase characters may only follow uncased characters and lowercase
characters only cased ones. It returns false otherwise.
Example:
str = "This Is String Example...Wow!!!"
print ([Link]()) True
False
str = "This is string example....wow!!!"
print ([Link]())
Return Value
This method returns a string, which is the concatenation of the strings in the sequence seq.
The separator between elements is the string providing this method.
Example:
s = "-"
seq = ("a", "b", "c") # This is sequence of strings. a-b-c
print ([Link]( seq ))
Parameters
NA.
Return Value
This method returns the length of the string.
Example:
str = "Ajith" Length of the string: 5
print ("Length of the string: ", len(str))
str - This is the string from which max alphabetical character needs to be returned.
Return Value
This method returns the max alphabetical character from the string str.
Example:
str = "this is a string example....really!!!"
Max character: y
print ("Max character: " + max(str)) Max character: x
str = "this is a string example....wow!!!"
print ("Max character: " + max(str))
str - This is the string from which min alphabetical character needs to be returned.
Return Value
This method returns the min alphabetical character from the string str.
Example:
str = "[Link]"
Min character: .
print ("Min character: " + min(str))
Min character: H
str = "Hello"
print ("Min character: " + min(str))
Parameters
old - This is old substring to be replaced.
new - This is new substring, which would replace old substring.
max - If this optional argument max is given, only the first count occurrences are
replaced.
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by
new. If the optional argument max is given, only the first count occurrences are replaced.
Example:
str = "this is string example....wow!!! this is really string"
print ([Link]("is", "was"))
print ([Link]("is", "was", 3))
Lists
Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python.
Lists are a useful tool for preserving a sequence of data and further iterating over it.
Creating a List
Lists in Python can be created by just placing the sequence inside the square brackets [ ]. A list may
contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values
can be passed as a sequence at the time of list creation.
List = ['Python']
print("\nList with the use of String: ") List with the use of String:
['Python']
print(List)
List = [1, 2, 'Hello', 4, 'how', 6, 'ru'] List with the use of Mixed Values:
[1, 2, 'Hello', 4, 'how', 6, 'ru']
print("\nList with the use of Mixed Values: ")
print(List)
Note – append() and extend() methods can only add elements at the end.
In order to access the list items refer to the index [Link] the index operator [ ] to access
an item in a [Link] index must be an [Link] list are accessed using nested indexing.
print(List)
# Removing elements from List using iterator method
for i in range(1, 5): List after Removing a range of elements:
[7, 8, 9, 10, 11, 12]
[Link](i)
print("\nList after Removing a range of elements: ")
print(List)
# Removing element at a
# specific location from the
# List using the pop() method
[Link](2) List after popping a specific element:
[7, 8, 10, 11]
print("\nList after popping a specific element: ")
print(List)
Slicing of a List
To print a specific range of elements from the list, we use Slice operation. Slice operation is
performed on Lists with the use of colon(:). To print elements from beginning to a range use
[:Index], to print elements from end use [:-Index], to print elements from specific Index till the
end use [Index:], to print elements within a range, use [Start Index:End Index] and to print
whole List with the use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Note – To print elements of List from rear end, use Negative Indexes.
print(Sliced_List)
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
Example:
Python Expression Result
len([1, 2, 3]) 3
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6]
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!']
3 in [1, 2, 3] True
for x in [1,2,3] : 123
print (x,end=' ')
Parameters
list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
Example:
list1 = ['physics', 'chemistry', 'maths']
3
print (len(list1)) 5
list2 = list(range(5)) #creates list of numbers between 0-4
print (len(list2))
Parameters
list - This is a list from which max valued element are to be returned..
Return Value
This method returns the elements from the list with maximum value.
Example:
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200] Max value element : Python
Max value element : 700
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
Parameters
list - This is a list from which min valued element are to be returned..
Return Value
This method returns the elements from the list with minimum value.
Example:
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200] Max value element : C++
Max value element : 200
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
Parameters
seq - This is a tuple or string to be converted into list.
Return Value
This method returns the list.
Example:
aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)
str="Hello World"
List elements : [123, 'C++', 'Java', 'Python']
list2=list(str)
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
print ("List elements : ", list2)
Parameters
obj - This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list..
Example:
list1 = ['C++', 'Java', 'Python']
[Link]('C#') updated list : ['C++', 'Java', 'Python', 'C#']
Parameters
obj - This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
Example:
aList = [123, 'xyz', 'zara', 'abc', 123];
Count for 123 : 2
print ("Count for 123 : ", [Link](123)) Count for zara : 1
print ("Count for zara : ", [Link]('zara'))
Parameters
seq - This is the list of elements.
Return Value
This method does not return any value but adds the content to an existing list.
Example:
list1 = ['physics', 'chemistry', 'maths']
#creates list of numbers between 0-4
list2=list(range(5))
Extended List : ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]
[Link](list2)
print ('Extended List :',list1)
Parameters
obj - This is the object to be find out.
Return Value
This method returns index of the found object otherwise raises an exception indicating that
the value is not found.
Example:
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', [Link]('chemistry'))
Index of chemistry 1
print ('Index of C++', [Link]('C++'))
Traceback (most recent call last):
File "[Link]", line 3, in <module>
print ('Index of C++', [Link]('C++'))
ValueError: 'C++' is not in list
Parameters
index - This is the Index where the object obj need to be inserted.
obj - This is the Object to be inserted into the given list.
Return Value
This method does not return any value but it inserts the given element at the given index.
Example:
list1 = ['physics', 'chemistry', 'maths']
[Link](1, 'Biology')
Final list : ['physics', 'Biology', 'chemistry', 'maths']
print ('Final list : ', list1)
Parameters
obj - This is an optional parameter, index of the object to be removed from the list.
Return Value
This method returns the removed object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]()
print ("list now : ", list1)
list now : ['physics', 'Biology', 'chemistry']
[Link](1) list now : ['physics', 'chemistry']
print ("list now : ", list1)
Parameters
obj - This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]('Biology')
print ("list now : ", list1)
list now : ['physics', 'chemistry', 'maths']
[Link]('maths') list now : ['physics', 'chemistry']
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]()
list now : ['maths', 'chemistry', 'Biology', 'physics']
print ("list now : ", list1)
Parameters
NA
Return Value
This method does not return any value but reverses the given object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]() list now : ['Biology', 'chemistry', 'maths', 'physics']
print ("list now : ", list1)
Tuples
Tuple is a collection of Python objects much like a list. The sequence of values stored in a
tuple can be of any type, and they are indexed by integers. The important difference between
a list and a tuple is that tuples are immutable.
Creating a Tuple
Tuples are created by placing sequence of values separated by ‘comma’ with or without the
use of parentheses for grouping of data sequence. Tuples can contain any number of elements
and of any datatype (like strings, integers, list, etc.).
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
# Python program to demonstrate creating Tuples
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1)) Tuple using List:
(1, 2, 4, 5, 6)
# Creating a Tuple with the use of loop
Tuple1 = ('Python')
n=5
print("\nTuple with a loop")
Tuple with a loop
for i in range(int(n)): ('Python',)
Tuple1 = (Tuple1,) (('Python',),)
((('Python',),),)
print(Tuple1) (((('Python',),),),)
((((('Python',),),),),)
Tuple1 = tuple('Python')
Tuple with the use of function:
print("\nTuple with the use of function: ") ('P', 'y', 't', 'h', 'o', 'n')
print(Tuple1)
# Creating a Tuple with Mixed Datatypes
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'Programmer')
Tuple3 = (Tuple1, Tuple2)
Tuple with nested tuples:
print("\nTuple with nested tuples: ") ((0, 1, 2, 3), ('python', 'Programmer'))
print(Tuple3)
# Creating a Tuple with repetition
Tuple1 = ('Python',) * 3
print("\nTuple with repetition: ") Tuple with repetition:
('Python', 'Python', 'Python')
print(Tuple1)
Concatenation of Tuples
Concatenation of tuple is the process of joining of two or more Tuples. Concatenation is done
using ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple.
Other arithmetic operations do not apply on Tuples.
Note- Only same datatypes can be combined with concatenation, an error arises if a list and a
tuple are combined.
Tuple 1 Tuple 2
1 2 3 4
Hello World !!!
Concatenated Tuple 3
1 2 3 4 Hello World !!!
# Concatenaton of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Hello', 'World','!!!')
Tuple2:
# Printing Second Tuple
('Hello', 'World', '!!!')
print("\nTuple2: ")
print(Tuple2)
Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple.
Note- Negative Increment values can also be used to reverse the sequence of Tuples
# Slicing of a Tuple
Tuple1 = tuple('HELLO WORLD')
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple gets
deleted by the use of del() method.
Note- Printing of Tuple after deletion results to an Error.
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4) (0, 1, 2, 3, 4)
After Deletion
print(Tuple1) Traceback (most recent call last):
File "[Link]", line 5, in <module>
del Tuple1 print(Tuple1)
print("After Deletion") NameError: name 'Tuple1' is not defined
print(Tuple1)
Parameters
tuple - This is a tuple for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the tuple.
Example:
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
First tuple length : 3
print ("First tuple length : ", len(tuple1))
Second tuple length : 2
print ("Second tuple length : ", len(tuple2))
Parameters
tuple - This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value..
Example:
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1)) Max value element : phy
Max value element : 700
print ("Max value element : ", max(tuple2))
Parameters
tuple - This is a tuple from which min valued element is to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example:
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", min (tuple1)) Max value element : bio
Max value element : 200
print ("Max value element : ", min (tuple2))
Parameters
seq - This is a tuple to be converted into tuple
Return Value
This method returns the tuple
Example:
list1= ['maths', 'che', 'phy', 'bio']
print(list1)
print(type(list1))
['maths', 'che', 'phy', 'bio']
tuple1=tuple(list1) <class 'list'>
<class 'tuple'>
print(type(tuple1)) tuple elements : ('maths', 'che',
'phy', 'bio')
print ("tuple elements : ", tuple1)
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
‘comma’.
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers
and tuples, but the key-values can be repeated and be of any type.
Creating a Dictionary
Dictionary can be created by placing sequence of elements within curly {} braces, separated
by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding
pair element being its Key:value. Values in a dictionary can be of any datatype and can be
duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.
# Creating an empty Dictionary
Dict = {}
Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Apple', 2: 'Bat', 3: 'Cat'}
Dictionary with the use of Integer Keys:
print("\nDictionary with the use of Integer Keys: ") {1: 'Apple', 2: 'Bat', 3: 'Cat'}
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Ajith', 1: [1, 2, 3, 4]} Dictionary with the use of Mixed Keys:
print("\nDictionary with the use of Mixed Keys: ") {'Name': 'Ajith', 1: [1, 2, 3, 4]}
print(Dict)
# Creating a Dictionary
# with dict() method Dictionary with the use of dict():
Dict = dict({1: 'Apple', 2: 'Bat', 3:'Cat'}) {1: 'Apple', 2: 'Bat', 3: 'Cat'}
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Apple'), (2, 'Bat')])
print("\nDictionary with each item as a pair: ") Dictionary with each item as a pair:
{1: 'Apple', 2: 'Bat'}
print(Dict)
Addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing
value in a Dictionary can be done by using the built-in update()method.
Note- While adding a value, if the key value already exists, the value gets updated otherwise
a new Key with the value is added to the Dictionary.
In order to access the items of a dictionary refer to its key [Link] can be used inside
square [Link] is also a method called get() that will also help in acessing the element
from a dictionary.
# Python program to demonstrate accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Hello', 'name': 'For', 3: 'Python'}
In Python Dictionary, deletion of keys can be done by using the del keyword. Using del
keyword, specific values from a dictionary as well as whole dictionary can be deleted. Other
functions like pop() and popitem()can also be used for deleting specific values and arbitrary
values from a Dictionary. All the items from a dictionary can be deleted at once by
using clear()method. Items in a Nested dictionary can also be deleted by using del keyword
and providing specific nested key and particular key to be deleted from that nested Dictionary.
Note- del Dict will delete the entire dictionary and hence printing it after deletion will raise
an Error.
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Python',
'A' : {1 : 'Hello', 2 : 'World', 3 : 'Program'},
'B' : {1 : 'Hello', 2 : 'Students'}}
print("Initial Dictionary: ") Initial Dictionary:
{'B': {1: 'Hello', 2: 'Students'}, 'A': {1: 'Hello', 2:
print(Dict) 'World', 3: 'Program'}, 5: 'Welcome', 6: 'To', 7:
'Python'}
# Deleting a Key
Popping specific element:
# using pop() {'B': {1: 'Hello', 2: 'Students'}, 'A': {1: 'Hello',
3: 'Program'}, 7: 'Python'}
[Link](5)
print("\nPopping specific element: ")
print(Dict)
[Link]()
print("\nPops an arbitrary key-value pair: ")
print(Dict)
print(Dict)
Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys. There are
two important points to remember about dictionary keys-
1. More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins.
For example-
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
dict['Name']: Manni
2. Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
For example-
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
When the above code is executed, it produces the following result:
Parameters
dict - This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example:
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Length : 3
print ("Length : %d" % len (dict))
Parameters
dict - This is the dictionary.
Return Value
This method returns string representation.
Example:
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Equivalent String : {'Age': 7, 'Name': 'Manni', 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))
Parameters
NA
Return Value
This method returns a copy of the dictionary..
Example:
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = [Link]() New Dictionary : {'Age': 7, 'Class': 'First', 'Name': 'Manni'}
print ("New Dictionary : ",dict2)
Parameters
key - This is the Key to be searched in the dictionary.
default - This is the Value to be returned in case key does not exist
Return Value
This method returns a value for the given key. If the key is not available, then returns default
value as None.
Example:
dict = {'Name': 'Zara', 'Age': 27}
Value : 27
print ("Value : %s" % [Link]('Age')) Value : NA
print ("Value : %s" % [Link]('Gender', "NA"))
Parameters
NA
Return Value
This method returns a list of tuple pairs.
Example:
dict = {'Name': 'Zara', 'Age': 7} Value : dict_items([('Name', 'Zara'), ('Age', 7)])
print ("Value : %s" % [Link]()))
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example:
dict = {'Name': 'Zara', 'Age': 7} Value : dict_keys(['Name', 'Age'])
print ("Value : %s" % dict. keys())
Syntax:
[Link](dict2)
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example:
dict = {'Name': 'Zara', 'Age': 7}
Parameters
NA
Return Value
This method returns a list of all the values available in a given dictionary.
Example:
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
Python has a module named datetime to work with dates and times.
print(date_object)
In the Eg2 , we have used today() method defined in the date class to get a date object
containing the current local date.
[Link]
A time object instantiated from the time class represents the local time.
Example 6: Time object to represent time
a = time()
print("a =", a)
print("b =", b)
print("d =", d)
Note: we haven't passed microsecond argument. Hence, its default value 0 is printed.
[Link]
The datetime module has a class named dateclass that can contain information from
both date and time objects.
Example 8: Python datetime object
from datetime import datetime
#datetime(year, month, day)
2018-11-28 00:00:00
a = datetime(2018, 11, 28)
2017-11-28 23:55:59.342380
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)
The first three arguments year, month and day in the datetime() constructor are mandatory.
[Link]
A timedelta object represents the difference between two dates or times.
Example 10-: Difference between two dates and times
from datetime import datetime, date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t6 = t4 - t5 t3 = 201 days, 0:00:00
print("t6 =", t6) t6 = -333 days, 1:14:20
type of t3 = <class '[Link]'>
print("type of t3 =", type(t3)) type of t6 = <class '[Link]'>
Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more
format codes and returns a formatted string based on it.
Functions
A function is a set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and again for different inputs, we can
call the function.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
The Python interpreter has many functions that are always available for use. These functions
are called built-in functions. For example, print() function prints the given object to the
standard output device (screen).
Python abs()
The abs() method returns the absolute value of the given number. If the number is a complex
number, abs() returns its magnitude.
#random integer number
num1 = -20
print('Absolute value of -20 is:', abs(integer))
Python input()
The input() method reads a line from input, converts into a string and returns it.
# get input from user
inputString = input('Enter a string:')
print('The inputted string is:', inputString)
if choice == '1':
print(number_1, "+", number_2, "=",
(number_1 + number_2))
Python len()
The len() function returns the number of items (length) in an object.
testList = [1, 2, 3]
[1, 2, 3] length is 3
print(testList, 'length is', len(testList))
testTuple = (1, 2, 3)
(1, 2, 3) length is 3
print(testTuple, 'length is', len(testTuple))
Python pow()
The pow() method returns x to the power of y. If the third argument (z) is given, it returns x
to the power of y modulus z, i.e. pow(x, y) % z.
# positive x, positive y (x**y)
4
print(pow(2, 2))
4
# negative x, positive y
print(pow(-2, 2))
# negative x, negative y
print(pow(-2, -2)) 0.25
Functions that we define ourselves to do certain specific task are referred as user-defined
functions.
Function definition
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Example of a function:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
Docstring
The first string after the function header is called the docstring and is short for documentation
string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice.
In the above example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines.
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2)) 2
4
print(absolute_value(-4))
def my_func():
x = 10
print("Value inside function:",x)
Function Arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
To call the function square( ), user need to pass one argument, else it gives a syntax error as
follows:-
# Function definition is here
def square(x):
y = x ** 2
return y
result = square( )
print(result)
Keyword Argument
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
# Function definition is here
def square(x):
y = x ** 2
return y
result = square(x = 5 )
print(result)
Default Arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
# Function definition is here
def square(x=3):
y = x ** 2
return y
PYTHON AJITH KUMAR J(BANGALORE)
111
PYTHON
Variable-length Arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments.
In Python, the single-asterisk form of *args can be used as a parameter to send a non-
keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is
the important element here.
Example 1: Example 2: Error as the number of arguments are more while calling
def multiply(x, y): def multiply(x, y):
print (x * y) print (x * y)
multiply(5, 4) multiply(5, 4, 3)
Output: Output:
20 TypeError: multiply() takes 2 positional arguments but 3 were give
Example 3: Solution
def multiply(*args):
z=1
for num in args:
z *= num
print(z)
multiply(4, 5)
20
multiply(10, 9) 90
24
multiply(2, 3, 4)
900
multiply(3, 5, 10, 6)
Modules
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use.
Consider a module to be the same as a code library. A file containing a set of functions you
want to include in your application.
Python modules are .py files that consist of Python code. Any Python file can be referenced
as a module.
Create a Module
To create a module just save the code you want in a file with the file extension .py
Example: [Link]
def mul(x, y):
print (x * y)
Use of Module
Now we can use the module we just created, by using the import statement:
Example:
import Multiplication
[Link](3,6)
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example:
import Multiplication as Mu
[Link](3,9)
Built – in Modules
There are several built-in modules in Python, which you can import depending on the
requirement.
Example: Import and use the platform module
import platform
x = [Link]()
Windows
print(x) # help('modules')
Packages
We don't usually store all our files in our computer in the same location. We use a well-
organized hierarchy of directories for easier access
Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.
Similar, as a directory can contain sub-directories and files, a Python package can have sub-
packages and modules.
A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.
We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as follows
import [Link]
Now if this module contains a function named select_difficulty(), we must use the full name
to reference it.
[Link].select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as
follows.
from [Link] import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
from [Link] import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Files
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
f = open("[Link]") # open file in current directory
f = open("C:/Python33/[Link]") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to
read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text
mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing
with non-text files like image or exe files.
Mode Description
Open a file for writing. Creates a new file if it does not exist or truncates the file
'w' if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
Open for appending at the end of the file without truncating it. Creates a new file
'a' if it does not exist.
Example:
f = open("[Link]") # equivalent to 'r' or 'rt'
f = open("[Link]",'w') # write in text mode
f = open("[Link]",'r+b') # read and write in binary mode
Note: When working with files in text mode, it is highly recommended to specify the encoding
type.
Closing a file
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("[Link]",encoding = 'utf-8')
# perform file operations
[Link]()
This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
f = open("[Link]",encoding = 'utf-8')
# perform file operations
finally:
[Link]()
This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when
the block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
The method writelines() writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.
f = open("[Link]",'r+',encoding = 'utf-8')
print ("Name of the file: ", [Link])
seq = ["This is 4th line\n", "This is 5th line"]
# Write sequence of lines at the end of the file.
[Link](0, 2)
line = [Link]( seq )
We can read a file line-by-line using a for loop. This is both efficient and fast.
f = open("[Link]",'r',encoding = 'utf-8')
for line in f:
print(line, end = '')
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these
reading method return empty values when end of file (EOF) is reached.
Example:
f = open("[Link]",'r',encoding = 'utf-8')
print([Link]())
Directory in Python
If there are many files to handle in your Python program, you can arrange your code within
different directories to make things more manageable.
A directory or folder is a collection of files and sub directories. Python has the os module,
which provides us with many useful methods to work with directories (and files as well).
Changing Directory
We can change the current working directory using the chdir() method.
The new path that we want to change to must be supplied as a string to this method. We can
use both forward slash (/) or the backward slash (\) to separate path elements.
It is safer to use escape sequence when using the backward slash.
[Link]('C:\\Python33')
print([Link]())
All files and sub directories inside a directory can be known using the listdir() method.
This method takes in a path and returns a list of sub directories and files in that path. If no
path is specified, it returns from the current working directory.
import os
print([Link]())
In order to remove a non-empty directory we can use the rmtree() method inside
the shutil module.
import os
import shutil
print([Link]())
[Link]('test')
print([Link]())
Python has been an object-oriented language since the time it existed. Due to this, creating
and using classes and objects are downright easy.
Data member: A class variable or instance variable that holds data associated with a class and
its objects.
Function overloading: The assignment of more than one behaviour to a particular function. The
operation performed varies by the types of objects or arguments involved.
Instance variable: A variable that is defined inside a method and belongs only to the current
instance of a class.
Inheritance: The transfer of the characteristics of a class to other classes that are derived from
it.
Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for
example, is an instance of the class Circle.
Instantiation: The creation of an instance of a class.
Object: A unique instance of a data structure that is defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
Operator overloading: The assignment of more than one function to a particular operator.
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows
Syntax:
class ClassName:
'Optional class documentation string'
class_suite
The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1
def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])
The variable empCount is a class variable whose value is shared among all the instances
of a in this class. This can be accessed as [Link] from inside the class or
outside the class.
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you
do not need to include it when you call the methods.
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows:-
[Link]()
[Link]()
print ("Total Employee %d" % [Link])
Complete Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1
def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])
Every Python class keeps the following built-in attributes and they can be accessed using dot
operator like any other attribute −
Example:
class Employee:
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1
def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])
Employee.__doc__: None
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', 'empCount': 2, '__init__': <function Employee.__init__ at
0x0541E6A8>, 'displayCount': <function [Link] at 0x05BD6C00>, 'displayEmployee':
<function [Link] at 0x060570C0>, '__dict__': <attribute '__dict__' of 'Employee'
objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}
Destroying Objects
Python deletes unneeded objects (built-in types or class instances) automatically to free the
memory space. The process by which Python periodically reclaims blocks of memory that no
longer are in use is termed as Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of aliases
that point to it changes
An object's reference count increases when it is assigned a new name or placed in a container
(list, tuple, or dictionary). The object's reference count decreases when it is deleted with del,
its reference is reassigned, or its reference goes out of scope. When an object's reference
count reaches zero, Python collects it automatically.
a = 40 # Create object <40>
b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
You normally will not notice when the garbage collector destroys an orphaned instance and
reclaims its space. However, a class can implement the special method__del__(), called a
destructor, that is invoked when the instance is about to be destroyed. This method might be
used to clean up any non-memory resources used by an instance.
Example:
This __del__() destructor prints the class name of an instance that is about to be destroyed.
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3))
# prints the ids of the obejcts
del pt1
97603632 97603632 97603632
del pt2 Point destroyed
del pt3
Inheritance
Inheritance is a powerful feature in object oriented programming.
It refers to defining a new class with little or no modification to an existing class. The new
class is called derived (or child) class and the one from which it inherits is called the base
(or parent) class.
For Example;
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Syntax:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Example:
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print ("Calling parent constructor")
def parentMethod(self):
print ('Calling parent method')
def setAttr(self, attr):
[Link] = attr
def getAttr(self):
print ("Parent attribute :", [Link])
In a similar way, you can drive a class from multiple parent classes as follows
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
You can use issubclass() or isinstance() functions to check a relationship of two classes
and instances.
The issubclass(sub, sup) boolean function returns True, if the given subclass sub is
indeed a subclass of the superclass sup.
The isinstance(obj, Class) boolean function returns True, if obj is an instance of class
Class or is an instance of a subclass of Class.
Overriding Methods
You can always override your parent class methods. One reason for overriding parent's
methods is that you may want special or different functionality in your subclass.
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method')
162
Overloading Operators
Operator Overloading means giving extended meaning beyond their predefined operational
meaning. For example, operator + is used to add two integers as well as join two strings and
merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class.
You might have noticed that the same built-in operator or function shows different behavior
for objects of different classes, this is called Operator Overloading.
Example
# Python program to show use of
# + operator for different purposes.
print(1 + 2)
# concatenate two strings
print("Python"+"Programming")
# Product two numbers 3
print(3 * 4) PythonProgramming
12
# Repeat the String pythonpythonpythonpython
print("python"*4)
When we use an operator on user defined data types then automatically a special function or
magic function associated with that operator is invoked. Changing the behaviour of operator
is as simple as changing the behavior of method or function. You define methods in your
class and operators work according to that behavior defined in methods. When we use +
operator, the magic method __add__ is automatically invoked in which the operation for +
operator is defined. There by changing this magic method’s code, we can give extra meaning
to the + operator.
Example
# Python Program to perform addition of two complex numbers using binary
# + operator overloading.
class complex:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return self.a, self.b
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2 (3, 5)
print(Ob3)
Binary Operators:
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
Comparison Operator
== __eq__(self, other)
!= __ne__(self, other)
Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to
name attributes with a double underscore prefix, and those attributes then will not be directly
visible to outsiders.
Example
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
1
counter = JustCounter() 2
Traceback (most recent call last):
[Link]() File "C:\Users\Programs\Python\Python37-32\Python
[Link]() Files\[Link]", line 11, in <module>
print (counter.__secretCount)
print (counter.__secretCount) AttributeError: 'JustCounter' object has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName.
If you would replace your last line as following, then it works for you-
print (counter._JustCounter__secretCount)
Regular Expression
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern.
Module Regular Expressions (RE) specifies a set of strings(pattern) that matches it.
The module re provides support for regular expressions in Python. Below are main methods
in this module.
match function
[Link]( ) : This function attempts to match pattern to whole string. The [Link] function
returns a match object on success, None on failure.
Syntax:
[Link](pattern, string, flags=0)
Parameters:
pattern : Regular expression to be matched.
string : String where pattern is searched
flags : We can specify different flags using bitwise OR (|).
Example:
# A Python program to demonstrate working of [Link]().
import re
# a sample function that uses regular expressions to find month and day of a date.
def findMonthAndDate(string):
regex = r"([a-zA-Z]+) (\d+)"
match = [Link](regex, string)
if match == None:
print ("Not a valid date")
return
search function
[Link]() : This method either returns None (if the pattern doesn’t match), or a
[Link] that contains information about the matching part of the string. This method
stops after the first match.
Syntax:
re. search (pattern, string, flags=0)
Parameters:
pattern : Regular expression to be matched.
string : String where pattern is searched
flags : We can specify different flags using bitwise OR (|).
Example:
# A Python program to demonstrate working of [Link]().
import re
if match != None:
else:
print ("The regex pattern does not match.")
[Link]()
This method return all non-overlapping matches of pattern in string, as a list of strings. The
string is scanned left-to-right, and matches are returned in the order found .
Example:
# A Python program to demonstrate working of
# findall()
import re
Pattern Description
^ Matches beginning of line
$ Matches end of line.
. Matches any single character except newline.
[...] Matches any single character in brackets.
[^...] Matches any single character not in brackets
re* Matches 0 or more occurrences of preceding expression.
re+ Matches 1 or more occurrence of preceding expression.
a| b Matches either a or b.
\w Matches word characters
\W Matches nonword characters.
\s Matches whitespace. Equivalent to [\t\n\r\f].
\S Matches nonwhitespace.
\d Matches digits. Equivalent to [0-9].
\D Matches nondigits.
\A Matches beginning of string.
\Z Matches end of string. If a newline exists, it matches just before newline.
\z Matches end of string.
Literal Characters:
Example Description
python Match "python"
Character classes:
Example Description
[Pp]ython Match "Python" or "python"
rub[ye] Match "ruby" or "rube"
[aeiou] Match any one lowercase vowel
[0-9] Match any digit; same as [0123456789]
[a-z] Match any lowercase ASCII letter
[A-Z] Match any uppercase ASCII letter
[a-zA-Z0-9] Match any of the above
[^aeiou] Match anything other than a lowercase vowel
[^0-9] Match anything other than a digit
Exception Handling
Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them-
Exception Handling.
Assertions.
Standard Exceptions
Assertions in Python
Python has built-in assert statement to use assertion condition in the program. assert statement
has a condition or expression which is supposed to be always true. If the condition is false
assert halts the program and gives an AssertionError.
Syntax
1. assert <condition>
2. assert <condition>,<error message>
mark1 = [ ]
print("Average of mark1:",avg(mark1))
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Example:
def input_age(age):
try:
assert int(age) > 18
except ValueError:
return 'ValueError: Cannot convert into int'
else:
return 'Age is saved successfully'
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
Handling an Exception
If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include an except:
statement, followed by a block of code which handles the problem as elegantly as possible.
Syntax
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Example
This example opens a file, writes content in the file and comes out gracefully because there is
no problem at all.
try:
f = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
[Link]()
Example
This example tries to open a file where you do not have the write permission, so it raises an
exception-
try:
f = open("testfile", "r")
[Link]("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
[Link]()
You can also use the except statement with no exceptions defined as follows
Syntax
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of
try-except statement is not considered a good programming practice though, because it
catches all exceptions but does not make the programmer identify the root cause of the
problem that may occur.
Example
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry) The entry is a
Oops! <class 'ValueError'> occured.
r = 1/int(entry) Next entry.
You can use a finally: block along with a try: block. The finally: block is a place to put any
code that must execute, whether the try-block raised an exception or not.
Syntax
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
In programming, there may be some situation in which the current method ends up while
handling some exceptions. But the method may require some additional steps before its
termination, like closing a file or a network and so on.
So, in order to handle these situations, Python provides a keyword finally, which is always
executed after try and except blocks. The finally block always executes after normal
termination of try block or after try block terminates due to some exception.
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Argument of an Exception
An exception can have an argument, which is a value that gives additional information about
the problem.
Syntax:
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of
the exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
Example:
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The argument does not contain numbers\n",Argument)
# Call above function here. The argument does not contain numbers
temp_convert("xyz") invalid literal for int() with base 10: 'xyz'
Raising an Exception
You can raise exceptions in several ways by using the raise statement.
Syntax:
raise [Exception [, args [, traceback]]]
If you want to throw an error when a certain condition occurs using raise, you could go about
it like this:
Example;
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
User-Defined Exception
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
Example:
class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg
try:
raise Networkerror('Bad hostname')
except Networkerror as e:
('B', 'a', 'd', ' ', 'h', 'o', 's', 't', 'n', 'a', 'm', 'e')
print([Link])
Runtime error is a class is a standard exception which is raised when a generated error does
not fall into any category. This program illustrates how to use runtime error as base class and
network error as derived class.
Example:
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# User guesses a number until he/she gets it right, you need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
Enter a number: 3
break This value is too small, try again!
except ValueTooSmallError: Enter a number: 36
print("This value is too small, try again!") This value is too large, try again!
Example:
class UnderAge(Exception):
pass
def verify_age(age):
if int(age) < 18:
raise UnderAge
else:
print('As your Age is: '+str(age) + '\nYou are eligible for voting')
# main program
verify_age(23) # won't raise exception
verify_age(17) # will raise exception
import sqlite3
con = [Link]('[Link]')
SQLite3 Cursor
To execute SQLite statements in Python, you need a cursor object. You can create it using
the cursor() method.
The SQLite3 cursor is a method of the connection object. To execute the SQLite3 statements,
a connection is established at first and then an object of the cursor is created using the
connection object as follows:
con = [Link]('[Link]')
cursorObj = [Link]()
Now we can use the cursor object to call the execute() method to execute any SQL queries.
Create Database
When you create a connection with SQLite, a database file is automatically created if it
doesn’t already exist. This database file is created on disk, we can also create a temporary DB
in the RAM by using :memory: with the connect function. This database is called in-memory
database.
When we are done working with the DB we need to close the connection:
[Link]()
Create Table
To create a table in SQLite3, you can use the Create Table query in the execute() method.
Consider the following steps:
1. The connection object is created
2. Cursor object is created using the connection object
3. Using cursor object, execute method is called with create table query as the parameter
Let’s create employees with the following attributes:
employees (id, name, salary, department, position, hireDate)
import sqlite3
def sql_connection():
try:
con = [Link]('[Link]')
return con
except Error:
print(Error)
def sql_table(con):
cursorObj = [Link]()
[Link]()
con = sql_connection()
sql_table(con)
In the above code, we have defined two methods, the first one establishes a connection and
the second method creates a cursor object to execute the create table statement.
The commit() method saves all the changes we make. In the end, both methods are called.
We can also pass values/arguments to an INSERT statement in the execute()method. You can
use the question mark (?) as a placeholder for each value. The syntax of the INSERT will be
like the following:
[Link]('''INSERT INTO employees(id, name, salary, department, position,
hireDate) VALUES(?, ?, ?, ?, ?, ?)''', entities)
con = [Link]('[Link]')
cursorObj = [Link]()
[Link]()
sql_insert(con, entities)
con = [Link]('[Link]')
def sql_update(con):
cursorObj = [Link]()
[Link]()
sql_update(con)
Select statement
The select statement is used to select data from a specific table. If you want to select all the columns
of the data from a table, you can use the asterisk (*). The syntax for this will be as follows:
For Example:
[Link]('SELECT id, name FROM employees')
import sqlite3
con = [Link]('[Link]')
def sql_fetch(con):
cursorObj = [Link]()
rows = [Link]()
print(row)
sql_fetch(con)
Now, to fetch id and names of those who have a salary greater than 50000:
import sqlite3
con = [Link]('[Link]')
def sql_fetch(con):
cursorObj = [Link]()
rows = [Link]()
print(row)
sql_fetch(con)
import sqlite3
con = [Link]('[Link]')
def sql_update(con):
cursorObj = [Link]()
# [Link]()
# [Link]()
sql_update(con)
GUI Programming
Python provides various options for developing graphical user interfaces (GUIs). The most
important features are listed below.
Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
wxPython: This is an open-source Python interface for wxWidgets GUI toolkit.
PyQt:This is also a Python interface for a popular cross-platform Qt GUI library.
JPython: JPython is a Python port for Java, which gives Python scripts seamless
access to the Java class libraries on the local machine[Link]
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides
a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the user.
Example:
import tkinter
top = [Link]()
# Code to add widgets will go here...
[Link]()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application.
There are currently 15 types of widgets in Tkinter. The most important and widely used
widgets will be discussed in the coming topics.
Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can display
text or images that convey the purpose of the buttons. You can attach a function or a method
to a button which is called automatically when you click the button.
Syntax:
w = Button ( master, option=value, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
activebackground: to set the background color when button is under the cursor.
activeforeground: to set the foreground color when button is under the cursor.
bg: to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the button.
width: to set the width of the button.
height: to set the height of the button.
Example:
Tkinter Canvas:
The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You
can place graphics, text, widgets or frames on a Canvas.
Syntax:
w = Canvas ( master, option=value, ... )
Parameters:
master: This represents the parent window
options: There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by commas. Some
of them are listed below.
Example:
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
coord = 10, 50, 240, 210
arc = C.create_arc(coord, start=0, extent=150, fill="red")
line = C.create_line(10,10,200,200,fill='white')
[Link]()
[Link]()
Tkinter Checkbuttton
The Checkbutton widget is used to display several options to a user as toggle buttons. The
user can then select one or more options by clicking the button corresponding to each option.
You can also display images in place of text.
Syntax:
w = Checkbutton ( master, option, ... )
Parameters:
master: This represents the parent window.
options: There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by commas. Some
of them are listed below.
Title: To set the title of the widget.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
bg: The normal background color displayed behind the label and indicator
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget.
Example:
Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
If you want to display multiple lines of text that can be edited, then you should use the
Text widget.
If you want to display one or more lines of text that cannot be modified by the user,
then you should use the Label widget.
Syntax:
w = Entry( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
bd: to set the border width in pixels.
bg: to set the normal background color.
cursor: to set the cursor used.
command: to call a function.
highlightcolor: to set the color shown in the focus highlight.
width: to set the width of the button.
height: to set the height of the button.
Example:
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
[Link]( side = LEFT)
E1 = Entry(top, bd =5)
[Link](side = RIGHT)
[Link]()
Tkinter Frame
The Frame widget is very important for the process of grouping and organizing other widgets
in a somehow friendly way. It works like a container, which is responsible for arranging the
position of other widgets.
Syntax:
w = Frame ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
highlightcolor: To set the color of the focus highlight when widget must be focused.
bd: to set the border width in pixels.
bg: to set the normal background color.
cursor: to set the cursor used.
width: to set the width of the widget.
height: to set the height of the widget.
Example:
from tkinter import *
root = Tk()
frame = Frame(root)
[Link]()
bottomframe = Frame(root)
[Link]( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
[Link]( side = LEFT)
greenbutton = Button(frame, text="Brown", fg="brown")
[Link]( side = LEFT )
bluebutton = Button(frame, text="Blue", fg="blue")
[Link]( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
[Link]( side = BOTTOM)
[Link]()
Tkinter Label
This widget implements a display box where you can place text or images. The text displayed
by this widget can be updated at any time you want.
Syntax:
w = Label ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
Example:
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
[Link]("Hey!? How are you doing?")
[Link]()
[Link]()
Tkinter Listbox
The Listbox widget is used to display a list of items from which a user can select a number of
items
Syntax:
w = Listbox ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
bg: to set he normal background color.
bd: to set the border width in pixels.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
Example:
from tkinter import *
import tkinter
top = Tk()
Lb1 = Listbox(top)
[Link](1, "Python")
[Link](2, "Java")
[Link](3, "C")
[Link](4, "PHP")
[Link](5, "JSP")
[Link](6, "Ruby")
[Link]()
[Link]()
Tkinter Menubutton
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every
menubutton is associated with a Menu widget that can display the choices for that
menubutton when the user clicks on it.
Syntax:
w = Menubutton ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
activebackground: To set the background when mouse is over the widget.
activeforeground: To set the foreground when mouse is over the widget.
bg: to set he normal background color.
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
Example:
from tkinter import *
import tkinter
top = Tk()
mb= Menubutton ( top, text="Juice", relief=RAISED )
[Link]()
[Link] = Menu ( mb, tearoff = 0 )
mb["menu"] = [Link]
pineVar = IntVar()
oraVar = IntVar()
mangoVar = IntVar()
[Link].add_checkbutton ( label="PineApple",
variable=pineVar )
[Link].add_checkbutton ( label="Orange",
variable=oraVar )
[Link].add_checkbutton ( label="Mango",
variable=mangoVar )
[Link]()
[Link]()
Tkinter Menu
The goal of this widget is to allow us to create all kinds of menus that can be used by our
applications. The core functionality provides ways to create three menu types: pop-up,
toplevel and pull-down.
Syntax:
w = Menu ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
Example
from tkinter import *
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
[Link]()
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=[Link])
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
editmenu.add_separator()
editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
[Link](menu=menubar)
[Link]()
Tkinter Message
This widget provides a multiline and noneditable object that displays texts, automatically
breaking lines and justifying their contents. Its functionality is very similar to the one
provided by the Label widget, except that it can also automatically wrap the text, maintaining
a given width or aspect ratio.
Syntax:
w = Message ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
bd: to set the border around the indicator.
bg: to set he normal background color.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
Example
from tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
[Link]("Hey!? How are you doing?")
[Link](bg='yellow')
[Link]()
[Link]()
Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.
Syntax:
w = Radiobutton ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
bg: to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the label in characters.
height: to set the height of the label in characters.
Example
from tkinter import *
def sel():
selection = "You selected the option " + str([Link]())
[Link](text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
[Link]( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
[Link]( anchor = W )
Tkinter Scrollbar
This widget provides a slide controller that is used to implement vertical scrolled widgets,
such as Listbox, Text and Canvas.
Syntax:
w = Scrollbar ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
width: to set the width of the widget.
activebackground: To set the background when mouse is over the widget.
bg: to set he normal background color.
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
Example:
root = Tk()
scrollbar = Scrollbar(root)
mainloop()
Tkinter Text
Text widgets provide advanced capabilities that allow you to edit a multiline text and format
the way it has to be displayed, such as changing its color and font.
Syntax:
w = Text ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
insertbackground: To set the background of the widget.
bg: to set he normal background color.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
Example:
from tkinter import *
root = Tk()
text = Text(root)
[Link](INSERT, "Hello.....")
[Link](END, "Bye Bye.....")
[Link]()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="orange")
text.tag_config("start", background="black", foreground="green")
[Link]()
Tkinter LabelFrame
Syntax:
w = LabelFrame ( master, option, ... )
Parameters:
master: This represents the parent window.
options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
bg: The normal background color displayed behind the label and indicator.
bd: The size of the border around the indicator. Default is 2 pixels.
cursor: If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
font: The vertical dimension of the new frame.
height: The vertical dimension of the new frame.
Example:
from tkinter import *
root = Tk()
labelframe = LabelFrame(root, text="This is a LabelFrame")
[Link](fill="both", expand="yes")
left = Label(labelframe, text="Inside the LabelFrame")
[Link]()
[Link]()
Tkinter tkMessageBox
The tkMessageBox module is used to display message boxes in your applications. This
module provides several functions that you can use to display an appropriate message.
Syntax:
[Link](title, message [, options])
Parameters:
FunctionName: This is the name of the appropriate message box function.
title: This is the text to be displayed in the title bar of a message box.
message: This is the text to be displayed as a message.
options: options are alternative choices that you may use to tailor a standard message
box. Some of the options that you can use are default and parent. The default option is
used to specify the default button, such as ABORT, RETRY, or IGNORE in the
message box. You could use one of the following functions with dialogue box-
showinfo()
showwarning()
showerror ()
askquestion()
askokcancel()
askyesno ()
askretrycancel ()
Example:
from tkinter import *
from tkinter import messagebox
top = Tk()
[Link]("100x100")
def hello():
[Link]("Say Hello", "Hello
World")
B1 = Button(top, text = "Say Hello", command = hello)
[Link](x=35,y=50)
[Link]()
Tkinter Colors
Tkinter represents colors with strings. There are 2 ways to specify colors in Tkinter-
You can use a string specifying the proportion of red, green and blue in hexadecimal
digits. For example, "#fff" is white, "#000000" is black, "#000fff000" is pure green,
and "#00ffff" is pure cyan (green plus blue).
You can also use any locally defined standard color name. The colors "white",
"black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be
available.
Color options:
The common color options are-
activebackground: Background color for the widget when the widget is active.
activeforeground: Foreground color for the widget when the widget is active.
background: Background color for the widget. This can also be represented as bg.
disabledforeground: Foreground color for the widget when the widget is disabled.
foreground: Foreground color for the widget. This can also be represented as fg.
highlightbackground: Background color of the highlight region when the widget has
focus.
highlightcolor: Foreground color of the highlight region when the widget has focus.
selectbackground: Background color for the selected items of the widget.
selectforeground: Foreground color for the selected items of the widget.
Tkinter Fonts
There may be up to three ways to specify type style.
1. Simple Tuple Fonts
As a tuple whose first element is the font family, followed by a size in points,
optionally followed by a string containing one or more of the style modifiers bold,
italic, underline and overstrike.
Example:
("Helvetica", "16") for a 16-point Helvetica regular.
("Times", "24", "bold italic") for a 24-point Times bold italic.
Example:
helv36 = [Link](family="Helvetica",size=36,weight="bold")
3. X Window Fonts
If you are running under the X Window System, you can use any of the X font names.
For example, the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*"
is the author's favorite fixed-width font for onscreen use.
Scenario:
In this game player must enter color of the word that appears on the screen and hence the
score increases by one, the total time to play this game is 30 seconds. Colors used in this
game are Red, Blue, Green, Pink, Black, Yellow, Orange, White, Purple and Brown.
Interface will display name of different colors in different colors. Player must identify the
color and enter the correct color name to win the game.
Code:
# import the modules
import tkinter
import random
if timeleft == 30:
nextColour()
score += 1
[Link](colours)
global timeleft
# if a game is in play
if timeleft > 0:
# Driver Code
[Link]()
OUTPUT:
Scenario:
There is one bar at the bottom of game window which can be moved left or right using the
buttons that are in the game window. Red ball will continuously fall from top to bottom and
can start from any random x-axis distance. The task is to bring that bar to a suitable location
by moving left or right so that the red ball will fall on that bar(catch the ball onto the bar) not
on the ground. If player catches the ball onto the bar then score will get increase and that ball
will disappear and again a new red ball will start falling from top to bottom starting from
random x-axis distance. If player miss the ball from catching it on the bar then you will lose
the game and then finally scorecard will appear on the game window.
Approach:
1. Use Tkinter package in python for building GUI(Graphical user interface).
2. Use Canvas for drawing objects in Python – Canvas is a rectangular area intended for
drawing pictures or other complex layouts. We can place graphics, text, widgets or
frames on Canvas.
3. Syntax: w = Canvas ( master, option=value, ... )
Parameters:
master - This represents the parent window.
options - List of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Example- width, height etc.
4. Use canvas.create_oval for creating the ball.
create_oval creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for the
oval.
Syntax: oval = canvas.create_oval(x0, y0, x1, y1, options)
5. Use canvas.create_rectangle for creating the bar.
create_rectangle creates a rectangle at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right coordinates.
Syntax: oval = canvas.create_rectangle(x0, y0, x1, y1, options)
6. Use [Link] for moving the ball or bar.
[Link] enables the object to move with the specified (x, y) coordinates.
Syntax: move=[Link](name of object, x, y)
Note: *Take x=0 for moving the ball in vertical direction only and take y=0 for moving the
bar in horizontal direction only. *Dissapear the ball when it touches the ground or the bar
using [Link](object).
7. Use Button for moving the bar in forward or backward and then apply action event on
it.
Code:
# defining offset
offset = 10
global limit
else:
# dissappear the ball
[Link]('dot1')
bar.delete_bar(self)
fill="yellow",tags='dot2')
def delete_bar(self):
[Link]('dot2')
button4 = Button(canvas2,text="EXIT",bg="green",
command=lambda:exit_handler(root2))
[Link]()
# Main function
def main():
global score,dist
score = 0
dist = 0
button2 = Button(canvas,text="<==",bg="green",
command=lambda:bar1.move_bar(0))
[Link](x=260,y=580)
# Driver code
if(__name__=="__main__"):
main()
OUTPUT: