Sie sind auf Seite 1von 100

CMR Institute of Technology Redefining Quality Education

Syllabus
PYTHON PROGRAMMING
B.Tech. II Year I Sem. LT PC
Course Code: CS-PCC-211 3 0 0 3
Course Outcomes: Upon completion of the course, the students will be able to
1. perceive the fundamentals of python programming
2. develop programs using control statements
3. analyze the programming performances using functions
4. make use of collections in python programming
5. design classes and build error-free codes

Unit-I: Introduction 10 hours


Introduction to Python, Installing Python. How a Program Works, Using Python, Program
Development Cycle, Input and Output, Comments, Variables, Data types, Reading Input from the
Keyboard, Displaying Output with the Print Function, Performing Calculations, Operators, Type
conversions, Expressions.

Unit-II: Control Flow, Functions and Modules 10 hours


Control Flow Statements: Decision Structures and Boolean Logic: if, if-else, if-elif-else
Statements, Nested Decision Structures, Repetition Structures: Introduction, while loop, for loop,
Input Validation Loops, Nested Loops, control statements-break, continue, pass.

Functions and Modules: Introduction, Defining and Calling a Void Function, Designing a
Program to Use Functions, Local Variables, Passing Arguments to Functions, Global Variables
and Global Constants, Value-Returning Functions-Generating Random Numbers, The math
Module, Storing Functions in Modules.

Unit-III: Strings and Collections (4 + 5) 9 hours


Part-A: Strings: Accessing Characters and Substrings in a String, String Methods, Basic String
Operations, String Slicing, Testing, Searching, Comparing and Manipulating Strings.

Part-B: Collections: Lists, Introduction to Lists, List slicing, Finding Items in Lists with the in
Operator, List Methods and Useful Built-in Functions, Copying Lists, Processing Lists, Two-
Dimensional Lists, Tuples, Tuple methods. Sets, Operations on Sets, Dictionaries and its methods.

Unit-IV: Classes and Exceptions 10 hours


Design with Classes: Classes and Objects, Classes and Functions, Classes and Methods, Working
with Instances, Inheritance and Polymorphism. Object-Oriented Programming: Procedural and
Object-Oriented Programming, Classes, techniques for Designing Classes.

PYTHON PROGRAMMING Page 1


CMR Institute of Technology Redefining Quality Education

Exceptions: Difference between an error and Exception, Handling Exception, try except block,
Raising Exceptions, User Defined Exceptions.

Unit-V: GUI Programming 9 hours

Graphical User Interfaces: Behavior of terminal based programs and GUI-based programs,
Coding simple GUI-based programs, other useful GUI resources. GUI Programming: Graphical
User Interfaces, Using the Tkinter Module, Display text with Label Widgets, Organizing Widgets
with Frames, Button Widgets and Info Dialog Boxes, Getting Input with Entry Widget, Using
Labels as Output Fields, Radio Buttons, Check Buttons.

Textbooks:

1. Kenneth A. Lambert, The Fundamentals of Python: First Programs, 2011, Cengage Learning.
2. Think Python First Edition, by Allen B. Downey, Orielly publishing.

References:

1. Introduction to Computation and Programming Using Python. John V. Guttag, The MIT Press.
2. James Payne, Beginning Python using Python 2.6 and Python 3, Wrox publishing.

PYTHON PROGRAMMING Page 2


CMR Institute of Technology Redefining Quality Education

Lecturer Notes
UNIT–1

Introduction to Python: Python is a high-level, interpreted, interactive and object-oriented


scripting language. Python is designed to be highly readable. It uses English keywords frequently
where as other languages use punctuation, and it has fewer syntactical constructions than other
languages.

 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.
 Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 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.

History of Python

 Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
 Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, Unix shell, and other scripting languages.
 At the time when he began implementing Python, Guido van Rossum was also reading the
published scripts from "Monty Python's Flying Circus" (a BBC comedy series from the
seventies, in the unlikely case you didn't know). It occurred to him that he needed a name
that was short, unique, and slightly mysterious, so he decided to call the language Python.
 Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
 Python 1.0 was released on 20 February, 1991.
 Python 2.0 was released on 16 October 2000 and had many major new features, including
a cycle detecting garbage collector and support for Unicode. With this release the
development process was changed and became more transparent and community-backed.
 Python 3.0 (which early in its development was commonly referred to as Python 3000 or
py3k), a major, backwards-incompatible release, was released on 3 December 2008 after a

PYTHON PROGRAMMING Page 3


CMR Institute of Technology Redefining Quality Education

long period of testing. Many of its major features have been back ported to the backwards-
compatible Python 2.6.x and 2.7.x version series.
 In January 2017 Google announced work on a Python 2.7 to go transcompiler, which The
Register speculated was in response to Python 2.7's planned end-of-life.

Python Features: Python's features include:

 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X Window system of UNIX.
 Scalable: Python provides a better structure and support for large programs than shell
scripting.

PYTHON PROGRAMMING Page 4


CMR Institute of Technology Redefining Quality Education

Installing Python:

Step 1: Go to website www.python.org and click downloads select version which you want.

Step 2: Click on Python 2.7.13 and download. After download open the file.

Step 3: Click on Next to continue.

PYTHON PROGRAMMING Page 5


CMR Institute of Technology Redefining Quality Education

Step 4: After installation location will be displayed. The Default location is C:\Python27.
Click on next to continue.

Step 5: After the python interpreter and libraries are displayed for installation. Click on
Next to continue.

PYTHON PROGRAMMING Page 6


CMR Institute of Technology Redefining Quality Education

Step 6: The installation has been processed.

Step 7: Click the Finish to complete the installation.

PYTHON PROGRAMMING Page 7


CMR Institute of Technology Redefining Quality Education

SETTING UP PATH TO P YTHON:


 Programs and other executable files can be in many directories, so operating
systems provide a search path that lists the directories that the OS searches for
executables.
 The path is stored in an environment variable, which is a named string maintained
by the operating system. This variable contains information available to the
command shell and other programs.
 Copy the Python installation location C:\Python27

 Right-click the My Computer icon on your desktop and choose Properties. And
then select Advanced System properties.

 Goto Environment Variables and go to System Variables select Path and


click on
EDIT.

PYTHON PROGRAMMING Page 8


CMR Institute of Technology Redefining Quality Education

 Copy the location C:\Python27 & give semicolon (;) & click OK.

PYTHON PROGRAMMING Page 9


CMR Institute of Technology Redefining Quality Education

How a Program Works: Python is an object oriented programming language like Java. Python is called
an interpreted language. Python uses code modules that are interchangeable instead of a single long list
of instructions that was standard for functional programming languages. The standard implementation of
python is called “cpython”. It is the default and widely used implementation of the Python.

Python doesn’t convert its code into machine code, something that hardware can understand. It actually
converts it into something called byte code. So within python, compilation happens, but it’s just not into
a machine language. It is into byte code and this byte code can’t be understood by CPU. So we need
actually an interpreter called the python virtual machine. The python virtual machine executes the byte
codes.

The Python interpreter performs following tasks to execute a Python program :

 Step 1 : The interpreter reads a python code or instruction. Then it verifies that the instruction is
well formatted, i.e. it checks the syntax of each line.If it encounters any error, it immediately
halts the translation and shows an error message.

 Step 2 : If there is no error, i.e. if the python instruction or code is well formatted then the
interpreter translates it into its equivalent form in intermediate language called “Byte code”.Thus,
after successful execution of Python script or code, it is completely translated into Byte code.

 Step 3 : Byte code is sent to the Python Virtual Machine(PVM).Here again the byte code is
executed on PVM.If an error occurs during this execution then the execution is halted with an
error message.

PYTHON PROGRAMMING Page 10


CMR Institute of Technology Redefining Quality Education

Using Python:

Running Python Interpreter:


Python comes with an interactive interpreter. When you type python in your shell or
command prompt, the python interpreter becomes active with a >>> prompt and waits for
your commands.

Now you can type any valid python expression at the prompt. Python reads the typed
expression, evaluates it and prints the result.

Running Python Scripts in IDLE:


 Goto File menu click on New File (CTRL+N) and write the code and save add.py
a=input("Enter a value ")
b=input("Enter b value ")
c=a+b
print "The sum is",c
 And run the program by pressing F5 or RunRun Module.

PYTHON PROGRAMMING Page 11


CMR Institute of Technology Redefining Quality Education

Running python scripts in Command Prompt:


 Before going to run we have to check the PATH in environment variables.
 Open your text editor, type the following text and save it as hello.py.
print "hello"
 And run this program by calling python hello.py. Make sure you change to the directory
where you saved the file before doing it.

Program Development Cycle:

Analyze->Design->Code->Test/Debug->Document

PYTHON PROGRAMMING Page 12


CMR Institute of Technology Redefining Quality Education

Input, Processing, and Output: A simple example to demonstrate all three.

Displaying Output with the Print Function:

We use the print() function or print keyword to output data to the standard output device
(screen). This function prints the object/string written in function.
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character. After all values
are printed, end is printed. It defaults into a new line ( \n ).

PYTHON PROGRAMMING Page 13


CMR Institute of Technology Redefining Quality Education

Reading Input from the Keyboard:

To get input from the user you can use the input function. When the input function is called the
program stops running the program, prompts the user to enter something at the keyboard by
printing a string called the prompt to the screen, and then waits for the user to press the Enter
key. The user types a string of characters and presses enter. Then the input function returns that
string and Python continues running the program by executing the next statement after the
input statement.
Python provides the function input(). input has an optional parameter, which is the prompt
string. For example

Comments: Comments in Python start with the hash character, # , and extend to the end of the
physical line. Acomment may appear at the start of a line or following whitespace or code, but
not within a string literal. A hash character within a string literal is just a hash character.

#This is a comment

#print out Hello

print('Hello')

Variables: Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space.
The declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
 A variable name must start with a letter or the underscore character

PYTHON PROGRAMMING Page 14


CMR Institute of Technology Redefining Quality Education

 A variable name cannot start with a number


 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)

The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For example

PYTHON PROGRAMMING Page 15


CMR Institute of Technology Redefining Quality Education

Multiple Assignments to variables:


Python allows you to assign a single value to several variables simultaneously.
For example –
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables.
For example –
a, b, c = 1, 2.5, ”mothi”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.

Operators: Operators are used to perform operations on variables and values. Python divides
the operators in the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Logical operators

 Identity operators

 Membership operators

 Bitwise operators

Python Arithmetic Operators: Arithmetic operators are used with numeric values to perform
common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

PYTHON PROGRAMMING Page 16


CMR Institute of Technology Redefining Quality Education

Python Assignment Operators: Assignment operators are used to assign values to variables

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators: Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

PYTHON PROGRAMMING Page 17


CMR Institute of Technology Redefining Quality Education

Python Logical Operators: Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

Python Identity Operators: Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory location:

Operator Description Example

is Returns true if both variables are x is y


the same object

is not Returns true if both variables are x is not y


not the same object

Python Membership Operators: Membership operators are used to test if a sequence is


presented in an object:

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the object

not in Returns True if a sequence with the x not in y


specified value is not present in the object

PYTHON PROGRAMMING Page 18


CMR Institute of Technology Redefining Quality Education

Python Bitwise Operators: Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits
shift fall off

>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
shift the rightmost bits fall off

