Professional Documents
Culture Documents
ON
pg. 1
BONAFIDE CERTIFICATE
Signature Signature
Mr.V.J.GNANESWARAN.,B.E., Miss.A.VIGNESWARI.,B.TECH.,
pg. 2
ACKNOWLEDGEMENT
To matter what accomplishment, we achieve
somebody helps us. For every accomplishment we
need the cooperation and help of others. As
knowledge advantages by steps not by leaps so,
ability advances by encouragement and guidance.
Although you have ability and knowledge but is
worthless unless and until you can develop it if
somebody encourages you. I express my deep sense
of gratitude and feeling of indebtedness to
Miss.Vigneswari project guide, for their bold
attention in this particular time of project and guide
us as per according to progress of our project
pg. 3
Table of Contents
INTRODUCTION TO PYTHON .......................................................................................................... 5
Why the Name Python? ...................................................................................................................... 6
An Informal Introduction to Python .......................................................................................... 15
HISTROY ................................................................................................................................................. 34
Python Advantages and Disadvantages ................................................................................... 35
What is python? .................................................................................................................................. 39
Python Scopes and Name Spaces ................................................................................................ 40
Random Remarks ............................................................................................................................... 44
Python Features: ................................................................................................................................ 47
Why is python so popular? ............................................................................................................ 63
Why Learn python? ........................................................................................................................... 64
What is python used for? ................................................................................................................ 64
Is Python’s popularity a good thing ........................................................................................... 69
What are the benefits of Python’s high readability? .......................................................... 71
What type of jobs use python ....................................................................................................... 72
Errors and Exceptions...................................................................................................................... 75
Syntax and semantics ....................................................................................................................... 80
Statement and control flow ........................................................................................................... 80
Expression ............................................................................................................................................. 82
Methods: ................................................................................................................................................. 87
Summary: ............................................................................................................................................... 88
Python Features .................................................................................................................................. 88
Student Marksheet Program In Python Programming Language ................................ 89
Conditions for a student to pass the exam .............................................................................. 89
Condition for a student to fail in the exam ............................................................................. 89
CODING ................................................................................................................................................... 90
INPUT ...................................................................................................................................................... 91
OUTPUT .................................................................................................................................................. 92
Explanation of the program........................................................................................................... 93
pg. 4
INTRODUCTION TO PYTHON
pg. 5
Why the Name Python?
pg. 6
Whetting Your Appetite
If you ever wrote a large shell script, you
probably know this feeling: you’d love to add yet another
feature, but it’s already so slow, and so big, and so
complicated; or the feature involves a system call or other
function that is only accessible from C . . . Usually the
problem at hand isn’t serious enough to warrant rewriting
the script in C; perhaps the problem requires variable-
length strings or other data types (like sorted lists of file
names) that are easy in the shell but lots of work to
implement in C, or perhaps you’re not sufficiently familiar
with C. Another situation: perhaps you have to work with
several C libraries, and the usual C write/compile/test/re-
compile cycle is too slow. You need to develop software
more quickly. Possibly perhaps you’ve written a program
that could use an extension language, and you don’t want
to design a language, write and debug an interpreter for it,
then tie it into your application. In such cases, Python may
be just the language for you. Python is simple to use, but it
is a real programming language, offering much more
structure and support for large programs than the shell
has. On the other hand, it also offers much more error
checking than C, and, being a veryhigh-level language, it
has high-level data types built in, such as flexible arrays
and dictionaries that would cost you days to implement
efficiently in C. Because of its more general data types
Python is applicable to a much larger problem domain
than Awk or even Perl, yet many things are at least as easy
in Python as in those languages. Python allows you to split
up your program in modules that can be reused in other
Python programs. It comes with a large collection of
standard modules that you can use as the basis of your
pg. 7
programs — or as examples to start learning to program
in Python. There are also built-in modules that provide
things like file I/O, system calls, sockets, and even
interfaces to graphical user interface toolkits like Tk.
Python is an interpreted language, which can save you
considerable time during program development because
no compilation and linking is necessary. The interpreter
can be used interactively, which makes it easy to
experiment with features of the language, to write throw-
away programs, or to test functions during bottom-up
program development. It is also a handy desk calculator.
Python allows writing very compact and readable
programs. Programs written in Python are typically much
shorter than equivalent C or C++ programs, for several
reasons:
• the high-level data types allow you to express
complex operations in a single statement;
• statement grouping is done by indentation instead of
begin/end brackets;
• no variable or argument declarations are necessary.
Python is extensible: if you know how to program in C it is
easy to add a new built-in function or module to the
interpreter, either to perform critical operations at
maximum speed, or to link Python programs to libraries
that may only be available in binary form (such as a
vendor-specific graphics library). Once you are really
hooked, you can link the Python interpreter into an
application written in C and use it as an extension or
command language for that application.
By the way, the language is named after the BBC show
“Monty Python’s Flying Circus” and has nothing to do with
pg. 8
nasty reptiles. Making references to Monty Python skits in
documentation is not only allowed, it is encouraged!
Now that you are all excited about Python, you’ll want to
examine it in some more detail. Since the best way to learn
a language is using it, you are invited here to do so.
pg. 9
directory in your Unix shell’s search path makes it possible
to start it by typing the command
pg. 10
be able to use backspace to remove characters from the
current line.
pg. 11
Interactive Mode
When commands are read from a tty, the interpreter is
said to be in interactive mode. In this mode it prompts for
the next command with the primary prompt, usually three
greater-than signs (‘>>> ’); for continuation lines it
prompts with the secondary prompt, by default three dots
(‘... ’). The interpreter prints a welcome message stating its
version number and a copyright notice before printing the
first prompt:
python
Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06)
Copyright 1991-1995 Stichting Mathematisch Centrum
>>>
Continuation lines are needed when entering a multi-line
construct. As an example, take a look at this if statement:
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
... Be careful not to fall off!
pg. 12
The Interpreter and Its Environment
Error Handling
pg. 14
If you want to read an additional start-up file from the
current directory, you can program this in the global start-
up file using code like this:
if os.path.isfile(’.pythonrc.py’):
execfile(’.pythonrc.py’)
If you want to use the startup file in a script,
you must do this explicitly in the script:
import os
filename = os.environ.get(’PYTHONSTARTUP’)
if filename and os.path.isfile(filename):
execfile(filename)
pg. 15
Many of the examples in this manual, even those entered
at the interactive prompt, include comments. Comments in
Python start with the hash character, ‘#’, and extend to the
end of the physical line. A comment 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.
Some examples:
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
if Statements
pg. 16
... print ’Negative changed to zero’
... elif x== 0:
... print ’Zero’
... elif x== 1:
... print ’Single’
... else:
... print ’More’
...
There can be zero or more elif parts, and the else part is
optional. The keyword ‘elif’ is short for ‘else if’, and is
useful to avoid excessive indentation. An if ... elif ... elif . . .
sequence is a substitute for the switch or case statements
found in other languages.
for Statements
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
pg. 18
The given end point is never part of the generated list;
range(10) generates a list of 10 values, exactly the legal
indices for items of a sequence of length 10. It is possible
to let the range start at another number, or to specify a
different increment (even negative; sometimes this is
called the ‘step’)
break and continue Statements, and else Clauses on
Loops
The break statement, like in C, breaks out of the smallest
enclosing for or while loop.
The continue statement, also borrowed from C, continues
with the next iteration of the loop.
Loop statements may have an else clause; it is executed
when the loop terminates through exhaustion of the list
(with for) or when the condition becomes false (with
while), but not when the loop is terminated by a break
statement.
pass Statements
The pass statement does nothing. It can be used when a
statement is required syntactically but the program
requires no action.
Defining Functions
The keyword def introduces a function definition. It must
be followed by the function name and the parenthesized
pg. 19
list of formal parameters. The statements that form the
body of the function start at the next line, and must be
indented. The first statement of the function body can
optionally be a string literal; this string literal is the
function’s documentation string, or docstring. There are
tools which use docstrings to automatically produce
online or printed documentation, or to let the user
interactively browse through code; it’s good practice to
include docstrings in code that you write, so try to make a
habit of it. The execution of a function introduces a new
symbol table used for the local variables of the function.
More precisely, all variable assignments in a function store
the value in the local symbol table; whereas variable
references first look in the local symbol table, then in the
global symbol table, and then in the table of built-in
names. Thus, global variables cannot be directly assigned a
value within a function (unless named in a global
statement), although they may be referenced. 29 The
actual parameters (arguments) to a function call are
introduced in the local symbol table of the called function
when it is called; thus, arguments are passed using call by
value (where the value is always an object reference, not
the value of the object).1 When a function calls another
function, a new local symbol table is created for that call. A
function definition introduces the function name in the
current symbol table. The value of the function name has a
type that is recognized by the interpreter as a user-defined
pg. 20
function. This value can be assigned to another name
which can then also be used as a function.
Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a
function can be called with an arbitrary number of
arguments. These arguments will be wrapped up in a
tuple. Before the variable number of arguments, zero or
more normal arguments may occur.
Lambda Forms
By popular demand, a few features commonly found in
functional programming languages and Lisp have been
added to Python. With the lambda keyword, small
anonymous functions can be created. Here’s a function
that returns the sum of its two arguments: ‘lambda a, b:
a+b’. Lambda forms can be used wherever function objects
are required. They are syntactically restricted to a single
expression. Semantically, they are just syntactic sugar for a
normal function definition.
Documentation Strings
There are emerging conventions about the content and
formatting of documentation strings.
The first line should always be a short, concise summary
of the object’s purpose. For brevity, it should not explicitly
state the object’s name or type, since these are available
by other means (except if the name happens to be a verb
pg. 21
describing a function’s operation). This line should begin
with a capital letter and end with a period.
If there are more lines in the documentation string, the
second line should be blank, visually separating the
summary from the rest of the description. The following
lines should be one or more paragraphs describing the
object’s calling conventions, its side effects, etc.
The Python parser does not strip indentation from multi-
line string literals in Python, so tools that process
documentation have to strip indentation if desired. This is
done using the following convention. The first non-blank
line after the first line of the string determines the amount
of indentation for the entire documentation string. (We
can’t use the first line since 35 it is generally adjacent to
the string’s opening quotes so its indentation is not
apparent in the string literal.) Whitespace “equivalent” to
this indentation is then stripped from the start of all lines
of the string. Lines that are indented less should not occur,
but if they occur all their leading whitespace should be
stripped. Equivalence of whitespace should be tested after
expansion of tabs (to 8 spaces, normally).
pg. 22
Data Structures
This chapter describes some things you’ve learned about
already in more detail, and adds some new things as well.
More on Lists
The list data type has some more methods. Here are all of
the methods of list objects:
append(x)
Add an item to the end of the list; equivalent to
a[len(a):] = [x].
extend(L)
Extend the list by appending all the items in the given
list; equivalent to a[len(a):] = L.
insert(i, x)
Insert an item at a given position. The first argument is
the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and
a.insert(len(a), x) is equivalent to a.append(x).
remove(x)
Remove the first item from the list whose value is x . It
is an error if there is no such item.
pop([i ])
Remove the item at the given position in the list, and
return it. If no index is specified, a.pop() returns the last
pg. 23
item in the list. The item is also removed from the list.
(The square brackets around the i in the method signature
denote that the parameter is optional, not that you should
type square brackets at that position. You will see this
notation frequently in the Python Library Reference.)
index(x)
Return the index in the list of the first item whose
value is x . It is an error if there is no such item.
count(x)
Return the number of times x appears in the list.
sort()
Sort the items of the list, in place.
reverse()
Reverse the elements of the list, in place.
The del statement
There is a way to remove an item from a list given its
index instead of its value: the del statement. This can also
be used to remove slices from a list (which we did earlier
by assignment of an empty list to the slice).
pg. 24
Tuples and Sequences
We saw that lists and strings have many common
properties, such as indexing and slicing operations. They
are two examples of sequence data types. Since Python is
an evolving language, other sequence data types may be
added. There is also another standard sequence data type:
the tuple.
Dictionaries
Another useful data type built into Python is the
dictionary. Dictionaries are sometimes found in other
languages as “associative arrays” or “hashes”. Unlike
sequences, which are indexed by a range of numbers,
dictionaries are indexed by keys, which can be any
immutable type; strings and numbers can always be keys.
Tuples can be used as keys if they contain only strings,
numbers, or tuples; if a tuple contains any mutable object
either directly or indirectly, it cannot be used as a key. You
can’t use lists as keys, since lists can be modified in place
using their append() and extend() methods, as well as
slice and indexed assignments.
It is best to think of a dictionary as an unordered set of
key: value pairs, with the requirement that the keys are
unique (within one dictionary). A pair of braces creates an
empty dictionary: {}. Placing a commaseparated list of
key:value pairs within the braces adds initial key:value
pairs to the dictionary; this is also the way dictionaries are
written on output.
pg. 25
The main operations on a dictionary are storing a value
with some key and extracting the value given the key. It is
also possible to delete a key:value pair with del. If you
store using a key that is already in use, the old value
associated with that key is forgotten. It is an error to
extract a value using a non-existent key.
The keys() method of a dictionary object returns a list of
all the keys used in the dictionary, in random order (if you
want it sorted, just apply the sort() method to the list of
keys). To check whether a single key is in the dictionary,
use the has key() method of the dictionary.
pg. 26
‘spam.pyc’ file are platform independent, so a Python
module directory can be shared by machines of different
architectures.
pg. 27
• When a script is run by giving its name on the
command line, the bytecode for the script is never
written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time
of a script may be reduced by moving most of its code
to a module and having a small bootstrap script that
imports that module. It is also possible to name a
‘.pyc’ or ‘.pyo’ file directly on the command line.
Packages
Packages are a way of structuring Python’s module
namespace by using “dotted module names”. For example,
the module name A.B designates a submodule named ‘B’ in
a package named ‘A’. Just like the use of modules saves the
authors of different modules from having to worry about
each other’s global variable names, the use of dotted
module names saves the authors of multi-module
packages like NumPy or the Python Imaging Library from
having to worry about each other’s module names.
Suppose you want to design a collection of modules (a
“package”) for the uniform handling of sound files and
sound data. There are many different sound file formats
(usually recognized by their extension, for example: ‘.wav’,
‘.aiff’, ‘.au’), so you may need to create and maintain a
pg. 28
growing collection of modules for the conversion between
the various file formats. There are also many different
operations you might want to perform on sound data
(such as mixing, adding echo, applying an equalizer
function, creating an artificial stereo effect), so in addition
you will be writing a never-ending stream of modules to
perform these operations.
pg. 29
* is encountered. It is up to the package author to keep this
list up-to-date when a new version of the package is
released. Package authors may also decide not to support
it, if they don’t see a use for importing * from their
package
Intra-package References
The submodules often need to refer to each
other. For example, the surround module might use the
echo module. In fact, such references are so common that
the import statement first looks in the containing package
before looking in the standard module search path. Thus,
the surround module can simply use import echo or from
echo import echofilter. If the imported module is not
found in the current package (the package of which the
current module is a submodule), the import statement
looks for a top-level module with the given name.
When packages are structured into subpackages (as with
the Sound package in the example), there’s no shortcut to
refer to submodules of sibling packages - the full name of
the subpackage must be used. For example, if the module
Sound.Filters.vocoder needs to use the echo module in the
Sound.Effects package, it can use from Sound.Effects
import echo.
pg. 30
Input and 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. This chapter will discuss
some of the possibilities.
Fancier Output Formatting
So far we’ve encountered two ways of writing values:
expression statements and the print statement. (A third
way is using the write() method of file objects; the
standard output file can be referenced as sys.stdout. See
the Library Reference for more information on this.)
Often you’ll want more control over the formatting of
your output than simply printing space-separated values.
There are two ways to format your output; the first way is
to do all the string handling yourself; using string slicing
and concatenation operations you can create any lay-out
you can imagine. The standard module string contains
some useful operations for padding strings to a given
column width; these will be discussed shortly. The second
way is to use the % operator with a string as the left
argument. The % operator interprets the left argument
much like a sprintf()-style format string to be applied to
the right argument, and returns the string resulting from
this formatting operation.
One question remains, of course: how do you convert
values to strings? Luckily, Python has ways to convert any
value to a string: pass it to the repr() or str() functions, or
pg. 31
just write the value between reverse quotes (‘‘, equivalent
to repr()).
The str() function is meant to return representations of
values which are fairly human-readable, while repr() is
meant to generate representations which can be read by
the interpreter (or will force a SyntaxError if there is not
equivalent syntax). For objects which don’t have a
particular representation for human consumption, str()
will return the same value as repr(). Many values, such as
numbers or structures like lists and dictionaries, have the
same representation using either function. Strings and
floating point numbers, in particular, have two distinct
representations.
The pickle Module
Strings can easily be written to and read from a file.
Numbers take a bit more effort, since the read() method
only returns strings, which will have to be passed to a
function like string.atoi(), which takes a string like ’123’
and returns its numeric value 123. However, when you
want to save more complex data types like lists,
dictionaries, or class instances, things get a lot more
complicated.
Rather than have users be constantly writing and
debugging code to save complicated data types, Python
provides a standard module called pickle. This is an
amazing module that can take almost any Python object
(even some forms of Python code!), and convert it to a
pg. 32
string representation; this process is called pickling.
Reconstructing the object from the string representation is
called unpickling. Between pickling and unpickling, the
string representing the object may have been stored in a
file or data, or sent over a network connection to some
distant machine.
If you have an object x, and a file object f that’s been
opened for writing, the simplest way to pickle the object
takes only one line of code:
pickle.dump(x, f)
To unpickle the object again, if f is a file object which has
been opened for reading:
x= pickle.load(f)
(There are other variants of this, used when pickling
many objects or when you don’t want to write the pickled
data to a file; consult the complete documentation for
pickle in the Library Reference.)
pickle is the standard way to make Python objects which
can be stored and reused by other programs or by a future
invocation of the same program; the technical term for
this is a persistent object. Because pickle is so widely used,
many authors who write Python extensions take care to
ensure that new data types such as matrices can be
properly pickled and unpickled.
pg. 33
HISTROY
pg. 36
But even if you do, a Python package manager(pip) makes
things easier to import other great packages from the
python package index(pypi). It consists of over 200,000
packages.
7.Portability:
In many languages like C/C++, you need to
change your code to run the program on different
platforms. That is not the same with python. You only
write once and run it anywhere.
However, you should be careful not to include any system-
dependent features.
Disadvantages of python:
1.Slow speed:
We discussed above that python is an
interpreted language and dynamically-typed language.
The line by slow execution.
The dynamic nature of python is also responsible for the
slow speed of python because it has to do the extra work
while execution code. So, python is not used for purposes
where speed is an important aspect of the project
2.Not memory efficient:
To provide simplicity to the
developer, python has to do a little trade off. The python
programming language uses a large amount of memory.
pg. 37
This can be a disadvantage while building application
when we prefer memory optimization.
3.Weak in mobile computing:
Python is generally used in
server-side programming. We don’t get to see python on
the client-side or mobile application because of the
following reasons. Python is not memory efficient and it
has slow processing power as compared to other
languages.
4.Database access:
Programming in python us easy and
stress=free. But when we are interacting with the
database, it lacks behind.
The python’s database access layer is primitive and
underdeveloped in comparison to the popular
technologies like JDBC and ODBC.
Huge enterprises need smooth interaction of complex
legacy data and python is thus rarely used in enterprises.
5.Runtime errors:
AS we know python is a dynamically
typed language so the data type of a variable can change
anytime. A variable containing integer number may hold a
string in the future, which can lead to runtime errors.
Therefore python programmers need to perform through
testing of the applications.
pg. 38
Summary:
Python is a simple, versatile and a complete programming
language. It is a great choice for beginners up to
professionals. Although it has some disadvantages, we can
observe that the advantages exceed the disadvantages.
Even googls has made python one of its primary
programming languages.
What is python?
Python is an object-oriented (base
around data), high-level (easier for humans to
understand) programming language. First launched in
1992, It’s built in a way that it’s relatively intuitive to write
and understand. As such, it’s an ideal coding language for
those who want rapid development.
If you’re wondering who uses python, you’ll find that
many of the biggest organisation in the world implement it
in some form, NASA, Google, Netflix, Spotify, and countless
more all use the language to help power their services.
pg. 39
Python Scopes and Name Spaces
pg. 40
By the way, I use the word attribute for any name
following a dot — for example, in the expression z.real,
real is an attribute of the object z. Strictly speaking,
references to names in modules are attribute references:
in the expression modname.funcname, modname is a
module object and funcname is an attribute of it. In this
case there happens to be a 77 straightforward mapping
between the module’s attributes and the global names
defined in the module: they share the same namespace! 1
pg. 41
their own global namespace. (The built-in names actually
also live in a module; this is called builtin .)
pg. 42
If a name is declared global, then all references and
assignments go directly to the middle scope containing the
module’s global names. Otherwise, all variables found
outside of the innermost scope are read-only.
1Except for one thing. Module objects have a secret read-
only attribute called dict which returns the dictionary
used to implement the module’s namespace; the name dict
is an attribute but not a global name. Obviously, using this
violates the abstraction of namespace implementation,
and should be restricted to things like post-mortem
debuggers.
Random Remarks
pg. 44
access to an object if necessary; this can be used by
extensions to Python written in C.)
pg. 45
Any function object that is a class attribute defines a
method for instances of that class. It is not necessary that
the function definition is textually enclosed in the class
definition: assigning a function object to a local variable in
the class is also ok.
pg. 46
Python Features:
pg. 47
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.
pg. 48
➢ Support libraries
Python comes with a large collection of prebuilt and
portable functionality, known as the standard library. This
library supports an array of application-level
programming tasks, from text pattern matching to
network scripting. In addition, Python can be extended
with both home grown libraries and a vast collection of
third-party application support software. Python‘s third-
party domain offers tools for website construction,
numeric programming, serial port access, game
development, and much more (see ahead for a sampling).
➢ Component integration
Python scripts can easily communicate with other parts
of an application, using a variety of integration
mechanisms. Such integrations allow Python to be used as
a product customization and extension tool. Today, Python
code can invoke C and C++ libraries, can be called from C
and C++ programs, can integrate with Java and .NET
components, can communicate over frameworks such as
COM and Silverlight, can interface with devices over serial
ports, and can interact over networks with interfaces like
SOAP, XML-RPC, and CORBA. It is not a standalone tool.
➢ Enjoyment
Because of Python‘s ease of use and built-in toolset, it
can make the act of programming more pleasure than
chore. Although this may be an intangible benefit, its effect
on productivity is an important asset. Of these factors, the
first two (quality and productivity) are probably the most
pg. 49
compelling benefits to most Python users, and merit a
fuller description.
➢ It's Object-Oriented
Python is an object-oriented language, from the ground
up. Its class model supports advanced notions such as
polymorphism, operator overloading, and multiple
inheritance; yet in the context of Python's dynamic typing,
object-oriented programming (OOP) is remarkably easy to
apply. Python's OOP nature makes it ideal as a scripting
tool for object-oriented systems languages such as C++
and Java. For example, Python programs can subclass
(specialized) classes implemented in C++ or Java.
➢ It's Free
Python is freeware—something which has lately been
come to be called open source software. As with Tcl and
Perl, you can get the entire system for free over the
Internet. There are no restrictions on copying it,
embedding it in your systems, or shipping it with your
products. In fact, you can even sell Python, if you're so
inclined. But don't get the wrong idea: "free" doesn't mean
"unsupported". On the contrary, the Python online
community responds to user queries with a speed that
most commercial software vendors would do well to
notice.
➢ It's Portable
Python is written in portable ANSI C, and compiles and
runs on virtually every major platform in use today. For
example, it runs on UNIX systems, Linux, MS-DOS, MS-
pg. 50
Windows (95, 98, NT), Macintosh, Amiga, Be-OS, OS/2,
VMS, QNX, and more. Further, Python programs are
automatically compiled to portable bytecode, which runs
the same on any platform with a compatible version of
Python installed (more on this in the section "It's easy to
use"). What that means is that Python programs that use
the core language run the same on UNIX, MS-Windows,
and any other system with a Python interpreter.
➢ It's Powerful
From a features perspective, Python is something of a
hybrid. Its tool set places it between traditional scripting
languages (such as Tcl, Scheme, and Perl), and systems
languages (such as C, C++, and Java). Python provides all
the simplicity and ease of use of a scripting language,
along with more advanced programming tools typically
found in systems development languages.
➢ Automatic memory management
Python automatically allocates and reclaims ("garbage
collects") objects when no longer used, and most grow and
shrink on demand; Python, not you, keeps track of
lowlevel memory details.
➢ Programming-in-the-large support
Finally, for building larger systems, Python includes
tools such as modules, classes, and exceptions; they allow
you to organize systems into components, do OOP, and
handle events gracefully.
pg. 51
➢ It's Mixable
Python programs can be easily "glued" to components
written in other languages. In technical terms, by
employing the Python/C integration APIs, Python
programs can be both extended by (called to) components
written in C or C++, and embedded in (called by) C or C++
programs. That means you can add functionality to the
Python system as needed and use Python programs within
other environments or systems.
➢ It's Easy to Use
For many, Python's combination of rapid turnaround
and language simplicity make programming more fun than
work. To run a Python program, you simply type it and
run it. There are no intermediate compile and link steps
(as when using languages such as C or C++). As with other
interpreted languages, Python executes programs
immediately, which makes for both an interactive
programming experience and rapid turnaround after
program changes. Strictly speaking, Python programs are
compiled (translated) to an intermediate form called
bytecode, which is then run by the interpreter.
➢ It's Easy to Learn
This brings us to the topic of this book: compared to
other programming languages, the core Python language is
amazingly easy to learn. In fact In fact, you can expect to
be coding significant Python programs in a matter of days
(and perhaps in just hours, if you're already an
experienced programmer).
pg. 52
➢ Internet Scripting
Python comes with standard Internet utility modules
that allow Python programs to communicate over sockets,
extract form information sent to a server-side CGI script,
parse HTML, transfer files by FTP, process XML files, and
much more. There are also a number of peripheral tools
for doing Internet programming in Python. For instance,
the HTMLGen and pythondoc systems generate HTML files
from Python class-based descriptions, and the JPython
system mentioned above provides for seamless
Python/Java integration.
➢ Database Programming
Python's standard pickle module provides a simple
object-persistence system: it allows programs to easily
save and restore entire Python objects to files. For more
traditional database demands, there are Python interfaces
to Sybase, Oracle, Informix, ODBC, and more. There is even
a portable SQL database API for Python that runs the same
on a variety of underlying database systems, and a system
named gadfly that implements an SQL database for Python
programs.
➢ Image Processing, AI, Distributed Objects, Etc.
Python is commonly applied in more domains than can
be mentioned here. But in general, many are just instances
of Python's component integration role in action. By
adding Python as a frontend to libraries of components
written in a compiled language such as C, Python becomes
useful for scripting in a variety of domains. For instance,
pg. 53
image processing for Python is implemented as a set of
library components implemented in a compiled language
such as C, along with a Python frontend layer on top used
to configure and launch the compiled components.
pg. 54
source code. Roughly, Python translates each of your
source statements into a group of byte code instructions
by decomposing them into individual steps. This byte code
translation is performed to speed execution —byte code
can be run much more quickly than the original source
code statements in your text file.
pg. 55
careful surgery to adapt the change. This means you have
too many assumptions about Table in Carpenter’s code or
the reverse.
• Heavy usage of global state or context: instead of
explicitly passing (height, width, type, wood) to each
other, Table and Carpenter rely on global variables that
can be modified and are modified on the fly by different
agents. You need to scrutinize all access to these global
variables to understand why a rectangular table became a
square, and discover that remote template code is also
modifying this context, messing with table dimensions.
• Spaghetti code: multiple pages of nested if clauses and
for loops with a lot of copy-pasted procedural code and no
proper segmentation are known as spaghetti code.
Python’s meaningful indentation (one of its most
controversial features) make it very hard to maintain this
kind of code. So the good news is that you might not see
too much of it.
• Ravioli code is more likely in Python: it consists of
hundreds of similar little pieces of logic, often classes or
objects, without proper structure. If you never can
remember if you have to use FurnitureTable, AssetTable
or Table, or even TableNew for your task at hand, you
might be swimming in ravioli code
pg. 56
Testing your code is very important.
Getting used to writing testing code and running this code
in parallel is now considered a good habit. Used wisely,
this method helps you define more
precisely your code’s intent and have a more decoupled
architecture.
Some general rules of testing:
• A testing unit should focus on one tiny bit of functionality
and prove it correct.
• Each test unit must be fully independent. Each test must
be able to run alone, and also within the test suite,
regardless of the order that they are called. The
implication of this rule is that each test must be loaded
with a fresh dataset and may have to do some cleanup
afterwards. This is usually handled by setUp() and
tearDown() methods.
• Try hard to make tests that run fast. If one single test
needs more than a few milliseconds to run, development
will be slowed down or the tests will not be run as often as
is desirable. In some cases, tests can’t be fast because they
need a complex data structure to work on, and this data
structure must be loaded every time the test runs. Keep
these heavier tests in a separate test suite that is run by
some scheduled task, and run all other tests as often as
needed.
• Learn your tools and learn how to run a single test or a
test case. Then, when developing a function inside a
pg. 57
module, run this function’s tests frequently, ideally
automatically when you save the code.
• Always run the full test suite before a coding session,
and run it again after. This will give you more confidence
that you did not break anything in the rest of the code.
• It is a good idea to implement a hook that runs all tests
before pushing code to a shared repository.
• If you are in the middle of a development session and
have to interrupt your work, it is a good idea to write a
broken unit test about what you want to develop next.
When coming back to work, you will have a pointer to
where you were and get back on track faster.
• The first step when you are debugging your code is to
write a new test pinpointing the bug. While it is not always
possible to do, those bug catching tests are among the
most valuable pieces of code in your project.
• Use long and descriptive names for testing functions.
The style guide here is slightly different than that of
running code, where short names are often preferred. The
reason is testing functions are never called explicitly.
square() or even sqr() is ok in running code, but in testing
code you would have names such as
test_square_of_number_2(),
test_square_negative_number(). These function names are
displayed when a test fails, and should be as descriptive as
possible.
• When something goes wrong or has to be changed, and
if your code has a good set of tests, you or other
pg. 58
maintainers will rely largely on the testing suite to fix the
problem or modify a given behavior. Therefore the testing
code will be read as much as or even more than the
running code. A unit test whose purpose is unclear is not
very helpful in this case.
• Another use of the testing code is as an introduction to
new developers. When someone will have to work on the
code base, running and reading the related testing code is
often the best thing that they can do to start. They will or
should discover the hot spots, where most difficulties
arise, and the corner cases. If they have to add some
functionality, the first step should be to add a test to
ensure that the new functionality is not already a working
path that has not been plugged into the interface.
pg. 59
WSGIcompliant web server. WSGI is documented in PEP
3333.
Frameworks
Broadly speaking, a web framework consists of a set of
libraries and a main handler within which you can build
custom code to implement a web application (i.e. an
interactive web site). Most web frameworks include
patterns and utilities to accomplish at least the following:
URL Routing Matches an incoming HTTP request to a
particular piece of Python code to be invoked
Request and Response Objects Encapsulates the
information received from or sent to a user’s browser
Template Engine Allows for separating Python code
implementing an application’s logic from the HTML (or
other) output that it produces
Development Web Server Runs an HTTP server on
development machines to enable rapid development;
often automatically reloads server-side code when files
are updated
Django
Django is a “batteries included” web application
framework, and is an excellent choice for creating content-
oriented websites. By providing many utilities and
patterns out of the box, Django aims to make it possible to
build complex, database-backed web applications quickly,
while encouraging best practices in code written using it.
pg. 60
Django has a large and active community, and many pre-
built re-usable modules that can be incorporated into a
new project as-is, or customized to fit your needs.
There are annual Django conferences in the United States,
Europe, and Australia.
The majority of new Python web applications today are
built with Django.
Flask
Flask is a “microframework” for Python, and is an
excellent choice for building smaller applications, APIs,
and web services.
Building an app with Flask is a lot like writing standard
Python modules, except some functions have routes
attached to them. It’s really beautiful.
Rather than aiming to provide everything you could
possibly need, Flask implements the most commonly-used
core components of a web application framework, like
URL routing, request and response objects, and templates.
If you use Flask, it is up to you to choose other
components for your application, if any. For example,
database access or form generation and validation are not
built-in functions of Flask.
This is great, because many web applications don’t need
those features. For those that do, there are many
Extensions available that may suit your needs. Or, you can
easily use any library you want yourself!
pg. 61
Flask is default choice for any Python web application that
isn’t a good fit for Django.
Falcon
Falcon is a good choice when your goal is to build RESTful
API microservices that are fast and scalable.
It is a reliable, high-performance Python web framework
for building large-scale app backends and microservices.
Falcon encourages the REST architectural style of mapping
URIs to resources, trying to do as little as possible while
remaining highly effective.
Falcon highlights four main focuses: speed, reliability,
flexibility, and debuggability. It implements HTTP through
“responders” such as on_get(), on_put(), etc. These
responders receive intuitive request and response objects.
Tornado
Tornado is an asynchronous web framework for Python
that has its own event loop. This allows it to natively
support WebSockets, for example. Well-written Tornado
applications are known to have excellent performance
characteristics.
I do not recommend using Tornado unless you think you
need it.
pg. 62
Why is python so popular?
According to the TIOBE index, which
measures the popularity of programming languages,
python is the third most popular programming language
in th world, behind only Java and C. There are many
reasons for the ubiquity of python, including:
▪ Its ease of use. For those who are new to
coding and programming, python can be
an excellent first step. It’s relatively easy
to learn, making it a great way to start
building your programming knowledge.
▪ Its simple syntax. Python is relatively
easy to read and understand, as its
syntax is more like English. Its straight
forward layout means that you can work
out what each line of code is doing.
▪ Its thriving community. As it’s an open-
source language, anyone can use python
to code. What’s more, there is a
community that supports and developers
the ecosystem, adding their own
contributions and libraries.
▪ Its versatility. As we’ll explore in more
detail, there are many uses for python.
Whether you’re interested in data
visualisation, artificial intelligence or
web development, you can find a use for
the language.
pg. 63
Why Learn python?
So, we know why python is so
popular at the moment, but why should you learn how to
use it? Aside from the ease of use and versatility
mentioned above, there are several good reasons to learn
Python:
o Python developers are in demand. Across
a wide range of fields, there is a demand for
those with python skills. If you’re looking to
start or change your career, it could be a
vital skill to help you.
o It could lead to a well-paid career. Data
suggest that the median annual salary for
those with python skills is around £65,000
in the UK.
o There will be many job opportunities.
Given that python can be used in many
emerging technologies, such as AI, machine
learning, and data analytics, it’s likely that
it’s a future-proof skill.
pg. 66
The simple and elegant design
of python and its syntax means that it has inspired the
creation of new programming languages. Languages such
as cobra Coffee Script, and go all use a similar syntax to
python.
This fact also means that python is a useful gateway
language. So, if you’re totally new to programming ,
understanding python can help you branch out into other
areas more easily.
8.Finance
Python is increasingly being utilised in the
world of finance, often in areas such as quantitative and
qualitative analysis. It can be a valuable tool in
determining asset price treads and predictions, as well as
in automating workflows across different data sources.
As mentioned already, python is an ideal tool for working
with big data sets, and there are many libraries available
to help with compiling and processing information. As
such, it’s one of the preferred languages in the finances
industry.
9.SEO
Another slightly surprising entry on our list of
python uses is in the field of search engine optimisation
(SEO), It’s an area that often benefits from automation
which is certainly possible through python. Whether it’s
pg. 67
implementing changes across multiple pages or
categorising keywords, python can help.
10.Design
When asking ‘what is python used for?’ You
probably weren’t expecting design to feature on the list.
However, python can be used to develop graphic design
applications. Surprisingly, the language is used across a
range of 2D imaging software, such as paint shop pro and
Gimp.
Python is even used in 3D animation software such as
Lightwave, Blender, and Cinema 4D,.
Final thought
That concludes our look at what python
programming can be used for. As you can see, there are
many applications for this popular language, with a wide
support network and a diverse range od libraries that can
help.
pg. 68
Is Python’s popularity a good thing?
Yes, very much so. While generally what is popular isn’t
always the best, in the case of programming languages the
popularity pays off.
pg. 69
The same is true for frameworks, which help get your
project off the ground and save you time and effort.
• Pyramid,
• Twisted,
• Falcon.
performance
Easy maintenance
Python is intuitive to read, because it resembles actual
English. This makes the language effortless to decipher
and maintain.
pg. 70
Additionally, Python has a clear syntax and doesn’t require
as many lines of code as Java or C to give you comparable
results.
Python Developer
Python Developers often work server side, either writing
logic or developing the platform. Typically, they are
responsible for deploying applications and working with
development and design teams to build websites or
applications that suit the user’s needs.
Software Engineer
Software Engineers, like Developers, are responsible for
writing, testing, and deploying code. As a Software
pg. 73
Engineer, you’ll need to integrate applications, debug
programs, and overall improve and maintain software.
Data Analyst
Data analysts collect, organize, and interpret data to create
actionable insights. To accomplish this, Data Analysts must
collect large amounts of data, sift through it, and assemble
key sets of data based on the organization’s desired
metrics or goals.
Data Scientist
Data Scientists have a more complex skill set than Data
Analysts, combining computer science, mathematics,
statistics, and modeling with a strong understanding of
their business and industry to unlock new opportunities
and strategies.
pg. 74
Data Scientists are not only responsible for analyzing data
but often also using machine learning, developing
statistical models, and designing data structures for an
organization.
pg. 75
Syntax Errors
Exceptions
pg. 76
Exceptions come in different types, and the type is printed
as part of the message: the types in the example are
ZeroDivisionError, NameError and TypeError. The string
printed as the exception type is the name of the built-in
name for the exception that occurred. This is true for all
built-in exceptions, but need not be true for user-defined
exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved
keywords).
Handling Exceptions
It is possible to write programs that handle selected
exceptions. Look at the following example, which asks the
user for input until a valid integer has been entered, but
allows the user to interrupt the program (using Control-C
or whatever the operating system supports); note that a
pg. 77
user generated interruption is signalled by raising the
Keyboard Interrupt exception.
Raising Exceptions
The raise statement allows the programmer to force a
specified exception to occur.
pg. 78
The first argument to raise names the exception to be
raised. The optional second argument specifies the
exception’s argument.
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
User-defined Exceptions
Programs may name their own exceptions by creating a
new exception class. Exceptions should typically be
derived from the Exception class, either directly or
indirectly.
Exception classes can be defined which do anything any
other class can do, but are usually kept simple, often only
offering a number of attributes that allow information
about the error to be extracted by handlers for the
exception. When creating a module which can raise
several distinct errors, a common practice is to create a
base class for exceptions defined by that module, and
subclass that to create specific exception classes for
different error conditions.
pg. 79
Syntax and semantics
The syntax of the python
programming language is the set of rules that defines how
a python program will be written and interpreted (by both
the runtime system and by humans readers). The python
languages has many similarities to perl, C, and Java.
However, there are some definite differences between the
languages.
pg. 80
➢ The class statement, which executes a block of code
and attaches its local namespace to a class. For use in
object-oriented programming.
➢ The def statement, which defines a functions or
method.
➢ The with statement, which encloses a code block
within a context manager (for example, acquiring a
lock before the block of code is run and releasing the
lock afterwards, or opening a file and then closing it),
allowing resource-acquisition-is-initialization
(RAAII)-like behavior and replaces a common
try/finally idiom.[81]
➢ The break statement, exits from a loop.
➢ The continue statement, skips the iteration and
continues with the next item.
➢ The del statement, removes a variable, which means
the reference from the name to the value is deleted
and trying to use that variable will cause an error. A
deleted variable can be reassigned.
➢ The pass statement, which serves as a NOP. It is
syntactically needed to create an empty code block.
➢ The assert statement, used during debugging to check
for conditions that should apply.
➢ The yield statement, which returns a value from a
generator function and yield is also an operator. This
form is used to implement coroutines.
➢ The return statement, used to return a value from a
function.
pg. 81
➢ The import statement, which is used to import
modules whose functions or variables can be used in
the current program.
The assignment statement(=) operates by binding a name
as a reference to a separate, dynamically-allocated object.
Variable may subsequently be rebound at any time to any
object. In python, a variable name is generic reference
holder and does not have a fixed data type associated with
it.
However, at a given time, a variable will refer to some
object, which will have a type. This is referred to as
dynamic typing and is contrasted with statically-typed
programming languages, where each variable may only
contain values of a contain type.
Python does not support tail call optimization or first-class
continuations, and, according to Guido Van Rossum, it
never will.[82][83] However, better support for coroutine-
like functionally is provided, by extending python’s
generators.[84] Before 2.5, generators were lazy iterators;
information was passed unidirectionally out of the
generator. From python 2.5, it is possible to pass
information back into a generator function, and from
python 3.3, the information can be passed through
multiple stack levels.[85]
Expression
Some python expressions are similar to those
found in languages such as C and Java, while some are not:
pg. 82
❖ Addition, subtraction, and multiplication are the
same, but the behavior of division differs. There are
two types of divisions in python. They are floor
division (or integer division) //and floating-
point/division.[86] Python also uses the ** operator for
exponentiation
.
❖ From python 3.5, the new @ infix operator aws
introduced. It is intended to be used by libraries such
as Numpy for matrix multiplication.[87][88]
❖ From python 3.8, the syntax :=, called the ‘walrus
operator’ was introduced. It assigns value to variable
as part of a larger expression.[89]
❖ In python, ==compares by value, versus java, which
compares numeric by value[90] and object by
reference.[91] (value comparisons in java on objects
can be performed with the equals() method).
Python’s is operator may be used to compare object
identities (comparison by reference). In python,
comparisons may be chained, for example a <=b <= c.
❖ Python uses the words and, or, not for its Boolean
operators rather than the symbolic &&, ||, ! used in
Java, C.
❖ Python has a type of expression termed a list
comprehension as well as a more general expression
termed a generator expression.[64]
pg. 83
❖ Anonymous functions are implemented using lambda
expressions; however, these are limited in that the
body can only one expression.
❖ Conditional expressions in python are written as x if c
else y[92] (different in order of operands from the c?
x:y operator common to many other languages).
❖ Python makes a distinction between lists and tuple.
Lists are written as [ 1, 2, 3], are mutable, and cannot
be used as the keys of dictionaries (dictionary keys
must be immutable in python). Tuples are written as
(1, 2, 3), are immutable and thus can be used as the
keys of dictionaries, provide all elements of the tuple
are immutable. The + operator can be used to
concatenate two tuples, which does not directly
modify their contents, but rather produces a new
tuple containing the elements of both provided tuples.
Thus, given the variable t initially equal to (1, 2, 3),
executing t = t + (4 ,5) first evaluates t + (4, 5), which
yields (1, 2, 3, 4, 5), which is then assigned back to t,
thereby effectively “modifying the contents” of t,
while conforming to the immutable nature of tuple
objects. Parentheses are optional for tuples in
unambiguous context.[93]
❖ Python features sequence unpacking where in
multiple expressions, each evaluating to anything that
can ne assigned to (a variable, a writable property,
etc), are associated in an identical manner to that
forming tuple literals and, as whole, are put on the
pg. 84
left-hand side of the equal sign in an assignment
statement. The statement expects an iterable object
on the right hand side of the equal sign that produces
the same number of values as the provided writable
expressions when iterated through and will iterate
through it, assigning each of the produces values to
the corresponding expression on the left.[94
❖ Python has a “string format” operator %. This
functions analogously to printf format strings in C,
e.g. “spam=%s eggs=%d”%(“blah”, 2) evaluates to
“spam=blah eggs=2”. In python 3 and 2.6+, this was
supplemented by the format() method of the str class,
e.g. “spam={0} eggs={1} “.format(“blah”, 2). Python
3.6 added “f-string”: blah=”blah”;eggs=2;
f‘spam={blah}eggs={eggs}’.[95]
❖ Strings in python can be concatenated, by “adding”
them(same operator as for adding integer and floats).
E.g.”spam”+”eggs” returns “spameggs”.even if your
strings contain numbers, they are still added as string
rather than integers. e.g. “2” + “2” returns “22”.
❖ Python has various kinds of strings literals:
Strings delimited by single or
double quote marks. Unlike in unix shells, perl and
perl-influenced language, single quote marks and
double quote marks function identically. Both kinds
of string use the backslash (\) as an escape character.
String interpolation became available in python 3.6 as
“formatted string literals”.[95]
pg. 85
❖ Triple quote strings, which begin and end with a
series of three single or double quote marks. They
may span multiple lines and function like here
documents in shells, perl and ruby.
Raw string varieties, denoted by prefixing the string
literals with an r. Escape sequences are not
interpreted; hence raw strings are useful where
literal backslash are common, such as regular
expressions and windows-style paths. Compare “@-
quoting” in C#.
❖ Python has array index and array slicing expression
on list, denoted as a[key], a[start:stop] or
a[start:stop:step]. Indexes are zero-based, and
❖ negative indexes are relative to the end. Slices take
elements from the start index up to, but not including,
the stop index. The third slice parameter, called step
or strode, allows elements to be skipped and
reversed. Slice indexes may be omitted, for example
a[:] returns a copy of the entire list. Each elements of
a slice is a shallow copy.
In python, a distinction between expressions and
statements is rigidly enforced, in contrast to languages
such as common lisp, scheme. Or ruby. This leads to
duplicating some functionality. For example:
• List comprehensions vs,]. For-loops
• Conditional expressions vs. if blocks
pg. 86
• The eval() vs. exec() b uilt-in functions (in python
2, exec is a statement); the former is for
expressions, the latter is for statement.
Statement cannot be a part of an expression, so list and
other comprehensions or lambda expressions, all begin
expressions, cannot contain statement. A particular case
of this is that an assignment statement such as a=1
cannot form part of the conditional expression of a
conditional statement. This has the advantage of
avoiding a classic C error of mistaking an assignment
operator = for an equality operator == in conditions: if
(c=1) {….} is syntactically valid (but probably
unintended) C code but if c=1:…. Causes a syntax error
in python.
Methods:
Methods on objects are functions attached to the
object’s class; the syntax is, for normal methods and
functions, syntactic sugar for python methods have an
explicit self parameter to access instance data, in contrast
to the implicit self (or this) un some other object-oriented
programming languages (e.g., C++,Java, Objective-C, or
Ruby).[96] Apart from this, python also provides methods,
often called dunder methods (due to their names
beginning and ending with double-underscores), to allow
user-defined classes to modify how they are handled by
native operations such as length, comparison, in
arithmetic operations, type conversion, and many more.[97]
pg. 87
Summary:
Python is a simple, versatile ans a complete
programming language. It is a great choice for beginners
up to professionals . Although it has some
disadvantages, we can observe that the advantages
exceed the disadvantages. Even Google has made
python one of its primary programming languages.
Python Features
pg. 88
Student Marksheet Program In Python
Programming Language
pg. 89
CODING
pg. 90
INPUT
pg. 91
OUTPUT
pg. 92
Explanation of the program
pg. 93