Python Programming
Python Programming
Name : ……………………………………………………………………………………………
Module II: Decision Making -conditional (if), alternative (if-else), if..elif..else -nested if - Loops for,range()
while, break, continue, pass; Functions: return values, parameters, local and global scope, function
composition, recursion; Strings: string slices, immutability, string functions and methods, string module;
Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum of an array of numbers,
linear search, binary search, bubble sort, insertion sort, selection sort
Module III: Built-in Modules - Creating Modules - Import statement - Locating modules - Namespaces
and Scope - The dir() function - The reload function - Packages in PythonFiles and exception: text files,
reading and writing files Renaming and Deleting files Exception handling exceptions, Exception with
arguments, Raising an Exception - User defined Exceptions - Assertions in python
Module IV: GUI Programming- Introduction – Tkinter Widgets – Label – Message Widget – Entry Widget
– Text Widget – tk Message Box – Button Widget – Radio Button- Check Button – Listbox- Frames _
Toplevel Widgets – Menu Widget
MODULE 1
Introduction to Python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990.
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
Characteristics of Python
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Advantages of Python
1. Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
2. Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
3. Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
4. Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
Features in Python
There are many features in Python, some of which are discussed below –
1.Easy to code:
Python is high level programming language.Python is very easy to learn language as compared to other
language like c, c#, java script, java etc.It is very easy to code in python language and anybody can learn
python basic in few hours or days.It is also developer-friendly language.
Python language is freely available at official website.Since, it is open-source, this means that source
code is also available to the public.So you can download it as, use it as well as share it.
3.Object-Oriented Language:
One of the key features of python is Object-Oriented programming.Python supports object oriented
language and concepts of classes, objects encapsulation etc.
Graphical Users interfaces can be made using a module such as PyQt5, PyQt4, wxPython or Tk in
python.PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the
system architecture, nor do we need to manage the memory.
6.Extensible feature:
Python is a Extensible language. we can write our some python code into c or c++ language and also we
can compile that code in c/c++ language.
Python language is also a portable language.for example, if we have python code for windows and if we
want to run this code on other platform such as Linux, Unix and Mac then we do not need to change it,
we can run this code on any platform.
Python is also an Integrated language because we can easily integrated python with other language like
c, c++ etc.
9. Interpreted Language:
Python is an Interpreted Language. because python code is executed line by line at a time. The source
code of python is converted into an immediate form called bytecode.
Python has a large standard library which provides rich set of module and functions so you do not have
to write your own code for every single thing.There are many libraries present in python for such as
regular expressions, unit-testing, web browsers etc.
Python is dynamically-typed language. That means the type (for example- int, double, long etc) for a
variable is decided at run time not in advance.because of this feature we don’t need to specify the type
of variable.
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one
entity from another.
Example: a=10
Keywords in Python
A python keyword is a reserved word which you can’t use as a name of your variable, class,
function etc.
These keywords have a special meaning and they are used for special purposes in Python
programming language.
For example – Python keyword “while” is used for while loop thus you can’t name a variable
with the name “while” else it may cause compilation error.
There are total 33 keywords in Python
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Since Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
In python, if you want to show something on screen as an output, there we use the print()
function. Using the print() function you can show the output data on your standard screen.
Normally print() function is used to show the output data of variables and strings.
Example:
print(“Welcome to Python”)
print(a)
String Formatting:
There is a special function called format() which is used with a string, that gives you more
flexibility over the print() function. format() function is used with a string and you can insert
variables in specific places of that particular string.
We use {} curly brackets to hold the places of variables or string that pass in the format()
function.
Example
s= "Kiran"
age=25
print("My name is {} and I am {} years old ". format(s,age))
The prompt is a string which is used as a message that displays on the screen
Import in Python:
Import is a keyword which is used to import the definitions of the module (modules are the
python files which contain the prewritten code or function) in the current file. Import keyword is
used along with another keyword from which is used to import the module
Suppose you want a programme which accepts an integer and give the square root of the
integer. For this, you can make a program or you can use a predefined function sqrt() which is a
part of module math. So to use the sqrt() function you need to import it on your current file by
using the import keyword.
Output:
Enter a Number:25
5
Operators in Python
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Membership Operators
6. Identity Operators
1.Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then –
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
// Floor Division - The division of operands where the result is 9//2 = 4 and 9.0//2.0 = 4.0,
the quotient in which the digits after the decimal point are -11//3 = -4, -11.0//3 = -4.0
removed. But if one of the operands is negative, the result is
floored, i.e., rounded away from zero (towards negative
infinity) −
2.Comparison Operators
These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
== If the values of two operands are equal, then the condition (a == b) is not true.
becomes true.
!= If values of two operands are not equal, then condition becomes (a != b) is true.
true.
<> If values of two operands are not equal, then condition becomes (a <> b) is true. This is
true. similar to != operator.
> If the value of left operand is greater than the value of right (a > b) is not true.
operand, then condition becomes true.
< If the value of left operand is less than the value of right operand, (a < b) is true.
then condition becomes true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is not true.
right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of (a <= b) is true.
right operand, then condition becomes true.
3.Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
= Assigns values from right side operands to left side c = a + b assigns value of a + b
operand into c
+= Add AND It adds right operand to the left operand and assign
c += a is equivalent to c = c + a
the result to left operand
-= Subtract AND It subtracts right operand from the left operand and
c -= a is equivalent to c = c - a
assign the result to left operand
*= Multiply AND It multiplies right operand with the left operand and
c *= a is equivalent to c = c * a
assign the result to left operand
/= Divide AND It divides left operand with the right operand and
c /= a is equivalent to c = c / a
assign the result to left operand
%= Modulus AND It takes modulus using two operands and assign the c %= a is equivalent to c = c %
result to left operand a
//= Floor Division It performs floor division on operators and assign c //= a is equivalent to c = c //
value to the left operand a
4.Logical Operators
There are following logical operators supported by Python language. Assume variable a holds 10 and
variable b holds 20 then
and Logical AND If both the operands are true then condition becomes true. (a and b) is true.
or Logical OR If any of the two operands are non-zero then condition becomes true. (a or b) is true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is
false.
5.Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below −
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results in a 1 if x is
specified sequence and false otherwise. not a member of sequence y.
6.Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −
is Evaluates to true if the variables on either side of the x is y, here is results in 1 if id(x)
operator point to the same object and false otherwise. equals id(y).
is not Evaluates to false if the variables on either side of the x is not y, here is not results in
operator point to the same object and true otherwise. 1 if id(x) is not equal to id(y).
Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
1.Numbers
Number data types store numeric values. Number objects are created when you assign a value
to them. For example −
var1 = 1
var2 = 10
Python supports four different numerical types −
2.Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs 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 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example −
3.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 difference 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 −
4.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 parentheses.
The main differences between lists and tuples are: 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 −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
5.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"
Every variable in python holds an instance of an object. There are two types of objects in
python i.e. Mutable and Immutable objects.
Whenever an object is instantiated, it is assigned a unique object id. The type of the
object is defined at the runtime and it can’t be changed afterwards. However, it’s state
can be changed if it is a mutable object.
To summarise the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.
Immutable Objects : These are of in-built types like int, float, bool, string, unicode,
tuple. In simple words, an immutable object can’t be changed after it is created.
Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
Python defines type conversion functions to directly convert one data type to another which is
useful in day to day and competitive programming. The following are type conversion functions
in python.
1.int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which
string is if data type is string.
2. float() : This function is used to convert any data type to a floating point number
Example
s = "10010"
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Example:
# initializing integer
s = '4'
c = ord(s)
print ("After converting character to integer : ")
print (c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
Example:
# initializing string
s = 'geeks'
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : : This function converts real numbers to complex(real,imag) number.
Example
# initializing integers
a =1
b =2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
12. chr(number) : : This function converts number to its corresponding ASCII character.
Example:
print(a)
print(b)
Output:
L
M
A = ['t','u','t','o','r','i','a','l']
for i in range(len(A)):
min_= i
min_ = j
#swap
# main
for i in range(len(A)):
print(A[i])
Output
a
i
l
o
r
t
t
u
def insertionSort(arr):
key = arr[i]
than key,
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# main
arr = ['t','u','t','o','r','i','a','l']
insertionSort(arr)
for i in range(len(arr)):
print (arr[i])
Output
The sorted array is:
a
i
l
o
r
t
t
u
Step1:
The same process goes on for the remaining iterations. After each iteration, the largest element
among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct positions.
def bubbleSort(array):
# run loops two times: one for walking throught the array
# and the other for comparison
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
MODULE 2
Module II: Decision Making -conditional (if), alternative (if-else), if..elif..else -nested if - Loops for,range()
while, break, continue, pass; Functions: return values, parameters, local and global scope, function
composition, recursion; Strings: string slices, immutability, string functions and methods, string module;
Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum of an array of numbers,
linear search, binary search, bubble sort, insertion sort, selection sort
1.if Statements
It consists of a Boolean expression which results are either TRUE or FALSE, followed by one or more
statements.
Synatx:
if expression:
#execute your code
Example:
a = 15
if a > 10:
print("a is greater")
Output:
a is greater
It also contains a Boolean expression. The if the statement is followed by an optional else statement & if
the expression results in FALSE, then else statement gets executed. It is also called alternative execution
in which there are two possibilities of the condition determined in which any one of them will get
executed.
Synatx:
if expression:
#execute your code
else:
#execute your code
Example:
a = 15
b = 20
if a > b:
print("a is greater")
else:
print("b is greater")
Output:
b is greater
3.elif Statements
We can implement if statement and or if-else statement inside another if or if - else statement.
Here more than one if conditions are applied & there can be more than one if within elif.
elif - is a keyword used in Python replacement of else if to place another condition in the
program. This is called chained conditional.
Example:
if expression:
#execute your code
elif expression:
#execute your code
else:
#execute your code
Example:
a = 15
b = 15
if a > b:
print("a is greater")
elif a == b:
print("both are equal")
else:
print("b is greater")
Output:
both are equal
looping in Python
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.A loop statement allows us to execute a statement or
group of statements multiple times.
Python programming language provides following types of loops to handle looping
requirements.
1 while loop : Repeats a statement or group of statements while a given condition is TRUE. It tests
the condition before executing the loop body.
2 for loop :-Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1.While Loop
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Synatx:
while expression:
#execute your code
Example:
count =1
while count < 6 :
print (count)
count+=1
Output:
1
2
3
4
5
2.for loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.
Example :
for x in range (0,3) :
print (x)
Output:
0
1
2
3.Nested Loop
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Example:
for g in range(1, 6):
for k in range(1, 3):
print ("%d * %d = %d" % ( g, k, g*k))
Output:
1*1=1
1*2=2
2*1=2
2*2=4
3*1=3
3*2=6
4*1=4
4*2=8
5*1=5
5 * 2 = 10
1.Break statement:-It is used to exit a while loop or a for a loop. It terminates the looping & transfers execution to
the statement next to the loop.
Sytanx:
break
Example:
i = 0
while i <= 10:
print (i)
i++
if i == 3:
break
Output:
0
1
2
2.Continue statement:- It causes the looping to skip the rest part of its body & start re-testing its condition.
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.
Sytanx:
continue
Example:
i = 0
while i <= 10:
print (i)
i++
if i == 3:
continue
Output:
0
1
2
4
5
6
7
8
9
10
Muslim Association College of Arts and Science Page 32
CS1543 Python Programming
3.Pass statement:-
It is used in Python to when a statement is required syntactically, and the programmer does not want
to execute any code block or command.
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
is also useful in places where your code will eventually go, but has not been written yet i.e. in
stubs.
Syntax:
pass
Example
for i in 'Python':
if i == 'h':
pass
print ('This is pass block')
print ('Current Letter :', i)
Output
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Python functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses.
Any input parameters or arguments should be placed within these parentheses.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function
. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
“function body”
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that
they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function
or directly from the Python prompt. Following is the example to call printme() function −
def printme(a):
print a
return;
Output: 21 x hai
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular variable. There are two basic scopes of variables in Python −
Global variables
Local variables
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1.Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax
error as follows −
2.Keyword arguments
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.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printinfo() function in the following ways −
2.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. The following example gives an idea on default arguments, it prints
default age if it is not passed −
4.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 and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
example:
def printinfo(a,*var_argument)
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call. Following is a simple example −
def printinfo( arg1, *vartuple ):
print "Output is: "
print arg1
for var in vartuple:
print var
return;
Anonymous Functions
These functions are called anonymous because they are not declared in the standard manner
by using the def keyword. You can use the lambda keyword to create small anonymous
functions.
Lambda forms can take any number of arguments but return just one value in the form
of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an
expression
Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Recursion in Python
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
In this example, fact() is a function that we have defined to call itself ("recurse"). The
factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is 1*2*3*4*5*6 = 720. Factorial is not defined for negative
numbers and the factorial of zero is one, 0! = 1.
if x == 1:
return 1
else:
return (x * fact (x-1))
num = 3
print("The factorial of", num, "is", fact (num))
Output
The factorial of 3 is 6
String in Python
A character is simply a symbol. For example, the English language has 26 characters.
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes. Creating strings is
as simple as assigning a value to a variable.
For example –
var1 = 'Hello World!'
var2 = "Python Programming"
Example
Python slicing is about obtaining a sub-string from the given string by slicing it respectively
from start to end.Python slicing can be done in two ways.
1. slice() Constructor
2. Extending Indexing
1.slice() Constructor :The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Example:
String ='ASTRING'
s1 = slice(3)
s2 = slice(1, 5)
s3 = slice(-1, -7, -3)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
STRI
GR
2.Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string both syntax wise and execution wise.
Syntax
string[start:end:step]
start, end and step have the same mechanism as slice() constructor.
Example
String ='ASTRING'
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
print("\nReverse String")
print(String[::-1])
Output:
AST
SR
GITA
Reverse String
GNIRTSA
String Immutability
In python, the string data types are immutable. Which means a string value cannot be updated.
We can verify this by trying to update a part of the string which will led us to an error.
Example
t= "Tutorialspoint"
print type(t)
t[0] = "M"
When we run the above program, we get the following output –
t[0] = "M"
TypeError: 'str' object does not support item assignment
String Functions in Python
Python provides lots of built-in methods which we can use on strings.Below are the list of string
methods available in Python 3.
Returns a copy of the string with its >>> mystring = "hello python"
capitalize() first character capitalized and the rest >>> print(mystring.capitalize())
lowercased. Hello python
Returns True if the string ends with the >>> mystr = "Python"
endswith(suffix, >>>print(mystr.endswith("y"))
specified suffix, otherwise it returns
[start], [end]) False
False. >>>print(mystr.endswith("hon"))
True
>>> print(a.isalpha())
False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False
>>> c="133"
>>> print(c.isdigit())
True
Returns True if all characters in the >>> c = u"\u00B2"
Isdigit()
string are digits >>> print(c.isdigit())
True
>>> a="1.23"
>>> print(a.isdigit())
False
>>> c="Python"
>>> print(c.islower())
False
Returns True if all characters in the
Islower() >>> c="_user_123"
string are lower case >>> print(c.islower())
True
>>> print(c.islower())
False
>>> c="133"
Returns True if all characters in the >>> print(c.isnumeric())
Isnumeric() True
string are numeric
>>> c="_user_123"
>>> print(c.isnumeric())
False
>>> c="Python"
>>> print(c.isnumeric())
False
>>> c="133"
>>> print(c.isprintable())
True
Returns True if all characters in the >>> c="_user_123"
isprintable()
string are printable >>> print(c.isprintable())
True
>>> c="\t"
>>> print(c.isprintable())
False
>>> c="133"
>>> print(c.isspace())
False
>>> c="Hello Python"
>>> print(c.isspace())
Returns True if all characters in the False
isspace()
string are whitespaces 73
>>> c="Hello"
>>> print(c.isspace())
False
>>> c="\t"
>>> print(c.isspace())
True
>>> c="Python"
>>> print(c.isupper())
False
Returns True if all characters in the >>> c="PYHTON"
isupper()
string are upper case >>> print(c.isupper())
True
>>> c="\t"
>>> print(c.isupper())
False
>>> a ="-"
Joins the elements of an iterable to the >>> print(a.join("123"))
join(iterable) 1-2-3
end of the string
>>> a="Hello Python"
>>> a="**"
>>> print(a.join("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n
>>> a = "Python"
lower() Converts a string into lower case
>>> print(a.lower())
Python
String Module
The string module provides additional tools to manipulate strings.
It’s a built-in module and we have to import it before using any of its constants and classes.
Python String Module Classes-Python string module contains two classes –
1. Formatter
2. Template.
1.Formatter
It behaves exactly same as str.format() function. This class become useful if you want to subclass it and
define your own format string syntax
Example:
formatter = Formatter()
print(formatter.format('{website}', website='JournalDev'))
print(formatter.format('{} {website}', 'Welcome to', website='JournalDev'))
Example:
List as Arrays
During programming, there will be instances when you will need to convert existing lists to
arrays in order to perform certain operations on them (arrays enable mathematical operations
to be performed on them in ways that lists do not).
In Python programming, a list is created by placing all the items (elements) inside square
brackets [], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
Lists can be converted to arrays using the built-in functions in the Python numpy library.
numpy provides us with two functions to use when converting a list into an array:
1. numpy.array()
2. numpy.asarray()
1. Using numpy.array()
This function of the numpy library takes a list as an argument and returns an array that contains all the
elements of the list. See the example below:
Example:
import numpy as np
my_list = [2,4,6,8,10]
my_array = np.array(my_list)
# printing my_array
print my_array
# printing the type of my_array
print type(my_array)
Output:
[ 2 4 6 8 10]
<type 'numpy.ndarray'>
2. Using numpy.asarray()
This function calls the numpy.array() function inside itself. See the definition below
import numpy as np
my_list = [2,4,6,8,10]
my_array = np.asarray(my_list)
# printing my_array
print my_array
# printing the type of my_array
print type(my_array)
Output:
[ 2 4 6 8 10]
<type 'numpy.ndarray'>
The main difference between np.array() and np.asarray() is that the copy flag is false in the case
of np.asarray(), and true (by default) in the case of np.array().
Illustrative Programs:
1.Python program to find square root of a number
Python number method sqrt() returns the square root of x for x > 0.
import math # This will import math module
a=100
b=7
c=81
print "Square root of a is : ", math.sqrt(a)
print " Square root of b is ", math.sqrt(b)
print " Square root of c is ", math.sqrt(c)
Output
Square root of a is 10
Square root of b is 2.645
Square root of c is 9
Python program to find gsd of two numbers
Greatest common divisor or gcd is a mathematical expression to find the highest number which can
divide both the numbers whose gcd has to be found with the resulting remainder as zero. It has many
mathematical applications. Python has a inbuilt gcd function in the math module which can be used for
this purpose.
gcd():-It accepts two integers as parameter and returns the integer which is the gcd value.
Syntax
Syntax: gcd(x,y)
Example of gcd()
In the below example we print the result of gcd of a pair of integers.
import math
Output
Running the above code gives us the following result −
GCD of 75 and 30 is 15
GCD of 0 and 12 is 12
GCD of 0 and 0 is 0
GCD of -24 and -18 is 6
output:
Exponential value is 81
output
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
Here we linearly scan the list with the help of for loop.
Output
element found at index 6
MODULE 3
Module III: Built-in Modules - Creating Modules - Import statement - Locating modules - Namespaces
and Scope - The dir() function - The reload function - Packages in PythonFiles and exception: text files,
reading and writing files Renaming and Deleting files Exception handling exceptions, Exception with
arguments, Raising an Exception - User defined Exceptions - Assertions in python
The Python interpreter has a number of built-in functions. They are loaded automatically as the
interpreter starts and are always available.
For example, print() and input() for I/O, number conversion functions int(), float(), complex(),
data type conversions list(), tuple(), set(), etc.
In addition to built-in functions, a large number of pre-defined functions are also available as a
part of libraries bundled with Python distributions. These functions are defined in modules. A
module is a file containing definitions of functions, classes, variables, constants or any other
Python objects. Contents of this file can be made available to any other program.
Creating 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. A module is a Python object with arbitrarily named
attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
import Statement
We can use any Python source file as a module by executing an import statement in some other
Python source file.
The import has the following syntax −
import module_name
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches
before importing a module.
For example, to import the module support.py, you need to put the following command at the
top of the script −
import support
support.print_func("Zara")
When the above code is executed, it produces the following result −
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening over and over again if multiple imports occur.
from...import Statement
Python's from statement lets you import specific attributes from a module into the
current namespace.
The from...import has the following syntax −
from module_name import name1
For example, to import the function fibonacci from the module fib, use the following statement −
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces
the item fibonacci from the module fib into the global symbol table of the importing module.
from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement −
from modname import *
This provides an easy way to import all the items from a module into the current namespace.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following sequences
1. The current directory.
2. If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
3. If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path
variable contains the current directory, PYTHONPATH, and the installation-dependent default.
Money = 2000
def AddMoney():
Money = Money + 1
Print(“Value of money in function”+ Money)
AddMoney()
Print(“value of money outside the function”+Money)
Output
Value of money in function 2001
Value of money outside the function 2000
import math
content = dir(math)
print content
Now we are importing a.py and b.py into our program from the python code simple_package and calling
functions bar() and foo() using package name
from simple_package import a, b
a.bar()
b.foo()
Output:
Hello, function 'bar' from module 'a' calling
Hello, function 'foo' from module 'b' calling
Writing to a File
Let's see how to write data to a file.
Open a file using the open() in w mode. If you have to read and write data using a file, then
open it in an r+ mode.
Write the data to the file using write() or writelines() method
Close the file.
I am a Python programmer.
I am happy.
Example
Following is the example to rename an existing file test1.txt −
import os
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
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.
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else keyword to define a block of code to be executed if no errors were raised:
The finally block lets you execute code, regardless of the result of the try- and except blocks
1
Exception : Base class for all exceptions
2
StopIteration :Raised when the next() method of an iterator does not point to any object.
3
SystemExit : Raised by the sys.exit() function.
4
StandardError :Base class for all built-in exceptions except StopIteration and SystemExit.
5
ArithmeticError:Base class for all errors that occur for numeric calculation.
6
OverflowError:Raised when a calculation exceeds maximum limit for a numeric type.
7
FloatingPointError Raised when a floating point calculation fails.
8
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError Raised in case of failure of the Assert statement.
10
AttributeError Raised in case of failure of attribute reference or assignment.
11
EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is
reached.
12
ImportError Raised when an import statement fails.
13
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14
LookupError .Base class for all lookup errors.
15
IndexError Raised when an index is not found in a sequence.
16
KeyError Raised when the specified key is not found in the dictionary.
17
NameError Raised when an identifier is not found in the local or global namespace.
18
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has
been assigned to it.
19
EnvironmentError Base class for all exceptions that occur outside the Python environment.
21
IOError
Raised for operating system-related errors.
22
SyntaxError Raised when there is an error in Python syntax.
23
IndentationError Raised when indentation is not specified properly.
24
SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the
Python interpreter does not exit.
26
TypeError Raised when an operation or function is attempted that is invalid for the specified data type.
27
ValueError Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
28
RuntimeError Raised when a generated error does not fall into any category.
Syntax
Here is simple syntax of try....except...else blocks −
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
try:
a=int(input()
b=int(input())
div=a/b
except ArithmeticError:
print("Divistion with zero is not possible")
else:
print(div)
Argument of an Exception
An exception can have an argument, which is a value that gives additional information about
the problem. The contents of the argument vary by exception. You capture an exception's
argument by supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, 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.
Example
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general syntax for
the raise statement is as follows.
Syntax
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises
are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and
can be done as follows −
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed
from RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is
used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with your
testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an
exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced
in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after
a function call to check for valid output.
Example
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit.
Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative
temperature −
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
MODULE 4
Module IV: GUI Programming- Introduction – Tkinter Widgets – Label – Message Widget – Entry Widget
– Text Widget – tk Message Box – Button Widget – Radio Button- Check Button – Listbox- Frames _
Toplevel Widgets – Menu Widget
Python GUI
Python offers multiple options for developing GUI (Graphical User Interface). Out of all
the GUI methods, tkinter is the most commonly used method. It is a standard Python
interface to the Tk GUI toolkit shipped with Python.
Python with tkinter is the fastest and easiest way to create the GUI applications.
Creating a GUI using tkinter is an easy task.
Importing tkinter is same as importing any other module in the Python code
import tkinter
There are two main methods used which the user needs to remember while creating the Python
application with GUI.
2. mainloop():
There is a method known by the name mainloop() is used when your application is ready
to run. mainloop() is an infinite loop used to run the application, wait for an event to
occur and process the event as long as the window is not closed.
m.mainloop()
Example
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
This would create a following window −
Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have the
purpose of organizing widgets throughout the parent widget area. Tkinter exposes the
following geometry manager classes: pack, grid, and place.
The pack() Method − This geometry manager organizes widgets in blocks before placing
them in the parent widget.
The grid() Method − This geometry manager organizes widgets in a table-like structure
in the parent widget.
The place() Method − This geometry manager organizes widgets by placing them in a
specific position in the parent widget.
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
Tkinter is implemented as a Python wrapper for the Tcl Interpreter embedded within the
interpreter of Python. Tk provides the following widgets:
button
canvas
combo-box
frame
level
check-button
entry
level-frame
menu
list - box
menu button
message
tk_optoinMenu
progress-bar
radio button
scroll bar
separator
tree-view, and many more.
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.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and span
the text across multiple lines
Syntax
Here is the simple syntax to create this widget −
Parameters
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options
can be used as key-value pairs separated by commas.Commanly used options are
height,width,font,bgcolor etc
Example
Try the following example yourself −
from Tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var)
Syntax
Here is the simple syntax to create this widget −
w = Message ( master, option, ... )
Example
Try the following example yourself −
from Tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
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
Here is the simple syntax to create this widget −
w = Entry( master, option, ... )
Example
Try the following example yourself −
from Tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
Syntax
Here is the simple syntax to create this widget −
w = Text ( master, option, ... )
Example
Try the following example yourself −
from Tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
Tkinter tkMessageBox
The tkMessageBox module is used to display message boxes in your applications. This module
provides a number of functions that you can use to display an appropriate message.
Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel,
askyesno, and askretryignore.
Syntax
Here is the simple syntax to create this widget −
tkMessageBox.FunctionName(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. You could use one of the following functions with dialogue box −
showinfo()
showwarning()
showerror ()
askquestion()
askokcancel()
askyesno ()
askretrycancel ()
Example
Try the following example yourself −
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def hello():
tkMessageBox.showinfo("Say Hello", "Hello World")
top.mainloop()
Example
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B.pack()
top.mainloop()
When the above code is executed, it produces the following result −
Syntax
Here is the simple syntax to create this widget −
w = Radiobutton ( master, option, ... )
Example
from Tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result −
Syntax
w = Checkbutton ( master, option, ... )
Example
from Tkinter import *
import tkMessageBox
import Tkinter
top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
When the above code is executed, it produces the following result −
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, ... )
Example
from Tkinter import *
import tkMessageBox
import Tkinter
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
When the above code is executed, it produces the following result −
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.
It uses rectangular areas in the screen to organize the layout and to provide padding of these
widgets. A frame can also be used as a foundation class to implement complex widgets.
Syntax
w = Frame ( master, option, ... )
Example
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
root.mainloop()
When the above code is executed, it produces the following result −
Syntax
Here is the simple syntax to create this widget −
w = Menu ( master, option, ... )
Example
Try the following example yourself −
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
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=root.quit)
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)
root.config(menu=menubar)
root.mainloop()