Type conversions: Sometimes, you may need to perform conversions between the built-in
types. To convert between types, you simply use the type name as a function. For example, it is
not possible to perform “2”+4 since one operand is integer and the other is string type. To
perform this we have convert string to integer i.e., int(“2”) + 4 = 6.

There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

Function Description
int(x [,base]) Converts x to an integer.
long(x [,base] ) Converts x to a long integer.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary, d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

PYTHON PROGRAMMING Page 19


CMR Institute of Technology Redefining Quality Education

Expressions: An expression is a combination of variables constants and operators written


according to the syntax of Python language. In Python every expression evaluates to a value i.e.,
every expression results in some value of a certain type that can be assigned to a variable. Some
examples of Python expressions are shown in the table given below.

Algebraic Expression Python Expression

axb–c a*b–c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a*b/c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x/y+c

Decision Structures and Boolean Logic:

Decision making is anticipation of conditions occurring while execution of the


program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce True or False as
outcome. You need to determine which action to take and which statements to execute if
outcome is True or False otherwise.
Following is the general form of a typical decision making structure found in most of
the programming languages:

Python programming language assumes any non-zero and non-null values as True,
and if it is either zero or null, then it is assumed as False value.

Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements.
if...else statements if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
PYTHON PROGRAMMING Page 20
CMR Institute of Technology Redefining Quality Education

The if Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.

Syntax:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements given after
colon (:) are executed. We can write one or more statements after colon (:).

Example:
a=10
b=15
if a < b:
print “B is big” print
“B value is”,b
Output:
B is big
B value is 15
The if ... else statement
An else statement can be combined with an if statement. An else statement contains
the block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if condition:
statement(s)
else:
statement(s)
PYTHON PROGRAMMING Page 21
CMR Institute of Technology Redefining Quality Education

Example:
a=48
b=34
if a < b:
print “B is big” print
“B value is”, b
else:
print “A is big” print
“A value is”, a
print “END”
Output:
A is big
A value is 48
END
Q) Write a program for checking whether the given number is even or not.
Program:
a=input("Enter a value: ")
if a%2==0:
print "a is EVEN number"
else:
print "a is NOT EVEN Number"
Output-1: Output-2:
Enter a value: 56 Enter a value: 27
a is EVEN Number a is NOT EVEN Number

PYTHON PROGRAMMING Page 22


CMR Institute of Technology Redefining Quality Education

The 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.
Similar to the else, the elif statement is optional. However, unlike else, for which
there can be at most one statement, there can be an arbitrary number of elif statements
following an if.
Syntax: if condition1: statement(s)
elif condition2:
statement(s)
else:
statement(s)

Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a is big"
elif b >= a and b >= c:
print "b is big"

else:
Output:c is big print "c is big"

Comparing Strings: You can use ( > , < , <= , <= , == , != ) to compare two strings.
Python compares string lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Mary" and str2 as "Mac" . The first two characters
from str1 and str2 ( M and M ) are compared. As they are equal, the second two characters
are compared. Because they are also equal, the third two characters ( r and c ) are compared.
And because 'r' has greater ASCII value than 'c' , str1 is greater than str2 .
1 >>> "tim" == "tie"

2 False

3 >>> "free" != "freedom"

4 True

5 >>> "arrow" > "aron"

6 True

7 >>> "right" >= "left"

PYTHON PROGRAMMING Page 23


CMR Institute of Technology Redefining Quality Education

8 True

9 >>> "teeth" < "tee"

10 False

11 >>> "yellow" <= "fellow"

12 False

13 >>> "abc" > ""

14 True

15 >>>

Repetition Structures:

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. The following diagram illustrates a loop statement:

PYTHON PROGRAMMING Page 24


CMR Institute of Technology Redefining Quality Education

Python programming language provides following types of loops to handle looping


requirements.
Loop Type Description
Repeats a statement or group of statements while a given condition is
while loop
TRUE. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the
for loop
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for loop.

The while Loop


A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is True.
Syntax
The syntax of a while loop in Python programming language is:
while expression:
statement(s)

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.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

PYTHON PROGRAMMING Page 25


CMR Institute of Technology Redefining Quality Education

The for loop:

The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used
to execute a group of statements repeatedly depending upon the number of elements in the
sequence. The for loop can work with sequence like string, list, tuple, range etc.

The syntax of the for loop is given below:

for var in sequence:

statement (s)

The first element of the sequence is assigned to the variable written after „for‟ and then the
statements are executed. Next, the second element of the sequence is assigned to the variable and
then the statements are executed second time. In this way, for each element of the sequence, the
statements are executed once. So, the for loop is executed as many times as there are number of
elements in the sequence.

Nested Loop:
It is possible to write one loop inside another loop. For example, we can write a for loop inside a
while loop or a for loop inside another for loop. Such loops are called “nested loops”.

Example-1:
for i in range(1,6):
for j in range(1,6):

print j,
print ""
Example-2:
for i in range(1,6):
for j in range(1,6):

print
"*", print ""

Example-3:
for i in range(1,6):
for j in range(1,6):

if i==1 or j==1 or i==5 or j==5:


print "*",

else:

print " ",


PYTHON PROGRAMMING print "" Page 26
CMR Institute of Technology Redefining Quality Education

Strings: String literals in python are surrounded by either single quotation marks, or double
quotation marks.

'hello' is the same as "hello".

Strings can be output to screen using the print function. For example: print("hello").

Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, 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.

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Output: e

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Output: llo

Numeric Data Types: There are three numeric types in Python:

 int

 float

 complex

Variables of numeric types are created when you assign a value to them:

Example

x = 1 # int
y = 2.8 # float
z = 1j # complex

PYTHON PROGRAMMING Page 27


CMR Institute of Technology Redefining Quality Education

Character Sets: Python uses the traditional ASCII character set. The latest version (2.7) also
recognizes the Unicode character set. The ASCII character set is a subset of the Unicode character
set.

Functions and Modules:

A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.

Creating a Function:

In Python a function is defined using the def keyword:

Example

def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function():
print("Hello from a function")

my_function()

Module: 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.

Create a Module To create a module just save the code you want in a file with the file
extension .py:

Example Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module Now we can use the module we just created, by using the import statement:

Example Import the module named mymodule, and call the greeting function:
import mymodule

mymodule.greeting("Jonathan")

PYTHON PROGRAMMING Page 28


CMR Institute of Technology Redefining Quality Education

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

Example

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

PYTHON PROGRAMMING Page 29


CMR Institute of Technology Redefining Quality Education

UNIT-2

Definite Iteration: Conceptually, we distinguish two types of loops, which differ in the way in
which the number of iterations (i.e., repetitions of the body of the loop) is determined:

 In definite loops, the number of iterations is known before we start the execution of the
body of the loop.

Example: repeat for 10 times printing out a *.

 In indefinite loops, the number of iterations is not known before we start to execute the
body of the loop, but depends on when a certain condition becomes true (and this depends
on what happens in the body of the loop)

Example: while the user does not decide it is time to stop, print out a * and ask the user whether he
wants to stop.

Formatting Text for Output: There are several ways to present the output of a program, data can
be printed in a human-readable form, or written to a file for future use. Sometimes user often wants
more control the formatting of output than simply printing space-separated values. There are
several ways to format output.

 To use formatted string literals, begin a string with f or F before the opening quotation mark
or triple quotation mark.

 The str.format() method of strings help a user to get a fancier Output

 User can do all the string handling by using string slicing and concatenation operations to
create any layout that user wants. The string type has some methods that perform useful
operations for padding strings to a given column width.

Formatting output using String modulo operator(%) :


The % operator can also be used for string formatting. It interprets the left argument much like
a printf()-style format string to be applied to the right argument. In Python, there is no printf()
function but the functionality of the ancient printf is contained in Python. To this purpose, the
modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is
often called string modulo (or sometimes even called modulus) operator.
String modulo operator ( % ) is still available in Python(3.x) and user is using it widely. But
nowadays the old style of formatting is removed from the language.

# Python program showing how to use string modulo operator(%) to print fancier output

PYTHON PROGRAMMING Page 30


CMR Institute of Technology Redefining Quality Education

# print integer and float value

print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))

# print integer value

print("Total students : % 3d, Boys : % 2d" %(240, 120))

# print octal value

print("% 7.3o"% (25))

# print exponential value

print("% 10.3E"% (356.08977))

Output :

Geeks : 1, Portal : 5.33

Total students : 240, Boys : 120

031

3.561E+02

File and Exceptions: File handling is an important part of any web application. Python has several
functions for creating, reading, updating, and deleting files.

File Handling The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode. There are 4 different methods
(modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:

PYTHON PROGRAMMING Page 31


CMR Institute of Technology Redefining Quality Education

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.

Introduction to File Input and Output:

Reading Files: The open() function returns a file object, which has a read() method for reading the
content of the file:

Example

f = open("demofile.txt", "r")
print(f.read())

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters
you want to return:

Example

Return the 5 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(5))

Read Lines You can return one line by using the readline() method:

Example

Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:

PYTHON PROGRAMMING Page 32


CMR Institute of Technology Redefining Quality Education

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file, line by line:

Example

Loop through the file line by line:

f = open("demofile.txt", "r")
for x in f:
print(x)

Write to an Existing File: To write to an existing file, you must add a parameter to
the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

Create a New File: To create a new file in Python, use the open() method, with one of the
following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example

Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Result: a new empty file is created!

PYTHON PROGRAMMING Page 33


CMR Institute of Technology Redefining Quality Education

Example

Create a new file if it does not exist:

f = open("myfile.txt", "w")

Using Loops to Process Files: When you are typing a Python program and you press the enter or
return key on your keyboard, the editor inserts a newline character into your text at that point.

As the for loop iterates through each line of the file the loop variable will contain the current line of
the file as a string of characters. The general pattern for processing each line of a text file is as
follows:

for line in myFile:

statement1

statement2

...

Processing Records: To process all of our quarterback data, we will use a for loop to iterate over
the lines of the file. Using the split method, we can break each line into a list containing all the
fields of interest about the quarterback. We can then take the values corresponding to first name,
lastname, and passer rating to construct a simple sentence.

qbfile = open("qbdata.txt", "r")

for aline in qbfile:

values = aline.split()

print('QB ', values[0], values[1], 'had a rating of ', values[10] )

qbfile.close()

Exceptions:

Exceptions:
 An exception is a runtime error which can be handled by the programmer.
 That means if the programmer can guess an error in the program and he can do something to
eliminate the harm caused by that error, then it is called an „exception‟.
 If the programmer cannot do anything in case of an error, then it is called an „error‟ and not
an exception.
 All exceptions are represented as classes in python. The exceptions which are already
PYTHON PROGRAMMING Page 34
CMR Institute of Technology Redefining Quality Education

available in python are called „built-in‟ exceptions. The base class for all built-in exceptions
is „BaseException‟ class.
 From BaseException class, the sub class „Exception‟ is derived. From Exception class,
the sub classes „StandardError‟ and „Warning‟ are derived.
 All errors (or exceptions) are defined as sub classes of StandardError. An error should be
compulsory handled otherwise the program will not execute.
 Similarly, all warnings are derived as sub classes from „Warning‟ class. A warning represents
a caution and even though it is not handled, the program will execute. So, warnings can be
neglected but errors cannot neglect.
 Just like the exceptions which are already available in python language, a programmer can
