Notes Python Notes To Send
Notes Python Notes To Send
S
add, remove, in, not in, union, intersection, symmetric difference)-Tuples and Dictionaries,
Conditionals, Iteration and looping - Functions and Modules - File input and file output,
IC
Pickling.
UNIT II . Numerical Methods in physics (Programs are to be discussed in Python) 22 Hrs
General introduction to numerical methods, Comparison between analytical and numerical
techniques - Curve Fitting: Principle of least squares, fitting a straight line - Interpolation:
YS
Finite difference operator, Newton's forward difference interpolation formula, Solution of
algebraic equations: Newton-Raphson method - Numerical differentiation and integration:
Differnce table, Trapezoidal and Simpson's (1/3) method - Solution of differential
equations :Runge Kutta method (Second order) -Taylor's Series : Sin(x) and Cos(x).
UNIT III> Introduction to Computational approach in physics 12 Hrs
(Programs are to be discussed in Python) PH
One Dimensional Motion: Falling Objects: Introduction – Formulation: from Analytical
methods to Numerical Methods - Euler Method, Freely falling body, Fall of a body in
viscous medium - Simulation of free fall and numerical integration, Two dimensional
motion: Projectile motion (by Euler method)-Motion under an attractive Inverse Squarelaw
force Accuracy considerations .(elementary ideas)(Graphics not required, data may be
C
presented in table form)
References:
(For Python any book can be used as reference. Moreover a number of open articles are
K
available freely in internet. Python is included in default in all GNU/Linux platforms and It
is freely downloadable for Windows platform as well. However use of GNU/Linux may be
encouraged).
1. www.python.org
S
http://www.greenteapress.com/thinkpython/thinkpython.pdf
6. Numerical Methods in Engineering and Science, Dr. B S Grewal, Khanna Publishers,
Newdelhi (or any other book)
7. Numerical methods for scientists and engineers, K. Sankara Rao, PHI
8. Introductory methods of numerical analysis, S.S.Shastry , (Prentice Hall of
India,1983)
9. Computational Physics, V.K.Mittal, R.C.Verma & S.C.Gupta-Published by Ane
Books,4821,Pawana Bhawan,first floor,24 Ansari Road,Darya Ganj,New Delhi-110
002 (For theory part and algorithms. Programs must be discussed in Python)Programming in Python
Concept Of Programming Language
Microprocessor is the most important part of a computer. With the help of devices and chips a micro-
processor can accept instructions and data. It can manipulate this data to take decisions. The step by step
instructions based on logics to solve a problem is a computer program. The manufacturer will incorporate
the circuits and elements of the microprocessor so that it can perform jobs. Each job is designated with a
number in the binary format. So to use microprocessor we have to feed this number. An instruction set
written with this number and address of memory location is called a Machine Language Instruction.
S
To solve a problem, we have to develop a detailed and precise step by step method. These steps are
called Algorithm or Logical development of program. Each step in this algorithm can be decoded to
IC
machine language instructions. This sequence of machine language instructions is known as Machine
Language Program. Due to the machine dependency of the language and the difficulty to handle the
numbers, debugging become a difficult task. To avoid this, another language is developed. In this, the
YS
instructions are some combination of two or three characters which have close resemblance to the
corresponding English word for that job. MOV, ADD, HLT etc are examples. A program with this type of
instructions is called Assembly Language. A program in the computer can convert the Assembly Language
to Machine Language is known as Assembler
English are known as Syntax Rules. An instruction even if correct in syntax, may led to wrong answers, if it
is not properly used. That is, the instruction is with Semantic Error. For instance, the sentence ‘Marry
plays violin’ is both syntactically and semantically correct whereas ‘Violin plays Marry’ is syntactically
correct, but semantically wrong.
S
3. A detailed list of operators (arithmetic, logical, conditional etc.) to act on the data.
4. Instructions for control flow structures on decision making, branching, looping etc.
5. A set of syntax rules to frame the correct instruction with key words and symbols permitted by the
language.
6. A set of semantic rules to assign correct and unambiguous meaning to a statement.
The process of designing, writing, testing, debugging/ troubleshooting, and maintaining the source
code is called computer programming.
The Evolution of Programming Languages
Programming languages fall into three broad categories:
• Machine languages
• Assembly languages
• Higher-level languages
S
• Different types of hardware use different machine code. For example, IBM computers use different
machine language than Apple computers.
IC
Assembly Level Languages
• Assembly languages (second-generation languages) are only somewhat easier to work with than
machine languages.
• To create programs in assembly language, developers use cryptic English-like phrases to represent
YS
strings of numbers.
• The code is then translated into object code, using a translator called an assembler.
•
in a more English-like environment.
PH
eg:- Ada, Algol,BASIC,COBOL,C,C++,FORTRAN, LISP, PASCAL,PROLOG
• First HLL is Plankalkül (Konrad Zuse)
• Higher-level programming languages are divided into three "generations," each more powerful than
the last.
• Third-generation languages
C
• Fourth-generation languages
• Fifth-generation languages
K
• Third-generation languages (3GLs) are the first to use true English-like phrasing, making them easier
to use than previous languages.
S
• 3GLs are portable, meaning the object code created for one type of system can be translated for use
on a different type of system.
• The following languages are 3GLs:
FORTAN, C, COBOL,C++, BASIC, Java, Pascal, ActiveX
E
• 4GLs may use a text-based environment (like a 3GL) or may allow the programmer to work in a visual
environment, using graphical tools.
• The following languages are 4GLs:
Visual Basic (VB), VisualAge , Authoring environments
Advantages of High Level Languages
S
• tend to produce more efficient code
Disadvantages of HLL
• must be translated into machine language(executable program) by a compiler or interpreter
IC
• Programming features like more generic data structures, run time interpretation & intermediate code
files result in
• slower execution speed
YS
• higher memory consumption
• larger binary program size
program is free from syntax errors, compiler will convert the program to machine language and stores in a location.
We can directly execute the program from this stored file. So we need the compilation only once.
E
M
Compiling
Compiling is a process of transforming a program written in a high level programming language from
source code into object code. Program written in particular programming language in its original form is
called source program. Source code must go through several steps before it becomes an executable
program. The first step is to pass the source code through a compiler, which translates the HLL instruction
in the source code follow its syntax rules. If not it will inform the programmer where rules have been
violated.
S
The final step in producing an executable program (after the compiler has produced object code) is to pass
the object code through a linker. The linker combines different program segments and gives real values to
IC
all symbolic addresses (memory locations), thereby producing machine code.
Source code is the only format that is readable by humans. When we purchase programs, we usually
receive them in their machine language format. This means that we can execute them directly, but cannot
YS
read or modify them.
Compiler characteristics:
• Translates high-level instructions into machine language and this process is called compiling.
•
•
•
PH
spends a lot of time analyzing and processing the program
the resulting executable is some form of machine- specific binary code
the computer hardware interprets (executes) the resulting code
• program execution is fast
• syntax errors caught before running the program
• better performance
C
• Runs on any computer
Interpreter characteristics:
K
• They can execute a program immediately. For this reason, interpreters are sometimes used during the
development of a program, when a programmer wants to add small sections at a time and test them
quickly.
S
• Translates high-level instructions into intermediate code, it is interpreted by another program and then
executes the program
• Interpreter analyzes and executes each line of source code in succession, without looking at the entire
E
program
• Is comparatively faster at program analysis and processing
• Results in a form of intermediate code that is "interpreted" by another program
• Results in comparatively slow executing programs
M
S
o Document solution
IC
Step 1 : Analyze requirement
• Analyze the requirement of the problems that the program(s) should solve.
• Consists of three major steps:
YS
o Review the requirement - the requirement may be in the form of deliverables such as charts,
diagrams and reports.
o Meet the system analyst and users – enables the programmer to understand the purpose of
the requirements from the user’s perspective.
o Identify input, output, processing and data components – programmer defines the input,
PH
processing and output requirements for each requirement.
• Design the solution that will meet the user’s requirement which involves devising a solution
algorithm.
C
• Solution algorithm – a graphical or written description of the step-by-step procedures to solve the
Problem.
o Flowchart – graphically shows the logic in a solution algorithm using symbols for various
operations in a program’s logic.
o Pseudocode – uses a condensed form of English to convey program logic.
S
• Once developed the solution algorithm using flowchart or pseudocode, programmers should
E
validate or check the program design for accuracy, where the programmer checks the logic for
correctness and attempts to uncover logic errors.
• Logic error – a flaw in the design that causes inaccurate results.
M
• The goal is to ensure the program runs correctly and is error free.
• The errors can be either:
o Syntax error – occurs when the code violates the syntax or grammar of the programming
language.
o Logic error
• Debugging - process of locating and correcting syntax and logic errors .
Bugs - program error
S
Step 6 : Document Solution
IC
• The programmer perform two activities:
• Review the program code.
• Review all the documentation.
YS
• The documentation includes all charts, solution algorithms in the form of flowchart or pseudocode,
test data and program code listings.
• Should ensure that all the documents are complete and accurate.
Example:
PH
Consider the problem to calculate the area of a rectangle.
The algorithm will be as follows:
Read height and width
Apply the calculate area formula
Display result area in unit.
C
The Pseudocode:
Start
Request user to input width
K
Flow chart:
M
C++ Program:
include <iostream.h>
main()
{
int width, height, area;
cout << "Hi! Enter the width: ";
cin >> width;
cout << "Now enter the height: ";
S
cin >> height;
area = width * height;
IC
cout << "The area is: " << area;
}
Output:
YS
Hi! Enter the width:
Now enter the height:
The area is: 12
PH
C
K
S
E
M
Introduction
The implementation of Python was in December 1989 by a team headed by Guido Van Rossum of
Netherlands. In 2000 Python got the present scenario with some major changes like shifting to more
transparency and more community linked under free software movement. Free software can be used,
S
studied, and modified without any restriction. It can be copied and redistributed in modified or unmodified
form. Free software is generally available without charge. Software becomes free software only if the
human-readable form of the program must be made available to the recipient along with a notice granting
IC
the above permissions. Human-readable form of the program is known as the source code. The free
software movement was conceived in 1983 by Richard Stallman to give the benefit of "software freedom"
to computer users. Stallman founded the Free Software Foundation in 1985 to provide the organizational
YS
structure to advance his Free Software ideas. Later on, alternative movements like Open Source Software
came. Python comes in this category. So many experts made many remarkable changes in this software.
Python contain aspects of philosophy influenced by many other popular languages like Java, Perl etc. As a
result Python become more and more powerful.
• You Tube
• Google
C
• Yahoo!
• CERN
• NASA
K
• Google uses Python for many tasks including the backends of web apps such as Google Groups, Gmail, and Google
S
• Industrial Light & Magic uses Python in its production of special effects of large budget feature films
• NASA uses Python both for development and as scripting language in several of its systems.
NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and
transformation system which will be the core infrastructure for its next-generation collaborative engineering
M
environment
• reddit was originally written in Common Lisp, but was rewritten in Python in 2005
• Yahoo! Groups uses Python "to maintain its discussion groups"
• YouTube uses Python "to produce maintainable features in record times, with a minimum of developers"
Guido van Rossum, the creator and BDFL of Python programming language says that YouTube is almost
entirely written in Python. Oh! think of the scalability of a Python based system. Dec 13, 2006
As you probably know, the creator of Python, Guido van Rossum works for Google. Google uses Python for its
search engine quality, and half of Guido's work-week is spent in developing the Python interpreter.
It is used daily in the operations of the Google search engine, the video sharing web site YouTube, NASA , and the
New York Stock Exchange. These are but a few of the places where Python plays important roles in the success of
business, government, and non-profit organisations; there are many others.
S
• Designed by : Guido van Rossum based on language ABC(HLL).
• Name is derived from the British television show Monty Python’s Flying Circus
IC
• It is a general purpose, high level programming language with an emphasis for the
code readability.
• Python is in the category of “open source software” and so no need of paying any special license fee to use.
Its source code is freely available.
YS
• It is powerful with clear,simple syntax.
• It is so abbreviated due to its power to couple the instructions together.
• The use of indentation for block delimiters (will explain later) is unique among most
• popular languages. Due to this debugging is easier.
•
•
•
The “type system” of Python is dynamic PH
Highly extensible. Provide useful basic types, but allow the user to extend them
It offers strong support for integration with other languages and tools
• Is an interpreted, object oriented, general-purpose high-level programming language with
dynamic semantics
• Its standard library is large and comprehensive
C
• supports multiple programming paradigms
• free and open source software
• Used as a scripting language for web applications, but is also used in a wide range of non-scripting contexts
• Used extensively for system administration tasks (it is a vital component of several Linux distributions).
K
• User-defined types should behave just like the built-in types, even if implemented in C.
• Easy to parse (may be not as easy as Lisp, but quite simple compared to C++)
• Python should bridge the gap between shell languages and systems programming languages like C and C++.
S
eg: programs written in C++ or Object Pascal can be purely procedural, or purely object-oriented, or contain
elements of both paradigms. Software designers and programmers decide how to use those paradigm
elements. In object-oriented programming, programmers can think of a program as a collection of interacting
objects, while in functional programming a program can be thought of as a sequence of stateless function
M
evaluations.
When programming computers or systems with many processors, process-oriented programming allows
programmers to think about applications as sets of concurrent processes acting upon logically shared data
structures.
Advantages
• Clean, simple syntax.
• Python is open-source software, which means that it is free; it is included in most Linux
distributions.
• Easy to parse and also to learn!
• Programs can be tested & debugged quickly, allowing the user to concentrate more on the
principles
behind the program and less on programming itself.
Portable
S
•
• Powerful built-in types.
• Elegant and flexible module system, user-defined types using classes.
IC
Disadvantages
• Not terribly fast on computationally intensive operations.
YS
• Might not be as fast as compiled languages (C,C++,…)
• Language processor cares at a syntactic level, how many spaces are in a tab.
• Not terribly concise (not a lot of fiddly little close-in operators, a la Perl, C, etc.).
• Interpreted programs do not produce stand-alone applications. Thus a Python program can be run
only on computers that have the Python interpreter installed.
PH
---------------------------------------------------------------------------------------------------------------------------------------------------
(For additional reading- not included in syllabus)
Sugar
Sugar is an open source desktop environment designed with the goal of being used by children for learning.
Developed as part of the One Laptop per Child (OLPC) project, it is the default interface on OLPC XO-1 family of
C
laptop computers.
Unlike most other desktop environments, Sugar does not use the "desktop", "folder" and "window"
metaphors. Instead, Sugar's default full-screen activities require users to focus on only one program at a
K
time. Sugar implements a novel file-handling metaphor (the journal), which automatically saves the user's
running program session and allows them to later use an interface to pull up their past works by date,
activity used or file type.
S
Sugar is now developed under the umbrella of Sugar Labs, a nonprofit spin-off of OLPC which began
operating in May 2008. It is available as a LiveCD, as LiveUSB, or as a package installable through several
GNU/Linux distributions.
E
Sugar is free software released under the GNU GPL. As such, its development is done by a variety of
contributors, including many who are not employed by Sugar Labs, One Laptop per Child, or any other
M
related organization.Sugar is intentionally designed to encourage the modification of its activities and core
functionality by users, which makes Sugar developers' adoption of an open source development approach
seem a fitting choice. Whereas most other desktop environments are written in a compiled language (e.g.,
the GNOME desktop environment, Microsoft Windows XP and Vista were all written mostly in C), Sugar
is written in the interpreted Python programming language. This allows for easier modification and
customization of Sugar by its users than is often possible with projects written in non-interpreted
languages.
------------------------------------------------------------------------------------------------------------------------------
Installing Python
Windows
1. Visit http://www.python.org
2. Click Download link to get the most recent version of Python
3. Click the Windows installer link to download the installer file
4. Store the Windows Installer file on your computer
5. Run the downloaded file by double-clicking it in Windows Explorer. Just accept the default settings,
wait until the installation in finished
S
6. Run the Python Integrated Development Environment(IDLE) by selecting Start→Programs→ Python
IDLE(Python GUI)
IC
Different Methods of using Python
YS
Python can be used in two modes. Interactive mode and file mode. Interactive mode can be termed as
calculator mode or shell mode due to its nature of operation. If we are opening Python without any
arguments in the command prompt of the Operating System, The interpreter will active with a display ‘>>>’.
This is called Command Prompt. Type a single python statement on this prompt and press the enter key. A
PH
complicated mathematical expression also will work. System will show the answer, if there is an answer to
display. Otherwise prompt will appear again. This interaction can be continued. So this method is called
Interactive Mode. This can be used as a calculator to view the result of simple or complicated calculations
including complex numbers and even to view graph. We can type an arithmetic expression at the prompt
and system will show the answer. The operators +, -, x and / will work like a calculator. So this mode can be
called as calculator mode. For example, type x=10 on the command prompt and press enter key. Since
C
nothing to display as answer, command prompt will appear again. Type y=5 and press enter key. Again
command prompt will appear. Type print x*y and press enter key. Just below the prompt, system will show
the answer. Command prompt will appear again.
K
Python programs are executer by an interpreter. When the interpreter starts, a prompt appears at which
S
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print "Hello World"
M
Hello World
>>>
Use this method only for viewing the results of single Python statements, for example to use Python as
Calculator It could be confusing when you start writing larger programs, having looping and conditional
statements. Everything your write in the interactive interpreter is lost when you quit. File Mode is the
preferred way in such a case.
2.File Mode - Saving & Executing Programs
In this mode, type the source code using any available text editor like notepad in Windows or gedit in
Linux. The filename must be with an extension ‘.py’. This can be compiled and operated by Python.
With IDLE you can simply create a new editor window with File→New Window. Type your program code
in this new window and select File→Save to save your program. To run your program select Run→Run
module.
S
Example :- Select File→New Window and type the following program
a=10
IC
b=5
print a*b
print a+b
YS
Save this program as first.py in a suitable directory by selecting File→Save. To run the program select
Run→Run module. The output screen will show
50
15
Comments PH
The hash sign(#) is a bit special in Python. When you put it in your code, everything to right of it is
ignored. It is useful in making programs easier to understand.
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.
K
Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for
example, Pascal or C); parentheses can be used for grouping. For example:
>>> 2+2
4
S
S
You could add the following statement to the beginning of your program or simply execute it in the
interactive interpreter:
IC
>>>from _ _future _ _ import division
>>>1/2
0.5
YS
Then the single slash ‘/’ can no longer be used for the kind of integer division.
>>>1//2
0
>>>1.0//2.0
0.0
PH
The double slash consistently performs integer division, even with floats
Modulus operator
This is the remainder operator. x%y gives the remainder of x divided by y
C
>>>1%2
1
>>>10%3
1
K
>>>2.75%0.5
0.25
Exponentiation operator
S
>>>2**3
8
E
>>>-3**2
-9
>>>(-3)**2
9
M
Large Integers
Ordinary integers can’t be larger than 2147483647 or smaller than -2147483648. If your want really big
numbers, you must use longs. A long (or long integer) is written just like an ordinary integer but with an L
or l at the end.
>>> 1987163987163981639186L*198765357892567L+23
394979361099869226585244079145330485L
You can mix long integers and plain integers as you like.
The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is displayed before the
next interactive prompt:
>>> width = 20
>>> height = 5*9
>>> width * height
900
S
>>> x = y = z = 0 # Zero x, y and z
>>> x
IC
0
>>> y
0
>>> z
YS
0
Variables must be “defined” (assigned a value) before they can be used, or an error will occur:
There is full support for floating point; operators with mixed type operands convert the integer operand to
C
floating point:
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
K
3.5
Complex numbers are also supported; imaginary numbers are written with a suffix of j or J. Complex
numbers with a nonzero real component are written as (real+imagj), or can be created with the
S
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
M
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
Complex numbers are always represented as two floating point numbers, the real and imaginary part. To
extract these parts from a complex number z, use z.real and z.imag.
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
The conversion functions to floating point and integer (float(), int() and long()) don’t work for
complex numbers — there is no one correct way to convert a complex number to a real number. Use
abs(z) to get its magnitude (as a float) or z.real to get its real part.
S
>>> a=3.0+4.0j
>>> float(a)
IC
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
YS
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
PH
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are
using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
C
12.5625
>>> price + _
113.0625
>>> round(_, 2)
K
113.06
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would
create an independent local variable with the same name masking the built-in variable with its magic
S
behavior.
Most of the programs require some input from the user. Input statements are the instructions in python to
input a data from keyboard to computer. The most common formats of input statements are the following.
There are mainly two functions used for this purpose
1. input() for numeric type
2. raw_input() for string type
The message to be displayed can be given as an argument while calling these functions. It is also possible
to read more than one variable using a single input() statement.
S
The general syntax of this instruction is
IC
Variable list separated by comma = input(message within quotes which is optional)
The number of variables in the list must match with the number of data typed through keyboard. In
python, we can mix all data types in a single instruction. The allocation of date type for each variable is
YS
automatic. For example on execution of instruction, x = input (‘Enter the number ‘) type 10. Then
computer will treat x as an integer data. If we are typing 10.0 computer will treat x as a float. If it is ’10.0’,
computer will treat it as a string. This is called dynamic data type.
>>>
x:12
>>>
x=input('x: ')
y=input('y: ')
PH
y:54
>>> print x*y
648
C
>>> s=raw_input(‘Enter a string’)
Eg:- xyinput.py
K
# Program to read more than one variable using a single input() statement.
x,y=input(‘enter x and y separated by comma’)
print ‘the sum is’,x+y
s=raw_input(‘Enter a decimal number’)
S
a=float(s)
print s*2 #prints string twice
print a*2 #converted value times 2
E
Variables
A variable is basically a name that represents (or refers to) some value. Python supports numeric data
types like integers, floating point numbers and complex numbers. To handle character strings, it uses the
M
String data type. Python also supports other compound data types like lists, tuples, dictionaries etc.
Variable names can consist of letters, digits, and underscore characters(_). A variable can’t begin with a
digit. Explicit declaration of the variables is not required in Python. The data type of a variable is decided
by the value assigned to it. This is called dynamic data typing. The type of a particular variable can
change during the execution of the program. Strings are enclosed within single quotes or double quotes.
At any stage we can convert one type to another using type casting operator as follows
x=float(y)
x=int(x)
Rules of naming the variable
1. Any alphanumeric character combination is permitted.
2. A variable name must start with an alphabet or _.
3. White space is not permitted in the name.
4. Underscore (‘_’) is permitted.
5. Variables are case sensitive. That means for a computer ‘mark’ and ‘Mark’ are two different quantities.
6. Permitted length of a variable name depends on microprocessor type.
7. Even though any character combination can be used as a variable name, better to use some meaningful
combinations of English alphabets for effective programming.
S
8. Keyword cannot be used as a variable name.
IC
Output statements
During the execution of a program, computer has to show some messages and answers on the screen.
YS
We can use the following patterns of output instructions to display a text or numeral on the screen
print x
print x,
print no,mark
print ‘Hello’
print ‘The answers are’,x,y
print (x+3)/y
PH
print ‘The sum of ’,x , ‘and’,y, ‘is’,x+y
messages and variables are separated by comma. Each print command will force the computer to start the
printing in a new line. But a trailing comma after a variable will make the next print in the same line.
C
Note the variation between “print a” and “print a,”. Go through the following python program to
demonstrate
more I/O instructions.
K
Example 1: io.py
#program to demonstrate input and output instructions
x=input('Enter an integer')
S
print complex(x)
y=raw_input ('enter a name')
print y
M
Case sensitivity
Python is a case sensitive language. The commands and keywords are defined in lowercase letters. So we
have to use lowercase itself. The variables can be in uppercase or lowercase. But the variables assigned in
lower case and uppercase are distinct.
Data Types
Before proceeding with a computational work, computer must know the exact nature of the data. This is
to save time and memory space. Depends on the nature of operation, python can deal with four numeric
data types and one string data type. The numeric data types are integer, float, long integer and complex.
Integer type means a plain integer without a decimal part. Accuracy of integer depends on microprocessor.
Normally it is with 32 bit accuracy. Python language cannot deal with an integer above this accuracy level.
To get integers of more accuracy we can use long integer. Float represents the decimal number with 32 bit
S
accuracy. The numbers higher than this will automatically shifts to exponential form. Complex numbers
can deal with real part and imaginary part. In python, the selection of data type is automatic. Computer
IC
determines the data types from the value of a variable. During a mathematical operation type may change
according to some implicit type conversion rules. So python is a dynamic data type system.
YS
During the program, we must give extra care to deal with data type. For example, let x=1, y=2, z= x/y. The
value of z becomes 0 which is undesirable. This is the truncated integer of 0.5. To solve such situations, we
have to convert one data type to another depends on situations. The instructions for this are known as
data type casting instructions.
z=float(x)/y
stored in z as a float.
z=float(x/y) will yield another result.
PH
This is to instruct the computer to convert x to decimal accuracy. Then calculate x/y. The answer is to be
4. z=complex(x,y) : Create a complex number with x as real part and y as imaginary part If y is omitted, it
defaults to zero. Eg:- x=2, y=3, z=complex(x,y), Then z=(2+3j)
5. y=str(x) : Convert a number to string. The output will not support any mathematical Functions
x=2.75 , y=str(x) ,Then value store for y will be=’2.75’. It doesn’t have any property of a number. Value
S
The instruction print type(x) is to know the data type of a quantity represented by x.
E
Assignment statement
Assignment statement is the statement to assign data to a variable name. ‘=’ is the assignment operator.
M
x=10
x=x+4.
It is to be remembered that the RHS may be a value or string or a mathematical expression. RHS must be a
variable name. x=y+10 is valid where as y+10=x is not a valid assignment. Python supports chain assignment
also.
x=y=z=12 is a valid chain assignment. A string also can be assigned to a variable
name=’Antony’
You can use it to switch the contents of two variables.
>>> x,y,z=1,2,3
>>> x,y=y,x
>>> print x,y,z
213
Augmented Assignments
Instead of writing x=x+1 , you can write x+=1. This is called an augmented assignment.
>>x=2
>>>x*=2
>>>x
6
S
Operators
IC
Operators are tokens that trigger some computation when applied to variables or elements of expressions.
Python supports a large number of operators to do computational works.
Unary operator: They are the operators that require only one operand to operate upon. Eg: +, -
YS
Binary operator: They are the operators that require two operands on left and right of operator.Eg: +, -, x etc.
Bitwise Operations
Bitwise operations are special operations in which the decimal numbers are first converted to binary number
number.
Eg:- Bitwise OR: |
PH
and bitwise logic is operated on each pair of bits and 0 or 1 is generated and then converted to decimal
The following list gives a brief description of commonly using operators and their functions.
K
Relational operators
These operators are binary operators, to check whether a mathematical condition is true or false. This is to take
a decision in ‘while loop’, ‘if loop’ etc. Always the result will be Boolean.
S
Logical Operators
S
IC
YS
PH
C
K
S
E
M
Assignment Operator
Assignment Operator connects the data with the variable.
Operator Symbol Example Result
Equal to = x=2 Value of x in memory location becomes 2
Remember that assignment equal to (=) and relational equal to (==) are with different meaning.
Precedence of operators
S
Operator Description
Lambda Lambda expression
IC
if-else Conditional Expression
Or Logical (Boolean) OR
And Logical (Boolean) AND
YS
Not Logical (Boolean) NOT
in, not in, is, is not, <, Comparisons, including membership tests and identity tests
<=,>,>=,<>,!=,==
| Bitwise OR
^ Bitwise XOR
&
<<, >>
+, -
PHBitwise AND
Left shift and right shift
Addition and subtraction
*, /, //, % Multiplication, division and remainder
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation
C
x[index], x[index:index], x(arguments...),
Subscription, slicing, call, attribute reference
x.attribute
(expressions...), [expressions...], Binding or tuple display, list display, dictionary display, string
K
On solving a mathematical expression, the actions of operators are based on some rules of precedence.
Computer will scan the expression from left to right. It will execute the first precedence operators in the
S
order of occurrence. Then again scan from left to right for second precedence operators for second
precedence operators and will execute the second precedence operators in the order of occurrence. This will
continue up to the final answer. At any instant precedence rule can be violated with the proper use of
E
parenthesis. The following table summarizes the operator precedence in Python, from lowest precedence (least
binding) to highest precedence (most binding). Operators in the same box have the same precedence.
M
Data Structures
A data structure is a collection of data elements (such as numbers or characters, or even other data structures) that is
structured in some way, such as by numbering the elements. The most basic data structure in Python is sequence.
Each element of a sequence is assigned a number- its position, or index. The first index is zero, the second index is one,
and so forth. You can also cont from the end: the last item of a sequence is number -1, the next-to-last -2, and so forth.
Python has six built-in types of sequences. They are lists, tuples, strings, Unicode strings, buffer objects and xrange
objects.
The main difference between lists and tuples is that you can charge a list, but you can’t change a tuple. This means a
list might be useful if you need to add elements as you go along, while a tuple can be useful if, for some reason, you
S
can’t allow the sequence to change. Sequences are useful when you want to work with a collection of values. The
items of a list are separated by commas and enclosed in square brackets. Sequence can contain other sequences too.
IC
>>>Arun=['Arun K',30]
>>> Biju=['Biju N',42]
>>> database=[Arun,Biju]
YS
>>> database
[['Arun K', 30], ['Biju N', 42]]
Indexing PH
All elements in a sequence are numbered- from zero and upwards. You can access them individually with a number.
This is called indexing. You use an index to fetch an element.
>>>greeting=’Hellow’
>>>greeting[0]
‘H’
>>>’Hello’[1]
C
‘e’
Example:
# To print date, given year, month
months=['January','February','March','April','May','June','July','August','September','October','November','December']
K
endings=['st','nd','rd']+17*['th']\
+['st','nd','rd']+7*['th']\
+['st']
S
year=raw_input('Year: ')
month=raw_input('Month (1-12): ')
day=raw_input('Day (1-31):')
E
month_number=int(month)
day_number=int(day)
month_name=months[month_number-1]
ordinal=day+endings[day_number-1]
S
>>> n[3:6]
[4, 5, 6]
>>> n[0:1]
IC
[1]
In short, you can supply two indices as limits for your slice, where the first is inclusive and the second is exclusive.
n[7:10]
YS
[8, 9, 10]
>>> n[-3:-1]
[8, 9]
>>> n[-3:0]
[]
PH
That means, any time the leftmost index in a slice comes later in the sequence than the second index the result is
always an empty sequence (in the above example the third-to-last coming later than the first).
>>> n[-3:]
[8, 9, 10]
>>> n[:3]
C
[1, 2, 3]
>>> n[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
K
In a regular slice, the step size is one, which means that the slice “moves” from one element to the next, returning all
the elements between the start and end.
>>> n[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
S
If the step sixe is set to a number greater than one, elements will be skipped.
>>> n[0:10:1]
E
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>n[0:10:2]
[1, 3, 5, 7, 9]
>>> n[3:6:3]
M
[4]
>>> n[::4]
[1, 5, 9]
The step size can’t be zero, but it can be negative, which means extracting the elements from right to left.
>>> n[8:3:-1]
[9, 8, 7, 6, 5]
>>> n[10:0:-2]
[10, 8, 6, 4, 2]
>>> n[0:10:-2]
[]
>>> n[::-2]
[10, 8, 6, 4, 2]
>>> n[5::-2]
[6, 4, 2]
>>> n[:5:-2]
[10, 8]
In short, the first limit (the left most) is inclusive, while the second (right most) is exclusive. When you use negative
S
step size, you need to have the first limit (start index) that is higher than the second one.
Adding sequences
>>> [1,2,3]+[4,5,6]
IC
[1, 2, 3, 4, 5, 6]
>>> 'Good '+'Morning'
'Good Morning'
YS
You can’t concatenate a list and a string, although both are sequences.
>>> [1,2,3]+'String'
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
[1,2,3]+'String'
PH
TypeError: can only concatenate list (not "str") to list
Multiplication
Multiplying a sequence by a number x creates a new sequence where the original sequence is repeated x times.
>>> 'python'*3
'pythonpythonpython'
C
>>> [42]*5
[42, 42, 42, 42, 42]
You can initialize a list like this.
>>> [0]*5
K
[0, 0, 0, 0, 0]
>>> s=[None]*10
>>> s
[None, None, None, None, None, None, None, None, None, None]
S
Membership
To check whether a value can be found in sequence in operator is used. It checks whether something is true and
E
returns True for true and False for false. Such operators are called Boolean operators, and truth values are called
Boolean values.
>>> 'P' in 'Python'
True
M
S
>>> n=[100,34,678]
>>> len(n)
3
IC
max
Returns the largest element of the sequence.
>>> n=[100,34,678]
>>> max(n)
YS
678
min
Returns the smallest element of the sequence.
>>> n=[100,34,678]
>>> min(n)
34
STRINGS
PH
Any collection of alphabets, digits, special characters and white space is known as a character string in a computer
language. Any quantity assigned within the double quotes or single quotes for an input statement will be a string. Any
undeclared quantity received by raw_input also will be a string. The string addition, multiplication etc are quite
C
different from the numerical addition and multiplication. Strings can be used to
store names, information, status etc. Go through the following examples for strings.
x=’hello’
K
>>>’Let’s go’
Syntax Error: Invalid syntax
>>>’Let\’s go’
E
“Let’s go”
>>>print s[0]
h
>>>print s[4]
o
>>>print s[5]
w
>>>print s[-1]
w
# s[-1] indicates the last character of string s
+ and * operation on strings
a=’Good ’
b=’ Morning’
x=a+b
Then the value stored for x will be ’Good Morning’. This concept is called string concatenation.
The instruction x=3*a will assign “GoodGoodGood” for x.
Slicing of strings
Extracting a particular part of a string is known as slicing. This is an indexed operation. But slicing is done using two
S
indices. Indexing using s[a:b] extracts elements s[a] to s[b-1]. We can skip one of the indices. If the first index (a) is
skipped, slicing starts from the first element and if second index is skipped (b) slicing ends with the last element
>>>s=’demonstration’
IC
>>>print s[1:4]
emo
>>>print s[5:]
stration
YS
>>>print s[:4]
demo
>>>print s[0:30]
demonstration
Example : str1.py
#example to demonstrate string activities
s=’Indian’
PH
print s
print 3*s
print s[0:3]
C
print s[0:4]
print s[0:5]
print s[2:]
print s[:3]
K
#end
Running the program str.py will generate the following output
Indian
IndianIndianIndian
S
Ind
Indi
India
E
dian
Ind
String Methods
M
Find
Find method finds a substring within a larger string. It returns the leftmost index where the substring is found. If it
is not found -1 is returned.
>>>title=”Monty Python’s Flying Circus”
>>>title.find(‘Monty’)
0
>>>title.find(‘Python’)
6
>>>title.find(‘zircuss’)
-1
You may also supply a starting point for your search and, optionally and ending point.
S
>>> s.find('!!!')
16
>>> s.find('!!!',0,16) # Supplying starting and ending index
IC
-1
Note that the range specified by the start and stop values(second and third parameters) includes the first index but not
the second.
YS
split
Used to split a string into a sequence
>>>'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> 'Using the default'.split()
['Using', 'the', 'default']
PH
Note that if no separator is supplied, the default is to split on all runs of consecutive whitespace characters(spaces,
tabs, newlines and so on)
join
join is the inverse of split. It is used to join the elements of a sequence. The sequence elements that are to be joined
C
must all be strings.
>>>seq=[1,2,3,4,5]
>>>sepr=’+’
>>>sepr.join(seq) #trying to join a list of numbers
K
>>>seq=[‘1’,’2’,’3’,’4’,’5’]
>>>sepr.join(seq) #joining list of strings
‘1+2+3+4+5’
E
>>>dirs=’ ‘,physics’,’python’,’pythonnotes.doc’
>>> '\\'.join(dirs)
' \\physics\\python\\pythonnotes.doc'
M
>>> print'c:'+'\\'.join(dirs)
c: \physics\python\pythonnotes.doc
lower
The lower method returns a lower case version of the string
>>> 'Elementary Particles'.lower()
'elementary particles'
upper
Returns a copy of the string in which all the case based characters have been uppercased.
>>> 'Elementary Particles'.upper()
'ELEMENTARY PARTICLES'
title
Returns a copy of the string in which all the words are capitalized.
>>> 'elementary particles'.title()
'Elementary Particles'
S
swapcase
Returns a copy of the string in which all the case based characters have had their case swapped.
IC
>>> 'Elementary Particles'.swapcase()
'eLEMENTARY pARTICLES'
replace
Returns a string where all the occurrences of one string have been replaced by another.
YS
>>> 'This is a test'.replace('a','the')
'This is the test'
String Formatting
>>> '%s plus %s equals %s'%(1,3,4)
'1 plus 3 equals 4'
>>> '%f plus %f equals %f'%(1.1,0.5,1.6)
'1.100000 plus 0.500000 equals 1.600000'
PH
>>> '%.2f plus %.2f equals %.2f'%(1.1,0.5,1.6)
'1.10 plus 0.50 equals 1.60'
C
Mutable and Immutable Types
There is one major difference between string, set, tuple and list types. List and set are mutable but string and
tuple are immutable. We can change the value of an element in a list or set, add new elements to them and
remove any existing element. This is no t possible with string and tuple types.
K
LISTS
Lists much more flexible than string. The individual elements can be of any type like integer, float, complex, string
and even another list. Lists are defined by enclosing the elements inside a pair of square brackets and separated by
S
commas.
>>> l=[2.3,'A',3,'Khan']
>>> type(l)
E
<type 'list'>
>>> l[3]
'Khan'
>>> l[3]=28
M
>>> l
[2.2999999999999998, 'A', 3, 28]
Lists respond to the + (concatenation) and * (repetition) operators like strings. The result is a new list.
Python Expression Output Description
len[1,2,3] 3 Length
[1,2,3]+[4,5,6] [1,2,3,4,5,6] Concatenation
[‘Hi’]*4 [‘Hi’, ‘Hi’, ‘Hi’, ‘Hi’] Repetition
3 in [1,2,3] True Membership
for x in [1,2,3]: print x 123 Iteration
If you want to create a list from a string, you can use list function.
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']
S
[1, 7, 3]
You cannot assign to a position that doesn’t exist; if your list is of length 2, you cannot assign a value to index 10.
IC
Deleting Elements
Del statement is used to delete elements from a list.
>>> names=['Mary','Arun','Anu','Geetha']
>>> del names[2]
YS
>>> names
['Mary', 'Arun', 'Geetha']
List Methods
A method is function that is tightly coupled to some object, be it a list, a number, a string or whatever. In general, a
method is called like this:
object.method(arguments)
PH
Lists have several methods that allow you to examine or modify their contents.
len
Using len () you can find the total number of elements in a list.
C
>>> names=['Mary','Arun','Anu','Geetha']
>>> k=len(names)
>>> k
4
K
append
append method is used to append an object to the end of a list.
>>> lst=[1,2,3]
S
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
E
Count
Count method counts the occurrences of an element in a list. It returns zero if the element is not found in the list.
>>> ['to','be','or','not','to','be'].count('to')
M
2
>>> y=[[1,2],1,1,[2,1,[1,2]]]
>>> y.count(1)
2
>>> y.count([1,2])
1
>>>y.count(34)
0
insert
The insert method is used to insert an object into a list.
>>> n=[1,2,3,5,6,7]
>>> n.insert(3,'four')
>>> n
[1, 2, 3, 'four', 5, 6, 7]
pop
The pop method removes an element (by default, the last one) from the list and returns it. The pop method is the
S
only list method that both modifies the list and returns a value.
>>> x=[1,2,3]
>>> x.pop()
IC
3
>>> x
[1, 2]
>>> x.pop(0)
YS
1
>>> x
[2]
remove
>>> x=['to','be','or','not','to','be']
>>> x.remove('be')
PH
The remove method is used to remove the first occurrence of a value.
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x.remove('bee')
C
As you can see, only the first occurrence is removed, and you cannot remove something if it isn’t in the list to begin
with.
S
reverse
The reverse method reverses the elements in the list.
E
>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
M
>>> a=[1,1,[1,2],3,4,5]
>>> a.reverse()
>>> a
[5, 4, 3, [1, 2], 1, 1]
Note that if there is a list within a list, that list will not be reversed.
sort
The sort method is used to sort lists in place. Sorting “in place” means changing the original list so its elements are
in sorted order, rather than simply returning a sorted copy of the list.
>>> x=[4,6,2,1,7,9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> y=x.sort()
>>> print y
S
None
y contains ’None’ because sort modifies x but returns nothing.
IC
>>> x=[4,6,2,1,7,9]
>>> y=x[:] #x[:] is a slice containing all elements of x
>>> y.sort()
>>> x
YS
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
>>> y=x
>>> y.sort()
>>> x
[1, 2, 4, 6, 7, 9]
PH
>>> y
[1, 2, 4, 6, 7, 9]
C
Another way of getting a sorted copy of a list is using the sorted function.
>>> x=[4,6,2,1,7,9]
>>> y=sorted(x)
>>> x
K
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
S
sorted function can actually be used on any sequence, but will always return a list.
>>> sorted('Python')
['P', 'h', 'n', 'o', 't', 'y']
E
If you want to sort the elements in descending order, you can use sort (or sorted), followed by a call to the reverse
method.
>>> a=[4,6,2,1,7,9]
M
>>> a.sort()
>>> a.reverse()
>>> a
[9, 7, 6, 4, 2, 1]
Advanced sorting
If you want to have your elements sorted in a specific manner, you can define your own comparison fuction, of the
form, of the form cmp(x,y) which returns a negative number when x<y, a positive number when x>y and zero when
x==y. You can supply this as a parameter to sort().
>>> cmp(42,67)
-1
>>> cmp(18,8)
1
>>> cmp(12,12)
0
>>> n=[5,2,4,90,65]
>>> n.sort(cmp)
>>> n
S
[2, 4, 5, 65, 90]
The sort method has two other optional arguments: key and reverse. If you want to sort the elements according to
IC
their lengths, you can use len as the key function.
>>> x=['coconut','grape','mango','tomato']
>>> x.sort(key=len)
>>> x
YS
['grape', 'mango', 'tomato', 'coconut']
The other keyword argument, reverse is simply a truth value (True or False)
>>> a=[4,6,2,1,7,9]
>>> a.sort(reverse=True)
>>> a
[9, 7, 6, 4, 2, 1]
PH
The cmp, key and reverse arguments are available in the sorted function as well.
Len
Returns number of elements a sequence contains.
C
>>> n=[100,34,678]
>>> len(n)
3
max
K
min
Returns the smallest element of the sequence.
>>> n=[100,34,678]
E
>>> min(n)
34
in and Not in
M
in and not in are test statements (operators) to find whether a particular element is in the list or not. The operator
will return True or False depending on the test result
>>> a=[1,5,4,6,7]
>>> 5 in a
True
>>> 13 in a
False
>>> s=5 in a
>>> print s
True
>>> 12 not in a
True
>>> t=12 not in a
>>> print t
True
sum
S
The sum of all elements in a list can be evaluated by sum function.
>>> a=[1,5,4,6,7]
>>> b=sum(a)
IC
>>> print b
23
SETS
YS
Python supports defining and manipulating sets. A Set can be constructed by defining the elements of the set in the
following fashion. The sets module provides classes for constructing and manipulating unordered collections of
unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing
standard math operations on sets such as intersection, union, difference, and symmetric difference.Like other
collections, sets support x in set, len(set), and for x in set. Being an unordered collection sets do not record element
PH
position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
A Set can be constructed by defining the elements of the set in the following fashion.
set
>>> s=set([4,6,7,8])
>>> s
set([8, 4, 6, 7])
C
add
Sets are mutable. There is frozenset type, which represents immutable
An element can be added to the set by add().
K
>>> s.add(6)
>>> s
set([8, 4, 6, 7])
>>> s.add(2)
S
>>> s
set([8, 2, 4, 6, 7])
E
Note that since a set does not contain duplicate elements, if we add one of the members of s to s again, the add
function will have no effect. The same behavior occurs in the update function, which adds a group of elements to s
set.
>>> s.update([2,12,7,21])
M
>>> s
set([2, 4, 6, 7, 8, 12, 21])
The set function also provides a copy constructor. However, remember that the copy constructor will copy the set,
but not the individual elements.
>>> t=s.copy()
>>> t
set([2, 4, 21, 6, 7, 8, 12])
in and not in
You can check if an object is in the set using the same in operator as with sequential data types.
>>> s=set([2, 4, 6, 7, 8, 12, 21])
>>> 2 in s
True
>>> 34 in s
False
We can also test the membership of entire sets. Given two sets s and [2,4,21,6,7,8,12,22], we can check if s is a
S
subset of the given set.
>>> s.issubset([2,4,21,6,7,8,12,22])
True
IC
>>> s.issubset([2,4,21,6,7,8,22])
False
>>> s.issuperset([4,6])
True
YS
>>> s.issuperset([1,4,9])
False
>>> t=set([2,4,21,6,7,8,12,22])
>>> s.issubset(t)
True
PH
The <= and >= operators also express the issubset and issuperset functions respectively.
>>> set([2,3,56])<=set([4,5,2,3,7,56])
True
>>> set([2,3,56])>=set([2,3])
True
C
>>> print n
4
Removing elements
S
There are three function which remove individual items from a set, called pop, remove and discard.
pop
pop simply removes an item from the set. There is no defined behavior as to which element it chooses to remove.
E
>>> s=set([1,2,3,4,5,6])
>>> s.pop()
1
>>> s
M
set([2, 3, 4, 5, 6])
Using remove function a specified element can be removed from the set.
>>> t=set([5,6,7,8,9])
>>> t.remove(9)
>>> t
set([8, 5, 6, 7])
Removing an item which is not in the set causes an error. If you wish to avoid this error, use discard. It has the
same functionality as remove, but will simply do nothing if the element isn’t in the set. clear() removes all elements
from the set.
>>> t.clear()
>>> t
set([])
union
The union is the merger of two sets. Any element in S1 or S2 will appear in their union.
S
>>> s1=set([4,6,9])
>>> s2=set([1,4,86,9])
>>> s1.union(s2)
IC
set([1, 4, 86, 6, 9])
>>> s1
set([9, 4, 6])
>>> s1|s2
YS
set([1, 4, 86, 6, 9])
intersection
Any element which is in both s1 and s2 will appear in their intersection.
>>> s1=set([4,6,9])
>>> s2=set([1,4,86,9])
>>> s1.intersection(s2)
set([9, 4])
PH
>>> s1&s2
set([9, 4])
>>> s1.intersection_update(s2)
C
>>> s1
set([9, 4])
Symmetric Difference
K
The symmetric difference of two sets is the set of elements which are in one of either set, but not in both.
>>> s1=set([4,6,9])
>>> s2=set([1,6,8])
>>> s1.symmetric_difference(s2)
S
set([8, 1, 4, 9])
>>> s1^s2
set([8, 1, 4, 9])
E
>>> s1.symmetric_difference_update(s2)
>>> s1
set([8, 9, 4, 1])
M
difference
Returns a new set with elements in s1 but not in s2.
>>> s1=set([4,6,9])
>>> s2=set([1,6,8])
>>> s1-s2
set([9, 4])
Multiple sets
Starting with Python 2.6, union, intersection and difference can work with multiple inputs by using the set
constructor.
>>> s1=set([3,6,7,9])
>>> s2=set([16,7,9,10])
>>> s3=set([7,9,10,11])
>>> set.intersection(s1,s2,s3)
set([9, 7])
S
Frozenset
A frozenset is basically the same as a set, except that is immutable- once it is created, its members cannot be
changed. Since they are immutable, they are also hashable, which means that frozensets can be used as members
IC
in other sets and as dictionary keys. Frozenset have the same functions as normal sets, except none of the
functions that change the contents (update, remove, pop etc.) are available.
>>> fs=frozenset([2,3,4])
>>> s1=set([fs,4,5,6])
YS
>>> s1
set([4, frozenset([2, 3, 4]), 6, 5])
>>> fs.intersection(s1)
frozenset([4])
>>> fs.add(6)
by commas in a pair of braces { }. Dictionaries consist of pairs (called items) of keys and their corresponding values.
Each key is separated from its value by a colon : ,the items are separated by commas, and the whole thing is
enclosed in curly braces The values in a dictionary don’t have any particular order but are stored under a key, which
may be a number, string or even a tuple. Keys are unique within a dictionary. Values do not need to be unique
S
within a dictionary.
>>> phonebook={'Raj':9446562323,'Ram':9898787822,'Mini':9878787878}
E
>>> rajnum=phonebook['Raj']
>>> print rajnum
9446562323
>>> print phonebook['Mini']
M
9878787878
>>> phonebook['Kumar']=9887676521
>>> print phonebook
{'Mini': 9878787878L, 'Ram': 9898787822L, 'Raj': 9446562323L, 'Kumar': 9887676521L}
>>> print phonebook['Kumar']
9887676521
Use dict function to construct dictionaries from other mappings or from sequences of (key, value) pairs.
>>> items=[('name','Arun'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'Arun'}
>>> d['name']
'Arun'
S
{'age': 25, 'name': 'Ankith'}
It is not possible to sort a dictionary like a list.
IC
Basic Dictionary Operations
• len(d) : returns the number of items (key-value pairs) in d.
• d[k] : returns the value associated with the key k.
• d[k]=v : associates the value v with the key k
YS
• del d[k] : deletes the item with key k.
• k in d : checks whether there is an item in d that has the key k.
Although dictionaries and lists share several common characteristics, there are some distinctions:
Key Types: Dictionary keys don’t have to be integers. They may be any immutable type, such as float, strings or
tuples
PH
Automatic addition: You can assign a value to a key, even if that key isn’t in the dictionary to begin with; in that
case, a new item will be created. You cannot assign a value to an index outside the list’s range (without using
append or something like that)
Membership : The expression k in d (where d is a dictionary) looks for a key, not a value. The expression v in l, on
the other hand (where l is a list) looks for a value not an index.
C
Dictionary methods
Clear
The clear method removes all items from the dictionary. This is an in-place operation, so it returns nothing.
K
>>> d={}
>>> y=d
>>> d['name']='Neena'
>>> d['age']=23
S
>>> d
{'age': 23, 'name': 'Neena'}
>>> d.clear()
E
>>> d
{}
>>> y
{}
M
Copy
The copy method returns a new dictionary with the same key-value pairs.
>>> x={'name':'Liya','marks':46}
>>> y=x.copy()
>>> y['name']='Babu'
>>> y['marks']=35
>>> y
{'name': 'Babu', 'marks': 35}
>>> x
{'name': 'Liya', 'marks': 46}
When you replace a value in the copy, the original is unaffected. If you modify a value, the original is changed as
well because the same value is stored there. One way to avoid that problem is to make a deep copy, copying the
values, any values they contain and so forth as well. To use deep copy function you have to import copy module.
fromkeys
The fromkeys method creates a new dictionary with the given keys, each with a default corresponding value of
None.
S
>>> {}.fromkeys(['name','age'])
{'age': None, 'name': None}
IC
Above expression constructs an empty dictionary and then calls the fromkeys method on that. Instead, you can call
the method directly on dict, which is the type of all dictionaries.
>>> dict.fromkeys(['name','age'])
{'age': None, 'name': None}
YS
If you don’t want to use None as the default value, you can supply your own default.
>>> dict.fromkeys(['name','age'],'(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}
get
PH
The get method is a way of accessing dictionary items. Usually, when you try to access an item that is not present
in the dictionary, an error message will be displayed.
>>> print d['name']
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
C
print d['name']
KeyError: 'name'
But when you use get to access a nonexistent key, there is no exception (error message). Instead you get the calue
K
None. You may supply your own default value, which is then used instead of None. If the key is there, get works
like ordinary dictionary lookup.
>>> print d.get('name')
None
S
>>> d.get('name','N/A')
'N/A'
>>> d['name']='Priya'
E
>>> d.get('name')
'Priya'
has_key
M
The has_key method checks whether a dictionary has a given key. The expression d.has_key(k) is equivalent to k in d
>>> d={}
>>> d.has_key('name')
False
>>> d['name']='Naveen'
>>> d.has_key('name')
True
items
The items method returns all the items of the dictionary as a list of items in which each item is of the form
(key,value). The items are not returned in any particular order.
>>> d={'name':'Arun','age':18,'marks':49}
>>> d.items()
[('age', 18), ('name', 'Arun'), ('marks', 49)]
keys
The keys method returns a list of eh keys in the dictionary.
S
pop
The pop method can be used to get the value corresponding to a given key, and then remove the key-value pair
IC
from the dictionary.
>>> d={'x':1,'y':2}
>>> d.pop('x')
1
YS
>>> d
{'y': 2}
popitem
The popitem method is similar to list.pop, which pops off the last element of a list. popitem pops off an arbitrary
PH
item because dictionaries don’t have a last element or any order
update
The update method updates one dictionary with items of another.
>>> d={ 'x':1,'y':15,'z':8}
>>> e={'r':5,'s':1,'y':4}
C
>>> d.update(e)
>>> d
{'s': 1, 'r': 5, 'y': 4, 'x': 1, 'z': 8}
>>> e
K
The items in the supplied dictionary are added to the old one, supplanting any items there with the same keys.
S
values
The values method returns a list of the values in the dictionary. Unlike keys the list returned by values may
contain duplicates.
E
>>> d={}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=34
M
>>> d[4]=1
>>> d.values()
[1, 2, 34, 1]
Tuples
A tuple, like a list, is a container that can hold an arbitrary number of objects of different data types. Tuples are
immutable that is their elements cannot be modified; elements cannot be added to or removed from the tuple. An
error message is generated whenever the removal or addition of elements is attempted. Tuples can be created by
specifying a set of objects separated by commas (it is optional to use a pair of ordinary parenthesis)
>>> a=1,2,4,'hello'
>>> print a
(1, 2, 4, 'hello')
>>> print type(a)
<type 'tuple'>
>>> b=(1,2,3,4,'hello')
>>> print b
(1, 2, 3, 4, 'hello')
S
>>> print type(b)
<type 'tuple'>
>>> k=a[0]
IC
>>> print k
1
>>> m=b[4]
>>> print m
YS
hello
The comma is crucial. So you have to include a comma, even though there is only one value.
>>> 42,
(42,)
>>> (42,)
(42,)
PH
tuple function can also be used to create a tuple.
>>> tuple([1,2,3])
(1, 2, 3)
C
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)
K
Blocks: Indentation
A block is a group of statements that can be executed if a condition is true (conditional statements), or executed
S
several times (loops) and so on. A block is created by indenting a part of your code; that is, putting spaces in front
of it. You can use tab characters to indent your blocks as well. Each line in a block must be indented by the same
amount. In Python, a colon (:) is used to indicate that a block is about to begin, and then every line in that block is
E
Conditionals
Conditional statements are needed whenever a decision is to be taken according to some specific conditions that
M
may arise during the execution of a program. Conditionals are where a section of code is only run if certain
conditions are met.
The following values are considered by the interpreter to mean false when evaluated as a Boolean expression (as
the condition of an if statement)
False None 0 “” () [] {}
In other words, the standard values False, None, numeric zero of all types, empty sequences (such as empty strings,
tuples and lists) and empty dictionaries are all considered to be False. Everything else is interpreted as true,
including the special value True.
if statement
If the condition (the expression after if but before the colon) evaluates true, the following block is executed. If the
condition is False, then the block is not executed.
Example: largest.py
a,b=input("Enter two numbers:")
if(a<b):
print b," is the largest number"
Output
S
Enter two numbers:67,342
342 is the largest number
IC
Remember that you MUST have a colon : at the end of every line with an ‘if’, ‘elif’, ‘else’, ‘while’, ‘for’. The colon :
instructs the Python interpreter to execute the indented block of code below the conditional statement
else statement
YS
If there is an else clause along with an if statement the block after the else clause is executed if the if condition is
evaluated False.
Example:else.py
n=input("Enter the password: ")
if n==5645:
print "Access Granted"
else:
print " Incorrect password"
PH
elif statement
If you want to check for several conditions, you can use elif, which is short for ‘else if’. It is a combination of an if
C
clause and an else clause- an else clause with a condition.
Example:elif.py
n=input('Enter a number')
K
if n>0:
print 'The number is positive'
elif n<0:
print 'The number is negative'
S
else:
print 'The number is zero'
E
Nested if statements
You can gave if statements if statements inside other if statement blocks, as follows.
a,b,c=input('Enter three numbers: ')
if a>b:
M
if a>c:
print "The largest number is ",a
else:
print "The largest number is ",c
elif b>c:
print"The largestr number is ",b
else:
print "the largest number is",c
Comparisons can be chained in Python, just like assignments. Eg:- 10<age<30
ITERATIONS AND LOOPING
In computer programming certain tasks will be required to get executed repeatedly until some specific conditions
are met. Iteration is the name for repeated execution of certain tasks. for and while are the two important
statements for producing iterating loops in Python language
While Loop
While statement is followed by a condition and the indented block of code below this statement is executed
repeatedly while the said condition is true. The while statement is very flexible. It can be used to repeat a block of
code while any condition is true.
S
#program to print 1 to 10
x=1
while x<=10:
IC
print x
x=x+1
Example: factorial.py
YS
factorial=1
i=1
x=input('Enter a number: ')
if x>10:
print 'The Number is too large'
else:
while i<=x:
factorial=factorial*i
PH
i+=1
print x,'!= ',factorial
C
Example:squarelist.py
'''program to generate a list which contains square of +ve no:s starting from
1 upto a given no:'''
limit=int(input('Enter the limit : '))
K
i=1
newlist=[]
while i<=limit:
newlist.append(i*i)
S
i+=1
print newlist
E
For Loop
For loops are used when we have a block of code, that we want to repeat a specified (n) number of times. The ‘for’
statement, in most cases, accompanied by the range function. Python ‘for’ loop iterates over a compound data
type like a string, list, tuple. During each iteration, one member of the compound data is assigned to the loop
M
variable. For constructing ‘for’ loops that executes a fixed number of times, we can create a list using the range()
function and run the for loop over that. The range function can be used the following ways.
1. With a single index – for x in range(5). The iterations will be done for values of x form x=0 to x=4 ( a total of 5
values will be generated)
2. With two indices – for x in range(1,5). The starting value is the first index (1 in this case). The ending value is the
last index minus one (4 in this case)
3. With three indices - for x in range(5,51,5). Here the last index is the step value. The values are iterated in steps
of 5 starting from 5 to 50.
Example:multpclntable.py
for i in range (1,6):
for j in range(1,11):
print '%d * %d = %d'%(j,i,i*j)
Example: for loop using an already defined list
b=['hello',3.4,2345,3+5j]
for x in b:
print x,type(x)
S
Breaking out of loops
Usually, a loop simply executes a block until its condition becomes false, or until it has used up all sequence
IC
elements. But sometimes you may want to interrupt the loop, to start a new iteration, or to simply end the loop.
Then you can use one of the following statements.
break
YS
break statement is used to terminate a loop, if some condition is met.
Example:If you want to find the largest square below 100. Then you start at 100 and iterate downward to 0. When
you’ve found a square, there is no need to continue, so you simply break out of the loop.
continue
The continue statement is used to skip the rest of the block and go to the beginning again.
x=1
K
while x<15:
if x%3==0:
x=x+1
continue
S
print x
if x==13:
break
E
x=x+1
FUNCTIONS
M
Large program can be divided into small logical units. A function is a small isolated unit of code with a name and it
can perform a definite work. From any part of the programme, we can call this function by name. Then computer
will execute that code to do the defined job. When we are calling a function, we have to pass some data
to the function, for its proper working. These data variables are called arguments. On getting the arguments,
function will execute the instructions for doing the prescribed work. After doing it, control will return back to main
program with one or more answers. Functions are divided into user defined functions or built in functions or
library functions.
User defined functions
Functions can be defined using the keyword def. The def statement is followed by the form of the function and a
colon. The return statement is used to return something from the function. The variables you write after your
function name in def statement are often called the formal parameters of the function. The values you supply
when you call the function are called the actual parameters or arguments.
Example:
'''two simple functions sqr and sqrt'''
def sqr(x):
return x*x
S
def sqrt(x):
return x**0.5
sqrs=[]
IC
sqrts=[]
for k in range(1,11):
sqrs.append(sqr(k))
sqrts.append(sqrt(k))
YS
print sqrs
print sqrts
Example:fibo.py
#fibonacci series
def fibo(x,y,n):
series=[]
series.append(x)
series.append(y)
PH
for i in range(2,n):
series.append(series[i-1]+series[i-2])
return series
C
k=fibo(1,1,10)
print k
Values can be given to the parameters in the def statement itself. Such a parameters are called keyword
K
parameters.
>>>def tempfn(x=3,s=’hellow’)
Example:
S
a=42
def temp():
a=00
E
temp()
print a
Value 42 prints, when variables are assigned inside a function they are always bound to the functions local name
space.
M
BUILT IN FUNCTIONS
One of the major advantages of Python is the availability of various libraries for various applications like scientific
computation, graphics, networking etc. The standard library is divided into many modules like time, random, pickle,
system etc. Each module consists of many built in functions. To get the service of such functions, we have to instruct
the compiler to load the corresponding module or function-library to RAM. Following are some examples
S
from math import sin
x=30*3.14/180
print sin(x)
IC
Here we are loading the function to calculate sin(x) from the module named math. But with this type loading, we can
calculate only sin(x) from math library. Other functions defined in math library will not work. The same thing can do in
an another way.
YS
from math import *
x=30*3.14/180
print sin(x), cos(x)
In this example, we are importing the entire mathematical library. So we can call any functions defined in that module.
There is another method to do the same thing.
import math
print math.sin(x)
PH
print math.cos(x)
If the library name is large, the same instructions can be in another form.
C
import math as m
print m.sin(x)
print m.cos(x)
K
ceil(x) : Function returns the smallest integer value greater than or equal to x. Input x must be float.
E
x=12.8
y=12.3
ceil(x)=13
ceil(y)=13
M
floor(x) : Function returns the smallest integer value less than or equal to x. Input x must be float.
x=12.8
y=12.3
floor(x)=12
floor(y)=12
fabs(x) : Function returns the absolute value of x as a float. Input x may be integer or float.
factorial(x): Function returns factorial of x as an integer. X must be a positive integer.
fmod(x, y) : Function returns the reminder in x/y as a float. Inputs may be integer or float. It is almost identical to x%y.
But there may be a slight difference in accuracy. According to the developing team of Python fmod() is more accurate
when working with floats, while x%y is more accurate when working with integers.
x=10
y=9
fmod(x,y)=1.0
fsum(x) : Function returns an accurate floating point sum of values in the list named x
x=[.1,.2,.3,.4]
fsum(x)=1.0
S
trunc(x): Function returns the integer part of the float x after truncation.
x=12.473
IC
>>> trunc(x)
12
MODULES
YS
In Python, the definitions of functions, variables, constants may be saved in a file and use them in a script or in an
interpreter just like header files in C language. Such a file is called a module. The file name is the module name
with suffix .py appended. Within a module, the name of the module is assigned to the global variable __name__.
Definitions from a module can be imported into other modules or into the main module. Python comes with a
library of standard module; described in a separate document, the Python Library Reference. Examples of some
PH
standard modules are math, os, random, pylab, numpy etc. The main advantage of creating and using modules is
that longer programs can be split into several files so that maintenance of code is easy and can be reused in several
programs by including the file with the keyword import at the beginning of the program.
a,b=0,1
while b<=n:
result.append(b)
a,b=b,a+b
S
return result
>>>import fibo
E
In the above program code fibo.fib2(4) , fibo is the module name and fib2 is the function defined within that
M
module. A period (.) separates the module name and the function name.
S
In the third and fourth cases, we need not type the module name every time. But there could be trouble if two
modules imported contains a function with same name. The sin() from numpy is capable of handling list argument.
IC
But sin() in math module can accept only a numeric type argument.
Example 5: conflict.py
from numpy import *
x=[0.1,0.2,0.3]
YS
print sin(x) #numpy’s sin can handle lists
from math import *
print sin(x) #sin() from math module replaces the sin() from numpy.
# Therfore an error occurs since sin() from math module cannot accept a list argument.
Scope of Variables
PH
Namespace is a dictionary that contains the names of the variables and their values. The namespaces are automatically
created and updated as a program runs. There are three levels of namespaces in Python:
1. Local namespace, which is created when a function is called. It contains the variables passed to the function as
arguments and the variables created within the function. The namespace is deleted when the function terminates. If a
variable is created inside a function, its scope is the function’s local namespace. It is not visible outside the function.
C
2. Global namespace is created when a module is loaded. Each module has its own namespace. Variables assigned
in a global namespace are visible to any function within the module.
3. Built-in namespace is created when the interpreter starts. It contains the functions that come with the Python
interpreter. These functions can be accessed by any program unit.
K
When a name is encountered during execution of a function, the interpreter tries to resolve it by searching the
following in the order shown: (1) local namespace, (2) global namespace, and (3) built-in namespace. If the name
cannot be resolved, Python raises a NameError exception. Since the variables residing in a global namespace are visible
S
to functions within the module, it is not necessary to pass them to the functions as arguments (although is good
programming practice to do so), as the following program illustrates.
E
Note that the variable c is created inside the function divide and is thus not accessible to statements outside the
function. Hence an attempt to move the print statement out of the function fails:
def divide():
c = a/b
M
a = 100.0
b = 5.0
divide()
print ’a/b =’,c
>>>
Traceback (most recent call last):
File ’’C:\Python22\scope.py’’, line 8, in ?
print 'a/b =',c
NameError: name 'c' is not defined
def divide():
c = a/b
print ’a/b =’,c
a = 100.0
b = 5.0
divide()
Output
>>>
a/b = 20.0
S
FILES
A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM
IC
You can open and use files for reading or writing by creating an object of the file class and using its read, readline or
write methods appropriately to read from or write to the file. The ability to read or write to the file depends on the
mode you have specified for the file opening. Then finally, when you are finished with the file, you call the close
method to tell Python that you are done using the file.
YS
open()
Syntax: file_object_name.open(filename,mode)
Opens a new file filename.
Explicitly specifying read mode has the same effect as not supplying a mode string at all. The write mode enables you to
S
write to the file. The '+' can be added to any of the other modes to indicate that both reading and writing is allowed.
So, for example, 'r+' can be used when opening a text file for reading and writing. (For this to be useful, you will
probably want to use seek as well). The 'b' mode changes the way the file is handled. Generally, Python assumes that
you are dealing with text files (containing characters). Typically, this is not a problem. But if you are processing some
E
other kind of file (called a binary file) such as a sound clip or an image, you should add a 'b' to your mode: for example,
'rb' to read a binary file.
M
writelines()
The writelines() method operates on a list just like readlines(), but takes a list of strings and writes them out to a file.
S
Line termination characters are not inserted between each line, so if desired, they must be added to the end of each
line before writelines() is called.
IC
Note that there is no "writeline()" method since it would be equivalent to calling write() with a single line string
terminated with a NEWLINE character.
Syntax: file_object_name.writelines(sequence_of_strings)
YS
Write the sequence of strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
FILE INPUT
read()
PH
The read() method is used to read bytes directly into a string, reading at most the number of bytes indicated. If no size
is given (the default value is set to integer -1) or size is negative, the file will be read to the end. It will be phased out
and eventually removed in a future version of Python.
Syntax : file_object_name.read([size])
print str2
Example :
f=open('greeting.txt','r')
str3=f.read(5) #reads first 5 characters
S
f.close()
print str3
E
readline()
The readline() method reads one line of the open file (reads all bytes until a line-terminating character like NEWLINE is
encountered). The line, including termination character(s), is returned as a string. Like read(), there is also an optional
size option, which, if not provided, defaults to -1, meaning read until the line-ending characters (or EOF) are found. If
M
readlines()
The readlines() method does not return a string like the other two input methods. Instead, it reads all (remaining) lines
and returns them as a list of strings. The optional size argument, if given, is an approximate bound on the total number
of bytes in the lines returned. If provided and greater than zero, approximately sizhint bytes in whole lines are read
(perhaps slightly more to round up to the next buffer size) and returned as a list.
Syntax: file_object_name.readlines([size])
In Python 2.1, a new type of object was used to efficiently iterate over a set of lines from a file: the xreadlines object
(found in the xreadlines module). Calling file.xreadlines() was equivalent to xreadlines.xreadlines(file). Instead of
reading all the lines in at once, xreadlines() reads in chunks at a time, and thus were optimal for use with for loops in a
memory-conscious way. However, with the introduction of iterators and the new file iteration in Python 2.3, it was no
longer necessary to have an xreadlines() method because it is the same as using iter(file), or in a for loop, is replaced by
for eachLine in file.
Another odd bird is the readinto() method, which reads the given number of bytes into a writable buffer object, the
S
same type of object returned by the unsupported buffer() built-in function. (Since buffer() is not supported, neither is
readinto().
IC
Core Note: Line separators are preserved
When reading lines in from a file using file input methods like read() or readlines(), Python does not remove the line
termination characters. It is up to the programmer. For example, the following code is fairly common to see in Python
code:
YS
f = open('myFile', 'r')
data = [line.strip() for line in f.readlines()]
f.close()
Similarly, output methods like write() or writelines() do not add line terminators for the programmer... you have to do it
yourself before writing the data to the file.
close()
PH
Closes the file. Sets data attribute closed to true. A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
Syntax: file_object_name.close()
C
Example : Using files
# Filename: using_file.py
poem = '''\
Programming is fun
K
break
print line, # Notice comma to avoid automatic newline added by Python
f.close() # close the file
Output
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
First, we create an instance of the file class by specifying the name of the file and the mode in which we want to open
the file. The mode can be a read mode ('r'), write mode ('w') or append mode ('a'). We first open the file in write mode
and use the write method of the file class to write to the file and then we finally close the file. Next, we open the same
file again for reading. If we don't specify a mode, then the read mode is the default one. We read in each line of the file
using the readline method, in a loop. This method returns a complete line including the newline character at the end of
the line. So, when an empty string is returned, it indicates that the end of the file has been reached and we stop the
loop.
Notice that we use a comma with the print statement to suppress the automatic newline that the print statement adds
because the line that is read from the file already ends with a newline character. Then, we finally close the file. Now,
S
see the contents of the poem.txt file to confirm that the program has indeed worked properly.
IC
Now we will examine how to read a text data from a file and convert it into numeric type.
Example:
f=open('numericdata.txt','w')
YS
for i in range (1,4):
s='%3d\n'%i
f.write(s)
f.close()
f=open('numericdata.txt','r')
while 1: #infinite loop
s=f.readline()
if s=='': #Empty string means end of file
PH
break #terminate the loop
m=int(s)
print m
C
f.close()
Strings can easily be written to and read form a file. When we have to read numbers form a file things become a little
bit difficult. We should know the exact nature of the numeric data type existing in the file. Further, when you may
want to save more complex data types like lists, dictionaries, or class instances, things get a lot more complicated.
Python provides a standard module called ‘pickle’ using which you can store any Python object in a file and then get it
S
There is another module called cPickle which functions exactly same as the pickle module except that it is written in the
E
C language and is (upto 1000 times) faster. You can use either of these modules, although we will be using the Pickle
module here. Remember though, that we refer to both these modules as simply the pickle module.
import pickle
f=open('testpickle.txt','w')
pickle.dump(123.334,f) #writes a float type
f.close()
f=open('testpickle.txt','r')
x=pickle.load(f)
print x,type(x)
f.close()
Example :
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data' # the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
f = file(shoplistfile, 'w') # Write to the file
p.dump(shoplist, f) # dump the object to a file
f.close()
S
del shoplist # deletes the shoplist
f = file(shoplistfile) # Read back from the file
storedlist = p.load(f)
IC
print storedlist
Output
['apple', 'mango', 'carrot']
YS
How It Works
First, notice that we used import pickle as p. This makes programming easier since we can use a shorter name for a
module. In this case, it even allows us to switch to a different module (cPickle or pickle) by simply changing one line! In
the rest of the program, we simply refer to this module as p. To store an object in a file, first we open a file object in
write mode and store the object into the open file by calling the dump function of the pickle module. This process is
PH
called pickling. Next, we retrieve the object using the load function of the pickle module which returns the object.
This process is called unpickling.
Formatted Printing
% operator is used to format an output. Let us consider a variable x with floating point number stored into it. We
want to print the number with only two decimal places. The formatting is done in the following fashion.
C
If you are formatting real numbers (floats), you can use the f specifier type and supply the precision as a . (dot)
followed by the number of decimals you want to keep. The format specifier always ends with a type character, so
you must put the precision before that:
>>> print '%3.2f'%x
K
23.35
Here the formatting starts with a single quote followed by a % sign. Next characters do the formatting. Another
single quote is placed to end the formatting and after that the variable is given after a % sign. Spaces between the
formatting characters are optional.
S
A basic conversion specifier consists of the items that follow. Note here that the order is crucial.
• The % character : This marks the beginning of the conversion specifier.
E
• Conversion flags (optional) : These may be either -, indicating left alignment; +, indicating that a sign
should precede the converted value; “ ” (a space character), indicating that a space should precede
positive numbers; or 0, indicating that the conversion should be zero-padded.
M
• The minimum field width (optional): The converted string will be at least this wide. If this is an *
(asterisk), the width will be read from the value tuple.
• A . (dot) followed by the precision (optional) : If a real number is converted, this many decimals should
be shown. If a string is converted, this number is that maximum field width. If this is an * (asterisk), the
precision will be read from the value tuple.
S
o Unsigned octal '%o'%8 10
s String '%s'%'abcd' ‘abcd’
0d modified ‘d’ '%05d'%12 00012
IC
c Single character (accepts integer or single '%c'%'r' ‘r’
character string
YS
Right and Left justifications
a='Example for justification'
>>> print '%30s'%a #right justified
Example for justification
>>> print '%-30s'%a #minus sign for left justification
Example for justification
>>> for k in range(1,11):
print '5 x %2d= %2d'%(k,k*5)
PH
Output
5 x 1= 5
5 x 2= 10
C
5 x 3= 15
5 x 4= 20
5 x 5= 25
5 x 6= 30
K
5 x 7= 35
5 x 8= 40
5 x 9= 45
5 x 10= 50
S
E
M