also create his own exceptions, called „user-defined‟ exceptions.
 When the programmer wants to create his own exception class, he should derive his class
from Exception class and not from „BaseException‟ class.

Exception Handling:
 The purpose of handling errors is to make the program robust. The word „robust‟
means
„strong‟. A robust program does not terminate in the middle.
 Also, when there is an error in the program, it will display an appropriate message
to the user and continue execution.
 Designing such programs is needed in any software development.
 For that purpose, the programmer should handle the errors. When the errors can be
handled, they are called exceptions.
To handle exceptions, the programmer should perform the following four steps:
Step 1: The programmer should observe the statements in his program where there may be a
possibility of exceptions. Such statements should be written inside a „try‟ block. A try block looks
like as follows:
try:
statements
The greatness of try block is that even if some exception arises inside it, the program will not be
terminated. When PVM understands that there is an exception, it jumps into an
„except‟ block.
PYTHON PROGRAMMING Page 35
CMR Institute of Technology Redefining Quality Education

Step 2: The programmer should write the „except‟ block where he should display the
exception details to the user. This helps the user to understand that there is some error in the
program. The programmer should also display a message regarding what can be done to avoid
this error. Except block looks like as follows:
except exceptionname:
statements
The statements written inside an except block are called „handlers‟ since they handle the
situation when the exception occurs.
Step 3: If no exception is raised, the statements inside the „else‟ block is executed. Else block
looks like as follows:
else:
statements
Step 4: Lastly, the programmer should perform clean up actions like closing the files and
terminating any other processes which are running. The programmer should write this code in the
finally block. Finally block looks like as follows:
finally: statements
The speciality of finally block is that the statements inside the finally block are executed
irrespective of whether there is an exception or not. This ensures that all the opened files are
properly closed and all the running processes are properly terminated. So, the data in the files will
not be corrupted and the user is at the safe-side.
Here, the complete exception handling syntax will be in the following format:
try:
statements except Exception1:
statements except Exception2:
statements else:
statements finally:
statements
The following points are followed in exception handling:
 A single try block can be followed by several except blocks.
 Multiple except blocks can be used to handle multiple exceptions.
 We cannot write except blocks without a try block.
 We can write a try block without any except blocks.
 Else block and finally blocks are not compulsory.
 When there is no exception, else block is executed after try block.
 Finally block is always executed.

Example: A python program to handle IOError produced by open() function.


import sys try:
f = open('myfile.txt','r') s = f.readline()
print s f.close()
except IOError as e:
print "I/O error", e.strerror except:
print "Unexpected error:"
Output:
I/O error No such file or directory

In the if the file is not found, then IOError is raised. Then „except‟ block will display a message:
„I/O error‟. if the file is found, then all the lines of the file are read using readline()
method.

PYTHON PROGRAMMING Page 36


CMR Institute of Technology Redefining Quality Education

List of Standard Exceptions


Exception Name Description
Exception Base class for all exceptions
Raised when the next() method of an iterator does not point to
StopIteration
any object.
SystemExit Raised by the sys.exit() function.
Base class for all built-in exceptions except StopIteration and
StandardError
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
Raised when a calculation exceeds maximum limit for a
OverflowError
numeric type.
FloatingPointError Raised when a floating point calculation fails.
Raised when division or modulo by zero takes place for all
ZeroDivisionError
numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
Raised when there is no input from either the raw_input() or
EOFError
input() function and the end of file is reached.
ImportError Raised when an import statement fails.
Raised when the user interrupts program execution, usually by
KeyboardInterrupt
pressing Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
Raised when an identifier is not found in the local or global
NameError
namespace.
Raised when trying to access a local variable in a function or
UnboundLocalError
method but no value has been assigned to it.
Base class for all exceptions that occur outside the Python
EnvironmentError
environment.
Raised when an input/ output operation fails, such as the print
IOError statement or the open() function when trying to open a file that
does not exist.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
Raised when the interpreter finds an internal problem, but when
SystemError
this error is encountered the Python interpreter does not exit.
Raised when Python interpreter is quit by using the sys.exit()
SystemExit function. If not handled in the code, causes the interpreter to
exit.
Raised when an operation or function is attempted that is
TypeError
invalid for the specified data type.
Raised when the built-in function for a data type has the valid
ValueError type of arguments, but the arguments have invalid values
specified.
RuntimeError Raised when a generated error does not fall into any category.
Raised when an abstract method that needs to be implemented
NotImplementedError
in an inherited class is not actually implemented.

PYTHON PROGRAMMING Page 37


CMR Institute of Technology Redefining Quality Education

The Except Block:


The „except‟ block is useful to catch an exception that is raised in the try block. When there is an
exception in the try block, then only the except block is executed. it is written in various formats.
1. To catch the exception which is raised in the try block, we can write except block
with the Exceptionclass name as:
except Exceptionclass:
2. We can catch the exception as an object that contains some description about the
exception.
except Exceptionclass as obj:
3. To catch multiple exceptions, we can write multiple catch blocks. The other way
is to use a single except block and write all the exceptions as a tuple inside
parantheses as:
except (Exceptionclass1, Exceptionclass2, ....):
4. To catch any type of exception where we are not bothered about which type of
exception it is, we can write except block without mentioning any Exceptionclass
name as:
except:
Example:
try:
f = open('myfile.txt','w')
a=input("Enter a value ")
b=input("Enter a value ")
c=a/float(b)
s = f.write(str(c))
print “Result is stored” except
ZeroDivisionError:
print "Division is not possible" except:
print "Unexpected error:" finally:
lose()

Enter a value 1 Enter


Output: a value 5 Result is
stored

Raising an Exception
You can raise exceptions in several ways by using the raise statement. The general syntax for the
raise statement is as follows.
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (For example, NameError) and argument is a value for
the exception argument. The argument is optional; if not supplied, the exception argument is
None.
For Example, If you need to determine whether an exception was raised but don‟t intend to
handle it, a simpler form of the raise statement allows you to re-raise the exception:
try:
raise NameError('HiThere') except NameError:
print 'An exception flew by!' raise

PYTHON PROGRAMMING Page 38


CMR Institute of Technology Redefining Quality Education

User-Defined Exceptions:
 Like the built-in exceptions of python, the programmer can also create his own
exceptions which are called „User-defined exceptions‟ or „Custom exceptions‟. We
know Python offers many exceptions which will raise in different contexts.
 But, there may be some situations where none of the exceptions in Python are
useful for the programmer. In that case, the programme has to create his/her own
exception and raise it.
 For example, let‟s take a bank where customers have accounts. Each
account is characterized should by customer name and balance amount.
 The rule of the bank is that every customer should keep minimum Rs. 2000.00 as
balance amount in his account.
 The programmer now is given a task to check the accounts to know every customer
is maintaining minimum balance of Rs. 2000.00 or not.
 If the balance amount is below Rs. 2000.00, then the programmer wants to raise an
exception saying „Balance amount is less in the account of so and so person.‟ This
will be helpful to the bank authorities to find out the customer.
 So, the programmer wants an exception that is raised when the balance amount in
an account is less than Rs. 2000.00. Since there is no such exception available in
python, the programme has to create his/her own exception.
 For this purpose, he/she has to follow these steps:

1. Since all exceptions are classes, the programme is supposed to create his own
exception as a class. Also, he should make his class as a sub class to the
in-built
„Exception‟ class.
class MyException(Exception): def init (self, arg):
self.msg = arg
Here, MyException class is the sub class for „Exception‟ class. This class has a constructor
where a variable „msg‟ is defined. This „msg‟ receives a message passed from outside through
„arg‟.

2. The programmer can write his code; maybe it represents a group of statements or
a function. When the programmer suspects the possibility of exception, he
should raise his own exception using „raise‟ statement as:
raise MyException(‘message’)
Here, raise statement is raising MyException class object that contains the given
„message‟.

3. The programmer can insert the code inside a „try‟ block and catch the exception
using
„except‟ block as:
try:
code
except MyException as me: print me

Here, the object „me‟ contains the message given in the raise statement. All these steps are
shown in below program.

PYTHON PROGRAMMING Page 39


CMR Institute of Technology Redefining Quality Education

class MyException(Exception): def init (self, arg):


self.msg = arg def check(dict):
for k,v in dict.items():
print "Name=",k,"Balance=",v if v<2000.00:
raise MyException("Balance amount is less in the account of "+k)

bank={"ravi":5000.00,"ramu":8500.00,"raju":1990.00} try:
check(bank)
except MyException as me: print me.msg
Output:
Name= ramu Balance= 8500.0
Name= ravi Balance= 5000.0
Name= raju Balance= 1990.0
Balance amount is less in the account of raju

Functions:A function is a block of organized, reusable code that is used to perform a single,
related action.

 Once a function is written, it can be reused as and when required. So, functions are also called
reusable code.

 Functions provide modularity for programming. A module represents a part of the program.
Usually, a programmer divides the main task into smaller sub tasks called modules.

 Code maintenance will become easy because of functions. When a new feature has to be added
to the existing software, a new function can be written and integrated into the software.

 When there is an error in the software, the corresponding function can be modified without
disturbing the other functions in the software.

 The use of functions in a program will reduce the length of the program.

As you already know, Python gives you many built-in functions like sqrt( ), etc. but you can also
create your own functions. These functions are called user-defined functions.

Difference between a function and a method:

A function can be written individually in a python program. A function is called using its name.
When a function is written inside a class, it becomes a „method‟. A method is called using object
name or class name. A method is called using one of the following ways:

Objectname.methodname() Classname.methodname()

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
PYTHON PROGRAMMING Page 58
CMR Institute of Technology Redefining Quality Education

 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. You can also
define parameters inside these parentheses.

 The first statement of a function can be an optional statement - the documentation string of the
function or docstring.

 The code block within every function starts with a colon (:) and is indented.

 The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return none.

Syntax:

def functionname (parameters):


"""function_docstring"""
function_suite

return [expression]

PYTHON PROGRAMMING Page 59


CMR Institute of Technology Redefining Quality Education

By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.

Example:

def add(a,b):

"""This function sum the numbers""" c=a+b

print c return

Here, „def’ represents starting of function. „add’ is function name. After this name, parentheses ( )
are compulsory as they denote that it is a function and not a variable or something else. In the
parentheses we wrote two variables „a‟ and „b‟ these variables are called „parameters‟. A
parameter is a variable that receives data from outside a function. So, this function receives two
values from outside and those are stored in the variables „a‟ and

„b‟. After parentheses, we put colon (:) that represents the beginning of the function body. The
function body contains a group of statements called „suite‟.

Calling Function:

A function cannot run by its own. It runs only when we call it. So, the next step is to call function
using its name. While calling the function, we should pass the necessary values to the function in
the parentheses as:

add(5,12)

Here, we are calling „add‟ function and passing two values 5 and 12 to that function. When this
statement is executed, the python interpreter jumps to the function definition and copies the values
5 and 12 into the parameters „a‟ and „b‟ respectively.

Example:

def add(a,b):

"""This function sum the numbers"""


c=a+b

print c
add(5,12) # 17

PYTHON PROGRAMMING Page 60


CMR Institute of Technology Redefining Quality Education

Returning Results from a function:

We can return the result or output from the function using a „return‟ statement in the function
body. When a function does not return any result, we need not write the return statement in the
body of the function.

Q) Write a program to find the sum of two numbers and return the result from the function.

def add(a,b):

"""This function sum the numbers"""


c=a+b

return c
print add(5,12) #17

print add(1.5,6) #6.5

PYTHON PROGRAMMING Page 61


CMR Institute of Technology Redefining Quality Education

Returning multiple values from a function:

A function can returns a single value in the programming languages like C, C++ and JAVA. But, in
python, a function can return multiple values. When a function calculates multiple results and
wants to return the results, we can use return statement as:

return a, b, c

Here, three values which are in „a‟, „b‟ and „c‟ are returned. These values are returned by the
function as a tuple. To grab these values, we can three variables at the time of calling the
function as:

x, y, z = functionName( )

Here, „x‟, „y‟ and „z‟ are receiving the three values returned by the function.

Pass by Value:
Pass by value represents that a copy of the variable value is passed to the function and any
modifications to that value will not reflect outside the function. In python, the values are sent to
functions by means of object references. We know everything is considered as an object in
python. All numbers, strings, tuples, lists and dictionaries are objects.
If we store a value into a variable as:
x=10
In python, everything is an object. An object can be imagined as a memory block where we can
store some value. In this case, an object with the value „10‟ is created in memory for which
a name „x‟ is attached. So, 10 is the object and „x‟ is the name or tag given to that object. Also,
objects are created on heap memory which is a very huge memory that depends on the RAM of
our computer system.
Example: A Python program to pass an integer to a function and modify it. def
modify(x):
x=15
print "inside",x,id(x) x=10
modify(x)
print "outside",x,id(x)
Output:
inside 15 6356456
outside 10 6356516
From the output, we can understand that the value of „x‟ in the function is 15 and that is not
available outside the function. When we call the modify( ) function and pass „x‟ as:
modify(x)
We should remember that we are passing the object references to the modify( ) function. The
object is 10 and its references name is „x‟. This is being passed to the modify( ) function. Inside
the function, we are using:
x=15

PYTHON PROGRAMMING Page 62


CMR Institute of Technology Redefining Quality Education

This means another object 15 is created in memory and that object is referenced by the name „x‟.
The reason why another object is created in the memory is that the integer objects are immutable
(not modifiable). So in the function, when we display „x‟ value, it will display 15. Once we come
outside the function and display „x‟ value, it will display numbers of „x‟ inside and outside the
function, and we see different numbers since they are different objects.
In python, integers, floats, strings and tuples are immutable. That means their data cannot be
modified. When we try to change their value, a new object is created with the modified value.

Fig. Passing Integer to a Function


Pass by Reference:
Pass by reference represents sending the reference or memory address of the variable to the
function. The variable value is modified by the function through memory address and hence the
modified value will reflect outside the function also.
In python, lists and dictionaries are mutable. That means, when we change their data, the same
object gets modified and new object is not created. In the below program, we are passing a list of
numbers to modify ( ) function. When we append a new element to the list, the same list is
modified and hence the modified list is available outside the function also.
Example: A Python program to pass a list to a function and modify it. def
modify(a):
a.append(5)
print "inside",a,id(a) a=[1,2,3,4]
modify(a)
print "outside",a,id(a)
Output:
inside [1, 2, 3, 4, 5] 45355616
outside [1, 2, 3, 4, 5] 45355616
In the above program the list „a‟ is the name or tag that represents the list object.
Before calling the modify( ) function, the list contains 4 elements as: a=[1,2,3,4]
Inside the function, we are appending a new element „5‟ to the list. Since, lists are mutable,
adding a new element to the same object is possible. Hence, append( ) method modifies the same
object.

PYTHON PROGRAMMING Page 63


CMR Institute of Technology Redefining Quality Education

Fig. Passing a list to the function


Formal and Actual Arguments:
When a function is defined, it may have some parameters. These parameters are useful to receive
values from outside of the function. They are called „formal arguments‟. When we call the
function, we should pass data or values to the function. These values are called „actual
arguments‟. In the following code, „a‟ and „b‟ are formal arguments and „x‟ and
„y‟ are actual arguments.
Example:
def add(a,b): # a, b are formal arguments c=a+b
print c x,y=10,15
add(x,y) # x, y are actual arguments

The actual arguments used in a function call are of 4 types:


a) Positional arguments
b) Keyword arguments
c) Default arguments
d) Variable length arguments
a) Positional Arguments:
These are the arguments passed to a function in correct positional order. Here, the number of
arguments and their position in the function definition should match exactly with the number and
position of argument in the function call.
def attach(s1,s2): s3=s1+s2
print s3
attach("New","Delhi") #Positional arguments
This function expects two strings that too in that order only. Let‟s assume that this function
attaches the two strings as s1+s2. So, while calling this function, we are supposed to pass only
two strings as: attach("New","Delhi")

PYTHON PROGRAMMING Page 64


CMR Institute of Technology Redefining Quality Education

The preceding statements displays the following output NewDelhi


Suppose, we passed "Delhi" first and then "New", then the result will be: "DelhiNew". Also, if
we try to pass more than or less than 2 strings, there will be an error.

b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names. For example, the
definition of a function that displays grocery item and its price can be written as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which value
is for what. For example,
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword „item‟ and its value and then another keyword „price‟ and its
value. Please observe these keywords are nothing but the parameter names which receive these
values. We can change the order of the arguments as:
grocery(price=88.00, item=’oil’)
In this way, even though we change the order of the arguments, there will not be any problem as
the parameter names will guide where to store that value.

def grocery(item,price):
print "item=",item print
"price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
Output:
item= sugar price=
50.75 item= oil price=
88.0
c) Default Arguments:
We can mention some default value for the function parameters in the definition.
Let‟s take the definition of grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the second
argument is „price‟ and its default value is mentioned to be 40.00. at the time of calling this
function, if we do not pass „price‟ value, then the default value of 40.00 is taken. If we
mention the „price‟ value, then that mentioned value is utilized. So, a default argument is an
argument that assumes a default value if a value is not provided in the function call for that
argument.
Example: def grocery(item,price=40.00):
print "item=",item print
"price=",price
grocery(item="sugar",price=50.75)
grocery(item="oil")

PYTHON PROGRAMMING Page 65


CMR Institute of Technology Redefining Quality Education

Output:
item= sugar price=
50.75 item= oil price=
40.0
d) Variable Length Arguments:
Sometimes, the programmer does not know how many values a function may receive. In that
case, the programmer cannot decide how many arguments to be given in the function definition.
for example, if the programmer is writing a function to add two numbers, he/she can write:
add(a,b)
But, the user who is using this function may want to use this function to find sum of three
numbers. In that case, there is a chance that the user may provide 3 arguments to this function as:
add(10,15,20)
Then the add( ) function will fail and error will be displayed. If the programmer want to develop
a function that can accept „n‟ arguments, that is also possible in python. For this purpose, a
variable length argument is used in the function definition. a variable length argument is an
argument that can accept any number of values. The variable length argument is written with a
„*‟ symbol before it in the function definition as:
def add(farg, *args):
here, „farg‟ is the formal; argument and „*args‟ represents variable length argument. We can pass
1 or more values to this „*args‟ and it will store them all in a tuple.
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print "sum is",sum+farg
add(5,10)
add(5,10,20)
Output:
add(5,10,20,30)
sum is 15
sum is 35
sum is 65

Local and Global Variables:


When we declare a variable inside a function, it becomes a local variable. A local variable is a
variable whose scope is limited only to that function where it is created. That means the local
variable value is available only in that function and not outside of that function.

PYTHON PROGRAMMING Page 66


CMR Institute of Technology Redefining Quality Education

When the variable ‘a’ is declared inside myfunction() and hence it is available inside that
function. Once we come out of the function, the variable „a‟ is removed from memory and it is
not available.
Example-1:
def myfunction(): a=10
print "Inside function",a #display 10 myfunction()
print "outside function",a # Error, not available
Output:
Inside function 10 outside
function
NameError: name 'a' is not defined
When a variable is declared above a function, it becomes global variable. Such variables are
available to all the functions which are written after it.
Example-2:
a=11
def myfunction(): b=10
print "Inside function",a #display global var print "Inside
function",b #display local var
myfunction()
print "outside function",a # available print
"outside function",b # error
Output:
Inside function 11
Inside function 10
outside function 11 outside
function
NameError: name 'b' is not defined The
Global Keyword:
Sometimes, the global variable and the local variable may have the same name. In that case, the
function, by default, refers to the local variable and ignores the global variable. So, the global
variable is not accessible inside the function but outside of it, it is accessible.
Example-1:
a=11
def myfunction(): a=10
print "Inside function",a # display local variable myfunction()
print "outside function",a # display global variable
Output:
Inside function 10
outside function 11
When the programmer wants to use the global variable inside a function, he can use the keyword
„global‟ before the variable in the beginning of the function body as:
global a

PYTHON PROGRAMMING Page 67


CMR Institute of Technology Redefining Quality Education

Example-2:
a=11
def myfunction(): global a
a=10
print "Inside function",a # display global variable myfunction()
print "outside function",a # display global variable
Output:
Inside function 10
outside function 10
Recursive Functions:
A function that calls itself is known as „recursive function‟. For example, we can write the
factorial of 3 as:
factorial(3) = 3 * factorial(2) Here,
factorial(2) = 2 * factorial(1) And, factorial(1)
= 1 * factorial(0)
Now, if we know that the factorial(0) value is 1, all the preceding statements will evaluate and
give the result as:
factorial(3) = 3 * factorial(2)
= 3 * 2 * factorial(1)
= 3 * 2 * 1 * factorial(0)
=3*2*1*1
=6
From the above statements, we can write the formula to calculate factorial of any number „n‟ as:
factorial(n) = n * factorial(n-1)
Example-1:
def factorial(n): if n==0:
result=1 else:
result=n*factorial(n-1) return result
for i in range(1,5):
print "factorial of ",i,"is",factorial(i)
Output:
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24

Generating random numbers in python: In Python, just like in almost any other OOP language,
chances are that you'll find yourself needing to generate a random number at some point. Whether
you're just completing an exercise in algorithms to better familiarize yourself with the language, or
if you're trying to write more complex code, you can't call yourself a Python coder without
knowing how to generate random numbers.

PYTHON PROGRAMMING Page 68


CMR Institute of Technology Redefining Quality Education

Check out the code snippet below to see how it works to generate a number between 1 and 100.

import random

for x in range(10):

print random.randint(1,101)

The code above will print 10 random values of numbers between 1 and 100. The second line, for x
in range(10), determines how many values will be printed (when you use range(x), the number that
you use in place of x will be the amount of values that you'll have printed. if you want 20 values,
use range(20). use range(5) if you only want 5 values returned, etc.). Then the third line: print
random.randint(1,101) will automatically select a random integer between 1 and 100 for you. The
process is fairly simple.

What if, however, you wanted to select a random integer that was between 1 and 100 but also a
multiple of five? This is a little more complicated. The process is the same, but you'll need to use a
little more arithmetic to make sure that the random integer is in fact a multiple of five. Check out
the code below:

import random

for x in range(10):

print random.randint(1,21)*5,

print

Basically this code will generate a random number between 1 and 20, and then multiply that
number by 5. So not only will every number printed be a multiple of 5, but the highest number that
can be printed is 100 (20*5=100). Play around with the code yourself and see if you can generate a
random number between 1-100 where every number generated is a multiple of ten!

The math Module: The math module is a standard module in Python & is always available. To
use mathematical functions under this module, you must import the module using import math.

Function Descriptio
n
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x

PYTHON PROGRAMMING Page 69


CMR Institute of Technology Redefining Quality Education

fmod(x, y) Returns the remainder when x is divided by y


frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable) Returns an accurate floating point sum of values in the iterable
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number)
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x - 1
log(x[, base]) Returns the logarithm of x to the base (defaults to e)
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
Returns the natural logarithm of the absolute value of the Gamma
lgamma(x)
function at x
Mathematical constant, the ratio of circumference of a circle to it's
pi
diameter (3.14159...)
e mathematical constant e (2.71828...)
Storing Functions in Modules: A module is a file containing Python definitions and statements.
The file name is the module name with the suffix.py appended. Within a module, the module‟s
name (as a string) is available as the value of the global variable __name . For instance, use your

PYTHON PROGRAMMING Page 70


CMR Institute of Technology Redefining Quality Education

favourite text editor to create a file called fibo.py in the current directory with the following
contents:

# Fibonacci numbers module

def fib(n): # write Fibonacci series up to n a, b = 0, 1

while b < n: print b,

a, b = b, a+b

def fib2(n): # return Fibonacci series up to n result = []

a, b = 0, 1

while b < n: result.append(b) a, b = b, a+b

return result

Now enter the Python interpreter and import this module with the following command:

>>> import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol table;
it only enters the module name fibo there. Using the module name you can access the functions:

>>> fibo.fib(1000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

>>> fibo.fib2(100)

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

>>> fibo. name 'fibo'

PYTHON PROGRAMMING Page 71


CMR Institute of Technology Redefining Quality Education

from statement:

 A module can contain executable statements as well as function definitions. These


statements are intended to initialize the module. They are executed only the first time the
module name is encountered in an import statement. (They are also run if the file is executed
as a script.)

 Each module has its own private symbol table, which is used as the global symbol table by
all functions defined in the module. Thus, the author of a module can use global variables in
the module without worrying about accidental clashes with a user‟s global variables. On the
other hand, if you know what you are doing you can touch a module‟s global variables with
the same notation used to refer to its functions, modname.itemname.

 Modules can import other modules. It is customary but not required to place all import
statements at the beginning of a module (or script, for that matter). The imported module
names are placed in the importing module‟s global symbol table.

 There is a variant of the import statement that imports names from a module directly into the
importing module‟s symbol table. For example:

>>> from fibo import fib, fib2

>>> fib(500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol
table (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

>>> from fibo import *

>>> fib(500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

PYTHON PROGRAMMING Page 72


CMR Institute of Technology Redefining Quality Education

UNIT-3

Strings: Accessing Characters and Substrings in a String: String literals in python are
surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

Strings can be output to screen using the print function. For example: print("hello").

Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, 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.

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Output: e

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Output: llo

String Methods, Basic String Operations:

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

PYTHON PROGRAMMING Page 73


CMR Institute of Technology Redefining Quality Education

find() Searches the string for a specified value and returns the position of where it was
found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was
found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it
was found

PYTHON PROGRAMMING Page 74


CMR Institute of Technology Redefining Quality Education

rindex() Searches the string for a specified value and returns the last position of where it
was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

Note: All string methods returns new values. They do not change the original string.

Python Number Systems : The python number system is representing the way of using the
below numbers in Language.

 Binary Number System


 Octal Number System
 Decimal Number System
 Hexadecimal Number System

Let’s see one by one, how these are used in the python language.

Binary Number System:

In general, a binary number represents a 0 or 1 in the system.

The base or radix of the binary number system is 2.

The possible digits that are used in a binary number system are 0 and 1.

PYTHON PROGRAMMING Page 75


CMR Institute of Technology Redefining Quality Education

If we wanted to store a binary number in python variable, that number should sharts with 0b.

Example: Python binary Number System

x = 0b1010

print('Value is : ',x)

Output: (Value is : 10)

Note: we can not give the x=ob1020 since binary numbers contain only 0 and 1. If so we will
get an error message like SyntaxError: invalid syntax.

Octal Number System:

The base or radix of the octal number system is 8.

The possible digits that are used in the octal number system are 0 to 7.

To represent an octal number in Python, the number should start with 0 (python2) or ox
(python3).

Example: Python octal Number System

x=0123

print('Value is : '+x)

Output: (Value is : 83)

Note: we can not give the x=o180 since octal numbers contain from 0 to 7. If so we will get an
error message like SyntaxError: invalid token.

Decimal Number System :

The base or radix of the decimal number system is 10.

The possible digits that are used in the decimal number system are 0 to 9.

The default number system followed by python is the decimal number system.

x=1234

print('Value is : '+x)

Output: (Value is : 1234)

PYTHON PROGRAMMING Page 76


CMR Institute of Technology Redefining Quality Education

Note: we can not give the x=1234p since the decimal numbers contain from 0 to 9. If so we will
get an error message like SyntaxError: invalid syntax.

Hexadecimal Number System :

The base or radix of the hexadecimal number system is 16.

The possible digits that are used in hexadecimal number systems are 0 to 9 and a to f.

To represent a hexadecimal number in Python, the number should start with 0x.

x=0x25

print('Value is :'+x)

Output: (Value is : 37)

String Slicing: Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters. However, 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.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"

print(a[1])

Example

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"

print(b[2:5])

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "

print(a.strip()) # returns "Hello, World!"

PYTHON PROGRAMMING Page 77


CMR Institute of Technology Redefining Quality Education

Lists, Introduction to Lists: There are four collection data types in the Python programming
language:

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

 Set is a collection which is unordered and unindexed. No duplicate members.

 Dictionary is a collection which is unordered, changeable and indexed. No duplicate


members.

When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.

List: A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.

Example

Create a List:

thislist = ["apple", "banana", "cherry"]

print(thislist)

Output: ['apple', 'banana', 'cherry']

Access Items: You access the list items by referring to the index number:

Example

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]

print(thislist[1])

Change Item Value: To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"

PYTHON PROGRAMMING Page 78


CMR Institute of Technology Redefining Quality Education

print(thislist)

List slicing: After getting the list, we can get a part of it using python’s slicing operator which
has following syntax :

[start : stop : steps]

which means that slicing will start from index start will go up to stop in step of steps.

Default value of start is 0, stop is last index of list

and for step it is 1

So [: stop] will slice list from starting till stop index and [start : ] will slice list from start index
till end Negative value of steps shows right to left traversal instead of left to right traversal that
is why [: : -1] prints list in reverse order.

# Let us first create a list to demonstrate slicing

# lst contains all number from 1 to 10

lst = range(1, 11)

print lst

# below list has numbers from 2 to 5

lst1_5 = lst[1 : 5]

print lst1_5

# below list has numbers from 6 to 8

lst5_8 = lst[5 : 8]

print lst5_8

# below list has numbers from 2 to 10

lst1_ = lst[1 : ]

print lst1_

PYTHON PROGRAMMING Page 79


CMR Institute of Technology Redefining Quality Education

# below list has numbers from 1 to 5

lst_5 = lst[: 5]

print lst_5

# below list has numbers from 2 to 8 in step 2

lst1_8_2 = lst[1 : 8 : 2]

print lst1_8_2

# below list has numbers from 10 to 1

lst_rev = lst[ : : -1]

print lst_rev

# below list has numbers from 10 to 6 in step 2

lst_rev_9_5_2 = lst[9 : 4 : -2]

print lst_rev_9_5_2

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[2, 3, 4, 5]

[6, 7, 8]

[2, 3, 4, 5, 6, 7, 8, 9, 10]

[1, 2, 3, 4, 5]

[2, 4, 6, 8]

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

[10, 8, 6]

PYTHON PROGRAMMING Page 80


CMR Institute of Technology Redefining Quality Education

Finding Items in Lists with the in Operator: To determine if a specified item is present in a
list use the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")

List Methods and Useful Built-in Functions:

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Copying Lists:

o actually copy the list, you have various possibilities:

PYTHON PROGRAMMING Page 81


CMR Institute of Technology Redefining Quality Education

 You can use the builtin list.copy() method (available since Python 3.3):

new_list = old_list.copy()

 You can slice it:

new_list = old_list[:]

 You can use the built in list() function:

new_list = list(old_list)

 You can use generic copy.copy():

import copy

new_list = copy.copy(old_list)

This is a little slower than list() because it has to find out the datatype of old_list first.

 If the list contains objects and you want to copy them as well, use
generic copy.deepcopy():

import copy

new_list = copy.deepcopy(old_list)

Obviously the slowest and most memory-needing method, but sometimes unavoidable.

Two-Dimensional Lists: There can be more than one additional dimension to lists in Python.
Keeping in mind that a list can hold other lists, that basic principle can be applied over and over.
Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice
rather than a multi-dimensional list in Python.

# Python program to demonstrate that we

# can access multidimensional list using

# square brackets

a = [ [2, 4, 6, 8 ],

[ 1, 3, 5, 7 ],

[ 8, 6, 4, 2 ],

[ 7, 5, 3, 1 ] ]

for i in range(len(a)) :

PYTHON PROGRAMMING Page 82


CMR Institute of Technology Redefining Quality Education

for j in range(len(a[i])) :

print(a[i][j], end=" ")

print()

Output:

2468

1357

8642

7531

Tuples: A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.

Example

Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Output: ('apple', 'banana', 'cherry')

Access Tuple Items: You can access tuple items by referring to the index number, inside square
brackets:

Example

Return the item in position 1:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Changing Tuple values: Once a tuple is created, you cannot change its values. Tuples are
unchangeable.

Loop Through a Tuple: You can loop through the tuple items by using a for loop.

Example

Iterate through the items and print the values:

PYTHON PROGRAMMING Page 83


CMR Institute of Technology Redefining Quality Education

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

Dictionaries: A dictionary is a collection which is unordered, changeable and indexed. In


Python dictionaries are written with curly brackets, and they have keys and values.

Example

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Accessing Items: You can access the items of a dictionary by referring to its key name, inside
square brackets:

Example

Get the value of the "model" key:

x = thisdict["model"]
There is also a method called get() that will give you the same result:

Example

Get the value of the "model" key:

x = thisdict.get("model")

Change Values: You can change the value of a specific item by referring to its key name:

Example

Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

PYTHON PROGRAMMING Page 84


CMR Institute of Technology Redefining Quality Education

}
thisdict["year"] = 2018
Loop Through a Dictionary: You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.

Example

Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

You can also use the values() function to return values of a dictionary:

for x in thisdict.values():
print(x)

Loop through both keys and values, by using the items() function:

for x, y in thisdict.items():
print(x, y)

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Sets: A set is a collection which is unordered and unindexed. In Python sets are written with
curly brackets.

Example

Create a Set:

PYTHON PROGRAMMING Page 85


CMR Institute of Technology Redefining Quality Education

thisset = {"apple", "banana", "cherry"}


print(thisset)

Output: {'cherry', 'banana', 'apple'}

Note: Sets are unordered, so the items will appear in a random order.

Access Items: You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.

But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using thein keyword.

Example

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

Change Items: Once a set is created, you cannot change its items, but you can add new items.

Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}


print("banana" in thisset)

Add Items

 To add one item to a set use the add() method.


 To add more than one item to a set use the update() method.

Example

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")
print(thisset)

Example

Add multiple items to a set, using the update() method:

PYTHON PROGRAMMING Page 86


CMR Institute of Technology Redefining Quality Education

thisset = {"apple", "banana", "cherry"}


thisset.update(["orange", "mango", "grapes"])
print(thisset)

Recursion: 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.

The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor
power. However, when written correctly recursion can be a very efficient and mathematically-
elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We
use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends
when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.

Example

Recursion Example

def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

PYTHON PROGRAMMING Page 87


CMR Institute of Technology Redefining Quality Education

UNIT-4

Classes and Objects: Python has been an object-oriented language since it existed. Because of
this, creating and using classes and objects are downright easy. This chapter helps you become
an expert in using Python's object-oriented programming support.

If you do not have any previous experience with object-oriented (OO) programming, you may
want to consult an introductory course on it or at least a tutorial of some sort so that you have a
grasp of the basic concepts.

However, here is small introduction of Object-Oriented Programming (OOP) to bring you at


speed:

Overview of OOP Terminology

Class: A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance variables)
and methods, accessed via dot notation.

Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used as
frequently as instance variables are.

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.

Method: A special kind of function that is defined in a class definition.

Object: A unique instance of a data structure that's defined by its class. An object comprises
both data members (class variables and instance variables) and methods.

PYTHON PROGRAMMING Page 88


CMR Institute of Technology Redefining Quality Education

Operator overloading: The assignment of more than one function to a particular operator.

Creation of Class: A class is created with the keyword class and then writing the classname.
The simplest form of class definition looks like this:

class ClassName:

<statement-1>

<statement-N>

Class definitions, like function definitions (def statements) must be executed before they have
any effect. (You could conceivably place a class definition in a branch of an if statement, or
inside a function.)

Example: class Student:

def init (self): self.name="hari" self.branch="CSE"

def display(self): print self.name print self.branch

For example, If we „Student‟ class, we can write code in the class that specifies the
attributes and actions performed by any student.

Observer that the keyword class is used to declare a class. After this, we should write the class
name. So, „Student‟ is our class name. Generally, a class name should start with a capital
letter, hence „S‟ is a capital in „Student‟.

In the class, we have written the variables and methods. Since in python, we cannot declare
variables, we have written the variables inside a special method, i.e. init (). This method is used
to initialize the variables. Hence the name „init‟.

The method name has two underscores before and after. This indicates that this method is
internally defined and we cannot call this method explicitly.

Observe the parameter „self‟ written after the method name in the parentheses. „self‟ is a
variable that refers to current class instance.

When we create an instance for the Student class, a separate memory block is allocated on the
heap and that memory location is default stored in „self‟.

PYTHON PROGRAMMING Page 89


CMR Institute of Technology Redefining Quality Education

The instance contains the variables „name‟ and „branch‟ which are called instance
variables. To refer to instance variables, we can use the dot operator notation along with self as
„self.name‟ and „self.branch‟.

The method display ( ) also takes the „self‟ variable as parameter. This method displays the
values of variables by referring them using „self‟.

The methods that act on instances (or objects) of a class are called instance methods. Instance
methods use „self‟ as the first parameter that refers to the location of the instance in the
memory.

Writing a class like this is not sufficient. It should be used. To use a class, we should create an
instance to the class. Instance creation represents allotting memory necessary to store the actual
data of the variables, i.e., „hari‟, „CSE‟.

To create an instance, the following syntax is used: instancename = Classname( )

So, to create an instance to the Student class, we can write as: s1 = Student ( )

Here „s1‟ represents the instance name. When we create an instance like this, the
following steps will take place internally:

1.First of all, a block of memory is allocated on heap. How much memory is to be allocated is
decided from the attributes and methods available in the Student class.

2.After allocating the memory block, the special method by the name „ init (self)‟ is called
internally. This method stores the initial data into the variables. Since this method is useful to
construct the instance, it is called „constructor‟.

3.Finally, the allocated memory location address of the instance is returned into „s1‟ variable.
To see this memory location in decimal number format, we can use id( ) function as id(s1).

Self variable:„self‟ is a default variable that contains the memory address of the instance
of the current class. When an instance to the class is created, the instance name cotains the
memory locatin of the instance. This memory location is internally passed to „self‟.

For example, we create an instance to student class as:

s1 = Student( )

PYTHON PROGRAMMING Page 90


CMR Institute of Technology Redefining Quality Education

Here, „s1‟ contains the memory address of the instance. This memory address is
internally and by default passed to „self‟ variable. Since „self‟ knows the memory address of
the instance, it can refer to all the members of the instance.

We use „self‟ in two eays:

The self variable is used as first parameter in the constructor as:

def init (self):

In this case, „self‟ can be used to refer to the instance variables inside the constructor.

„self‟ can be used as first parameter in the instance methods as:

def display(self):

Here, display( ) is instance method as it acts on the instance variables. If this method wants to
act on the instance variables, it should know the memory location of the instance variables. That
memory location is by default available to the display( ) method through „self‟.

Constructor: A constructor is a special method that is used to initialize the instance variables of
a class. In the constructor, we create the instance variables and initialize them with some
starting values. The first parameter of the constructor will be „self‟ variable that contains the
memory address of the instance.

def init ( self ): self.name = "hari" self.branch = "CSE"

Here, the constructor has only one parameter, i.e. „self‟ using „self.name‟ and

„self.branch‟, we can access the instance variables of the class. A constructor is called at the
time of creating an instance. So, the above constructor will be called when we create an instance
as:

s1 = Student()

Let‟s take another example, we can write a constructor with some parameters in addition
to „self‟ as:

def init ( self , n = „ ‟ , b = „ ‟ ): self.name = n

self.branch = b

PYTHON PROGRAMMING Page 91


CMR Institute of Technology Redefining Quality Education

Here, the formal arguments are „n‟ and „b‟ whose default values are given as „‟
(None) and „‟ (None). Hence, if we do not pass any values to constructor at the time of creating
an instance, the default values of those formal arguments are stored into name and branch
variables. For example,

s1 = Student( )

Since we are not passing any values to the instance, None and None are stored into name and
branch. Suppose, we can create an instance as:

s1 = Student( “mothi”, “CSE”)

In this case, we are passing two actual arguments: “mothi” and “CSE” to the Student instance.

Example:

class Student:

def init (self,n='',b=''):

self.name=n

self.branch=b

def display(self):

print "Hi",self.name

print "Branch", self.branch s1=Student()

s1.display()

print “------------------------------”

s2=Student("mothi","CSE") s2.display()

print “------------------------------”

Hi Branch

------------------------------

Hi mothi Branch CSE

------------------------------

PYTHON PROGRAMMING Page 92


CMR Institute of Technology Redefining Quality Education

Types of Variables:The variables which are written inside a class are of 2 types:

a)Instance Variables

b)Class Variables or Static Variables

a)Instance Variables: Instance variables are the variables whose separate copy is created in
every instance. For example, if „x‟ is an instance variable and if we create 3 instances,
there will be 3 copies of „x‟ in these 3 instances. When we modify the copy of „x‟ in any
instance, it will not modify the other two copies.

Example: A Python Program to understand instance variables. class Sample:

def init (self): self.x = 10

def modify(self): self.x = self.x + 1

s1=Sample() s2=Sample()

print "x in s1=",s1.x print "x in s2=",s2.x print "----------------"

s1.modify()

print "x in s1=",s1.x print "x in s2=",s2.x print "----------------"

x in s1= 10 x in s2= 10

----------------

x in s1= 11 x in s2= 10

----------------

Instance variables are defined and initialized using a constructor with „self‟ parameter.
Also, to access instance variables, we need instance methods with „self‟ as first parameter. It is
possible that the instance methods may have other parameters in addition to the „self‟
parameter. To access the instance variables, we can use self.variable as shown in program. It is
also possible to access the instance variables from outside the class, as: instancename.variable,
e.g. s1.x

b)Class Variables or Static Variables: Class variables are the variables whose single copy is
available to all the instances of the class. If we modify the copy of class variable in an instance,
it will modify all the copies in the other instances. For example, if „x‟ is a class variable and if

PYTHON PROGRAMMING Page 93


CMR Institute of Technology Redefining Quality Education

we create 3 instances, the same copy of „x‟ is passed to these 3 instances. When we modify the
copy of

„x‟ in any instance using a class method, the modified copy is sent to the other two
instances.

Example: A Python program to understand class variables or static variables. class Sample:

x=10

@classmethod def modify(cls):

cls.x = cls.x + 1 s1=Sample() s2=Sample()

print "x in s1=",s1.x print "x in s2=",s2.x print "----------------"

s1.modify()

print "x in s1=",s1.x print "x in s2=",s2.x print "----------------"

Working with Instances:

Namespaces: A namespace represents a memory block where names are mapped to objects.

Suppose we write: n = 10

Here, „n‟ is the name given to the integer object 10. Please recollect that numbers, strings, lists
etc. Are all considered as objects in python. The name „n‟ is linked to 10 in the namespace.

a)Class Namespace:

A class maintains its own namespace, called „class namespace‟. In the class
namespace, the names are mapped to class variables. In the following code, „n‟ is a class
variable in the student class. So, in the class namespace, the name „n‟ is mapped or linked to 10
as shown in figure. We can access it in the class namespace, using classname.variable, as:
Student.n which gives 10.

Example:

class Student:

n = 10

print Student.n # displays 10 Student.n += 1

print Student.n # displays 11 s1 = Student( )

print s1.n # displays 11 s2 = Student( )

PYTHON PROGRAMMING Page 94


CMR Institute of Technology Redefining Quality Education

print s2.n # displays 11

Before modifying the class variable „n‟ After modifying the class variable „n‟

We know that a single copy of class variable is shared by all the instances. So, if the class
variable is modified in the class namespace, since same copy of the variable is modified, the
modified copy is available to all the instances.

b)Instance namespace: Every instance will have its own name space, called „instance
namespace‟. In the instance namespace, the names are mapped to instance variables. Every
instance will have its own namespace, if the class variable is modified in one instance
namespace, it will not affect the variables in the other instance namespaces. To access the class
variable at the instance level, we have to create instance first and then refer to the variable as
instancename.variable. Example:

class Student:

n = 10

s1 = Student( )

print s1.n # displays 10 s1.n += 1

print s1.n # displays 11

s2 = Student( )

print s2.n # displays 11

Before modifying the class variable „n‟ After modifying the class variable „n‟

Types of methods: We can classify the methods in the following 3 types:

a)Instance methods

Accessor methods

Mutator methods

b)Class methods

c)Static methods

a)Instance Methods:

Instance methods are the methods which act upon the instance variables of the class.instance
methods are bound to instances and hence called as: instancename.method(). Since instance
variables are available in the instance, instance methods need to know the memory address of

PYTHON PROGRAMMING Page 95


CMR Institute of Technology Redefining Quality Education

instance. This is provided through „self‟ variable by default as first parameter for the instance
method. While calling the instance methods, we need not pass any value to the „self‟ variable.

Example:

class Student:

def init (self,n='',b=''): self.name=n self.branch=b

def display(self):

print "Hi",self.name

print "Branch", self.branch s1=Student()

s1.display()

print “------------------------------”

s2=Student("mothi","CSE") s2.display()

print “------------------------------”

Instance methods are of two types: accessor methods and mutator methods.

Accessor methods simply access of read data of the variables. They do not modify the data in
the variables. Accessor methods are generally written in the form of getXXXX( ) and hence
they are also called getter methods.

Mutator methods are the methods which not only read the data but also modify them. They are
written in the form of setXXXX( ) and hence they are also called setter methods.

class Student:

def setName(self,n): self.name = n

def setBranch(self,b): self.branch = b

def getName(self): return self.name

def getBranch(self): return self.branch

s=Student() name=input("Enter Name: ") branch=input("Enter Branch: ") s.setName(name)


s.setBranch(branch)

print s.getName() print s.getBranch()

PYTHON PROGRAMMING Page 96


CMR Institute of Technology Redefining Quality Education

b)Class methods: These methods act on class level. Class methods are the methods which act
on the class variables or static variables. These methods are written using @classmethod
decorator above them. By default, the first parameter for class methods is „cls‟ which refers to
the class itself.

For example, „cls.var‟ is the format to the class variable. These methods are generally called
using classname.method( ). The processing which is commonly needed by all the instances of
class is handled by the class methods.

Example:

class Bird: wings = 2

@classmethod def fly(cls,name):

print name,"flies with",cls.wings,"wings"

Bird.fly("parrot") #display "parrot flies with 2 wings" Bird.fly("sparrow") #display "sparow


flies with 2 wings"

c)Static methods: We need static methods when the processing is at the class level but we need
not involve the class or instances. Static methods are used when some processing is related to
the class but does not need the class or its instances to perform any work.

For example, setting environmental variables, counting the number of instances of the class or
changing an attribute in another class, etc. are the tasks related to a class.

Such tasks are handled by static methods. Static methods are written with decorator
@staticmethod above them. Static methods are called in the form of classname.method ( ).

Inheritance:

class MyClass: n = 0

def init (self):

MyClass.n = Myclass.n + 1 def noObjects():

print "No. of instances created: ", MyClass.n m1=MyClass()

m2=MyClass() m3=MyClass() MyClass.noObjects()

PYTHON PROGRAMMING Page 97


CMR Institute of Technology Redefining Quality Education

•Software development is a team effort. Several programmers will work as team to develop S/W

•When a programmer develops a class, he will use its features by creating an instance to it.
When another programmer wants to create another class which is similar to the class already
created, then he need not create the class from the scratch. He can simply use the features of the
existing class in creating his own class.

•Deriving new class from the super class is called inheritance.

•The child class inherits the attributes of its parent class, and you can use those attributes as if
they were defined in the child class.

•A child class can also override data members and methods from the parent.

Syntax:

class Subclass(BaseClass):

<class body>

•When an object is to SubClass is created, it contains a copy of BaseClass within it. This means
there is a relation between the BaseClass and SubClass objects.

•We do not create BaseClass object,but still a copy of it is available to SubClass object.

•By using inheritance, a programmer can develop classes very easilt. Hence programmer‟s
productivity is increased. Productivity is a term that refers to the code developed by the
programmer in a given span of time.

•If the programmer used inheritance, he will be able to develop more code in less time.

•In inheritance, we always create only the sub class object. Generally, we do not create super
class object. The reason is clear. Since all the members of the super class are available to sub
class, when we crate an object, we can access the members of both the super and sub classes.

The super( ) method:

•super( ) is a built-in method which is useful to call the super class constructor or methods from
the sub class.

•Any constructor written in the super class is not available to the sub class if the sub class has a
constructor.

PYTHON PROGRAMMING Page 98


CMR Institute of Technology Redefining Quality Education

•Then how can we initialize the super class instance variables and use them in the sub class?
This is done by calling super class constructor using super( ) method from inside the sub class
constructor.

•super( ) is a built-in method which contains the history of super class methods.

•Hence, we can use super( ) to refer to super class constructor and methods from a aub class. So,
super( ) can be used as:

super().init() # call super class constructor

super().init(arguments) # call super class constructor and pass arguments super().method() # call
super class method

Example: Write a python program to call the super class constructor in the sub class using
super( ).

class Father:

def init (self, p = 0): self.property = p

def display(self):

print "Father Property",self.property class Son(Father):

def init (self,p1 = 0, p = 0): super(). init (p1) self.property1 = p

def display(self):

print "Son Property",self.property+self.property1 s=Son(200000,500000)

isplay()

Output:

Son Property 700000

Example: Write a python program to access base class constructor and method in the sub class
using super( ).

class Square:

def init (self, x = 0): self.x = x

PYTHON PROGRAMMING Page 99


CMR Institute of Technology Redefining Quality Education

def area(self):

print "Area of square", self.x * self.x class Rectangle(Square):

def init (self, x = 0, y = 0): super(). init (x)

self.y = y def area(self):

super().area()

print "Area of Rectangle", self.x * self.y r = Rectangle(5,16)

r.area()

Output:

Area of square 25 Area of Rectangle 80

Types of Inheritance:

There are mainly 2 types of inheritance.

a)Single inheritance

b)Multiple inheritance

a)Single inheritance: Deriving one or more sub classes from a single base class is called
„single inheritance‟. In single inheritance, we always have only one base class, but there can be
n number of sub classes derived from it. For example, „Bank‟ is a single base clas from where
we derive „AndhraBank‟ and „StateBank‟ as sub classes. This is called single inheritance.

Example:

class Bank: cash = 100

@classmethod def balance(cls):

print cls.cash

class AndhraBank(Bank): cash = 500 @classmethod

def balance(cls):

print "AndhraBank",cls.cash + Bank.cash class StateBank(Bank):

cash = 300 @classmethod def balance(cls):

PYTHON PROGRAMMING Page 100


CMR Institute of Technology Redefining Quality Education

print "StateBank",cls.cash + Bank.cash a=AndhraBank()

a.balance() # displays AndhraBank 600 s=StateBank()

s.balance() #displays StateBank 400

b)Multiple inheritance: Deriving sub classes from multiple (or more than one) base classes is
called multiple inheritance. All the members of super classes are by default available to sub
classes and the sub classes in turn can have their own members.

The best example for multiple inheritance is that parents are producing the children and the
children inheriting the qualities of the parents.

Example:

class Father:

def height(self):

print "Height is 5.8 incehs" class Mother:

def color(self):

print "Color is brown" class Child(Father, Mother):

pass c=Child()

c.height() # displays Height is 5.8 incehs c.color() # displays Color is brown

Problem in Multiple inheritance:

If the sub class has a constructor, it overrides the super class constructor and hence the super
class constructor is not available to the sub class.

But writing constructor is very common to initialize the instance variables.

In multiple inheritance, let‟s assume that a sub class „C‟ is derived from two super
classes „A‟ and „B‟ having their own constructors. Even the sub class „C‟ also has its
constructor.

Example-1:

class A(object):

def init (self):

print "Class A"

PYTHON PROGRAMMING Page 101


CMR Institute of Technology Redefining Quality Education

class B(object):

def init (self):

print "Class B"

class C(A,B,object):

def init (self): super(). init ()

print "Class C"

c1= C()

Output:

Class A

Class B

Class C

Example-2:

class A(object):

def init (self): super(). init ()

print "Class A"

class B(object):

def init (self):

super(). init ()

print "Class B"

class C(A,B,object):

def init (self): super(). init ()

print "Class C"

c1= C()

Output:

Class B

Class A

Class C

PYTHON PROGRAMMING Page 102


CMR Institute of Technology Redefining Quality Education

Polymorphism:

Method Overriding:

When there is a method in the super class, writing the same method in the sub class so that it
replaces the super class method is called „method overriding‟. The programmer overrides
the super class methods when he does not want to use them in sub class.

Example:

import math class square:

def area(slef, r):

print "Square area=",r * r class Circle(Square):

def area(self, r):

print "Circle area=", math.pi * r * r c=Circle()

c.area(15) # displays Circle area= 706.85834

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 are not be
directly visible to outsiders.

Example:

class JustCounter:

secretCount = 0 def count(self):

self. secretCount += 1 print self. secretCount

counter = JustCounter() counter.count() counter.count()

print counter. secretCount

When the above code is executed, it produces the following result: 1

Traceback (most recent call last):

File "C:/Python27/JustCounter.py", line 9, in <module> print counter. secretCount

AttributeError: JustCounter instance has no attribute ' secretCount'

PYTHON PROGRAMMING Page 103


CMR Institute of Technology Redefining Quality Education

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

When the above code is executed, it produces the following result: 1

Procedural and Object-Oriented Programming:

Procedural: Tasks are treated as step-by-step iterations where common tasks are placed in
functions that are called as needed. This coding style favors iteration, sequencing, selection, and
modularization. Python excels in implementing this particular paradigm.

The procedural style relies on procedure calls to create modularized code. This approach
simplifies your application code by breaking it into small pieces that a developer can view
easily. Even though procedural coding is an older form of application development, it’s still a
viable approach for tasks that lend themselves to step-by-step execution. Here’s an example of
the procedural coding style using my_list:

def do_add(any_list):

sum = 0

for x in any_list:

sum += x

return sum

print(do_add(my_list))

The use of a function, do_add(), simplifies the overall code in this case. The execution is still
systematic, but the code is easier to understand because it’s broken into chunks. However, this
code suffers from the same issues as the imperative paradigm in that the use of state limits
execution options, which means that this approach may not use hardware efficiently when
tackling complex problems.

PYTHON PROGRAMMING Page 104


CMR Institute of Technology Redefining Quality Education

Object-oriented: Relies on data fields that are treated as objects and manipulated only through
prescribed methods. Python doesn’t fully support this paradigm because it can’t implement
features such as data hiding (encapsulation), which many believe is a primary requirement of
the object-oriented programming paradigm. This coding style also favors code reuse.

Object-oriented coding is all about increasing an application’s ability to reuse code and make it
easier to understand. The encapsulation that object-orientation provides allows developers to
treat code as a black box. Using object-orientation features like inheritance make it easier to
expand the functionality of existing code. Here is the my_list example in object-oriented form:

class ChangeList(object):

def __init__(self, any_list):

self.any_list = any_list

def do_add(self):

self.sum = sum(self.any_list)

create_sum = ChangeList(my_list)

create_sum.do_add()

print(create_sum.sum)

In this case, create_sum is an instance of ChangeList. The inner workings


of ChangeList don’t matter to the person using it. All that really matters is that you can create
an instance using a list and then call the do_add() method to output the sum of the list elements.
Because the inner workings are hidden, the overall application is easier to understand.

PYTHON PROGRAMMING Page 105


CMR Institute of Technology Redefining Quality Education

UNIT-5

Graphical User Interfaces:

• Most modern computer software employs a graphical user interface or GUI

• A GUI displays text as well as small images (called icons) that represent objects such as
directories, files of different types, command buttons, and drop-down menus

• In addition to entering text at keyboard, the user of a GUI can select an icon with
pointing device, such as mouse, and move that icon around on the display

Behavior of terminal based programs and GUI-based programs:

• Two different versions of the bouncy program from a user’s point of view:

– Terminal-based user interface

– Graphical user interface

• Both programs perform exactly the same function

– However, their behavior, or look and feel, from a user’s perspective are quite
different

The Terminal-Based Version:

PYTHON PROGRAMMING Page 106


CMR Institute of Technology Redefining Quality Education

Problems with The Terminal-Based Version:

• User is constrained to reply to a definite sequence of prompts for inputs

– Once an input is entered, there is no way to change it

• To obtain results for a different set of input data, user must wait for command menu to
be displayed again

– At that point, the same command and all of the other inputs must be re-entered

• User can enter an unrecognized command

PROPERTY GUI TERMINAL-BASEDI

Interaction Using graphics(images, icons) Using commands(only text)

Navigation Easier Difficult

Peripherals used Keyboard and mouse(or any pointing Keyboard only

device)

Precision LOW HIGH

Speed LOW HIGH

Ease of Operation Easier Difficult, requires expertise

Memory Required HIGH LOW

Flexibility MORE Flexible LESS Flexible

Customising Highly customisable Appearance cannot be

Appearance changed

The GUI-Based Version:

• Uses a window that contains various components

– Called window objects or widgets

PYTHON PROGRAMMING Page 107


CMR Institute of Technology Redefining Quality Education

• Solves problems of terminal-based version

Coding simple GUI-based programs:

 Define a new class to represent the main window


 Instantiate the classes of window objects needed for this application (e.g., labels,
command buttons)
 Position these components in the window
 Instantiate the data model and provide for the display of any default data in the
window objects
 Register controller methods with each window object in which a relevant event
might occur
 Define these controller methods
 Define a main that launches the GUI

Other useful GUI resources:

 There are many libraries and toolkits of GUI components available to the Python
programmer

o For example, Tkinter and tkMessageBox

 Standard Python modules

 Tkinter includes classes for windows and numerous types of window objects

 tkMessageBox includes functions for several standard pop-up dialog boxes

 Layout of GUI components can be specified in more detail

o Groups of components can be nested in panes

 Paragraphs can be displayed in scrolling text boxes

PYTHON PROGRAMMING Page 108


CMR Institute of Technology Redefining Quality Education

 Lists of information can be presented for selection in scrolling list boxes and drop-
down menus

 Color, size, and style of text and of some GUI components can be adjusted

 GUI-based programs can be configured to respond to various keyboard events and


mouse events

GUI Programming: Graphical User Interfaces:

Python provides various options for developing graphical user interfaces (GUIs). Most
important 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
wxWindows http://wxpython.org.
 JPython: JPython is a Python port for Java which gives Python scripts seamless access
to Java class libraries on the local machine http://www.jython.org.

There are many other interfaces available, which you can find them on the net.

Using the tkinter Module: 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 = Tkinter.Tk()

# Code to add widgets will go here... top.mainloop()

PYTHON PROGRAMMING Page 109


CMR Institute of Technology Redefining Quality Education

Tkinter Widgets

•Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.

•There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief
description in the following table:

Operator Description
Button The Button widget is used to display buttons in your application.
The Canvas widget is used to draw shapes, such as lines, ovals,
Canvas
polygons and rectangles, in your application.
The Checkbutton widget is used to display a number of options as
Checkbutton
checkboxes. The user can select multiple options at a time.
The Entry widget is used to display a single-line text field for accepting
Entry
values from a user.
The Frame widget is used as a container widget to organize other
Frame
widgets.
The Label widget is used to provide a single-line caption for other
Label
widgets. It can also contain images.
Listbox The Listbox widget is used to provide a list of options to a user.
Menubutton The Menubutton widget is used to display menus in your application.
The Menu widget is used to provide various commands to a user. These
Menu
commands are contained inside Menubutton.
The Message widget is used to display multiline text fields for
Message accepting values from a user.
The Radiobutton widget is used to display a number of options as radio
buttons. The user can select only one option at a time. Scale The Scale
Radiobutton widget is used to provide a slider widget.
The Scrollbar widget is used to add scrolling capability to various
Scrollbar widgets, such as list boxes.
The Text widget is used to display text in multiple lines.
Text

The Toplevel widget is used to provide a separate window container.


Toplevel

The Spinbox widget is a variant of the standard Tkinter Entry widget,


Spinbox which can be used to select from a fixed number of values.
A PanedWindow is a container widget that may contain any number of
PanedWindow panes, arranged horizontally or vertically.
A labelframe is a simple container widget. Its primary purpose is to act
LabelFrame as a spacer or container for complex window layouts.
This module is used to display message boxes in your applications.
tkMessageBox

PYTHON PROGRAMMING Page 110


CMR Institute of Technology Redefining Quality Education

Display text with Label Widgets: A Label is a Tkinter Widget class, which is used to display
text or an image. The label is a widget that the user just views but not interact with. There is
hardly any book or introduction into a programming language, which doesn't start with the
"Hello World" example.

The following Python script uses Tkinter to create a window with the text "Hello Tkinter". You
can use the Python interpretor to type this script line after line, or you can save it in a file, for
example, "hello.py":

import tkinter as tk

# if you are still working under a Python 2 version,

# comment out the previous line and uncomment the following line

# import Tkinter as tk

root = tk.Tk()

w = tk.Label(root, text="Hello Tkinter!")

w.pack()

root.mainloop()

Output:

Organizing Widgets with Frames: Python Tkinter Frame widget is used to organize the group
of widgets. It acts like a container which can be used to hold the other widgets. The rectangular
areas of the screen are used to organize the widgets to the python application.

The syntax to use the Frame widget is given below.

Syntax

w = Frame(parent, options)

Example

from tkinter import *

PYTHON PROGRAMMING Page 111


CMR Institute of Technology Redefining Quality Education

top = Tk()

top.geometry("140x100")

frame = Frame(top)

frame.pack()

leftframe = Frame(top)

leftframe.pack(side = LEFT)

rightframe = Frame(top)

rightframe.pack(side = RIGHT)

btn1 = Button(frame, text="Submit", fg="red",activebackground = "red")

btn1.pack(side = LEFT)

btn2 = Button(frame, text="Remove", fg="brown", activebackground = "brown")

btn2.pack(side = RIGHT)

btn3 = Button(rightframe, text="Add", fg="blue", activebackground = "blue")

btn3.pack(side = LEFT)

btn4 = Button(leftframe, text="Modify", fg="black", activebackground = "white")

btn4.pack(side = RIGHT)

top.mainloop()

Output:

Button Widgets and Info Dialog Boxes: The button widget is used to add various types of
buttons to the python application. Python allows us to configure the look of the button according

PYTHON PROGRAMMING Page 112


CMR Institute of Technology Redefining Quality Education

to our requirements. Various options can be set or reset depending upon the requirements. We
can also associate a method or function with a button which is called when the button is pressed.

The syntax to use the button widget is given below.

Syntax

W = Button(parent, options)

Example

from tkinter import *

top = Tk()

top.geometry("200x100")

def fun():

messagebox.showinfo("Hello", "Red Button clicked")

b1 = Button(top,text = "Red",command = fun,activeforeground = "red",activebackground =


"pink",pady=10)

b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=1


0)

b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink",pady


= 10)

b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",pa


dy = 10)

b1.pack(side = LEFT)

b2.pack(side = RIGHT)

b3.pack(side = TOP)

b4.pack(side = BOTTOM)

top.mainloop()

Output:

PYTHON PROGRAMMING Page 113


CMR Institute of Technology Redefining Quality Education

Getting Input with Entry Widget: The Entry widget is used to provde the single line text-box
to the user to accept a value from the user. We can use the Entry widget to accept the text
strings from the user. It can only be used for one line of text from the user. For multiple lines of
text, we must use the text widget.

The syntax to use the Entry widget is given below.

Syntax

w = Entry (parent, options)

# !/usr/bin/python3

from tkinter import *

top = Tk()

top.geometry("400x250")

name = Label(top, text = "Name").place(x = 30,y = 50)

email = Label(top, text = "Email").place(x = 30, y = 90)

password = Label(top, text = "Password").place(x = 30, y = 130)

sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").


place(x = 30, y = 170)

e1 = Entry(top).place(x = 80, y = 50)

e2 = Entry(top).place(x = 80, y = 90)

e3 = Entry(top).place(x = 95, y = 130)

PYTHON PROGRAMMING Page 114


CMR Institute of Technology Redefining Quality Education

top.mainloop()

Output:

Using Labels as Output Fields

from Tkinter import *

master = Tk()

master.geometry('200x90')

master.title('Input Test')

def UserName():

global usrE

global usrN

global lbl

usrE1 = usrE.get()

usrN2 = usrN.get()

InputExcept = usrE1 + " " + usrN2

print InputExcept

lbl.config(text='User expected:'+InputExcept)

usrE = Entry(master, relief=SUNKEN)

usrE.pack()

usrN = Entry(master, relief=SUNKEN)

PYTHON PROGRAMMING Page 115


CMR Institute of Technology Redefining Quality Education

usrN.pack()

Btn1 = Button(master, text="Input", command=UserName)

Btn1.pack()

lbl = Label(master)

lbl.pack()

master.mainloop()

Output:

Radio Buttons: The Radiobutton widget is used to implement one-of-many selection in the
python application. It shows multiple choices to the user out of which, the user can select only
one out of them. We can associate different methods with each of the radiobutton.

We can display the multiple line text or images on the radiobuttons. To keep track the user's
selection the radiobutton, it is associated with a single variable. Each button displays a single
value for that particular variable.

The syntax to use the Radiobutton is given below.

Syntax

w = Radiobutton(top, options)

Example:

from tkinter import *

def selection():

selection = "You selected the option " + str(radio.get())

label.config(text = selection)

top = Tk()

PYTHON PROGRAMMING Page 116


CMR Institute of Technology Redefining Quality Education

top.geometry("300x150")

radio = IntVar()

lbl = Label(text = "Favourite programming language:")

lbl.pack()

R1 = Radiobutton(top, text="C", variable=radio, value=1, command=selection)

R1.pack( anchor = W )

R2 = Radiobutton(top, text="C++", variable=radio, value=2, command=selection)

R2.pack( anchor = W )

R3 = Radiobutton(top, text="Java", variable=radio, value=3, command=selection)

R3.pack( anchor = W)

label = Label(top)

label.pack()

top.mainloop()

Output:

Check Buttons: The Checkbutton is used to track the user's choices provided to the application.
In other words, we can say that Checkbutton is used to implement the on/off selections. The
Checkbutton can contain the text or images. The Checkbutton is mostly used to provide many
choices to the user among which, the user needs to choose the one. It generally implements
many of many selections.

The syntax to use the checkbutton is given below.

Syntax

w = checkbutton(master, options)

PYTHON PROGRAMMING Page 117


CMR Institute of Technology Redefining Quality Education

Example

from tkinter import *

top = Tk()

top.geometry("200x200")

checkvar1 = IntVar()

checkvar2 = IntVar()

checkvar3 = IntVar()

chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue = 0, hei


ght = 2, width = 10)

chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1, offvalue = 0,


height = 2, width = 10)

chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3, onvalue = 1, offvalue = 0,


height = 2, width = 10)

chkbtn1.pack()

chkbtn2.pack()

chkbtn3.pack()

top.mainloop()

Output:

PYTHON PROGRAMMING Page 118

Das könnte Ihnen auch gefallen