You are on page 1of 93

A PROJECT REPORT

ON

“STUDENT MARK SHEET”


SUMITTED IN PARTIAL FULFILLMENT
FOR THE DEGREE
HDCA
BY
J.KAVIYA
UNDER THE GUIDANCE OF
Miss.Vigneswari A,B.TECH.,

pg. 1
BONAFIDE CERTIFICATE

This is to certify that the project work that


is begin submitted by J.Kaviya ”Student
report card” is record of bonafide work
done under my supervision. The contents of
this project work, in full or in parts, have
neither been taken from any other source
nor have been submitted for any other
course.

Signature Signature

Mr.V.J.GNANESWARAN.,B.E., Miss.A.VIGNESWARI.,B.TECH.,

CENTER DIRECTOR PROJECT GUIDE

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

• Python is popular programming language. It was


created by Guido Van Rossum, and released in 1991.

• Python is an open-sources programming language


that is used in web programming, data science,
artificial intelligences, and many scientific application.
Learning python allows the programmer to focus on
solving problems, rather than focusing on syntax.

• Python is an interpreted, object-oriented high-level


programming language with dynamic semantics.
Python’s simple, easy to learn syntax emphasizes
readability and therefore reduces the cost of program
maintenances. Python supports modules and
packages, which encourages program modularity and
code recuse.

• Python is commonly used for developing websites


and software, task automation. data analysis, and data
visualization. Since it’s relatively easy to learn, python
has been adopted by many non-programmers such as
accountants and scientists, for a variety of everyday
tasks, like organizing finances.

pg. 5
Why the Name Python?

There is a fact behind choosing the name Python. Guido van


Rossum was reading the script of a popular BBC comedy
series "Monty Python's Flying Circus". It was late on-air
1970s.
Van Rossum wanted to select a name which unique, sort,
and little-bit mysterious. So he decided to select naming
Python after the "Monty Python's Flying Circus" for their
newly created programming language.
The comedy series was creative and well random. It talks
about everything. Thus it is slow and unpredictable, which
made it very interesting.
Python is also versatile and widely used in every technical
field, such as Machine Learning, Artificial Intelligence, Web
Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.

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!

Where From Here

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.

In the next chapter, the mechanics of using the interpreter


are explained. This is rather mundane information, but
essential for trying out the examples shown later.

The rest of the tutorial introduces various features of the


Python language and system through examples, beginning
with simple expressions, statements and data types,
through functions and modules, and finally touching upon
advanced concepts like exceptions and user-defined
classes.
Using the Python Interpreter

Invoking the Interpreter

The Python interpreter is usually installed as


‘/usr/bin/python’ or ‘/usr/local/bin/python’ on those
machines where it is available; putting the appropriate

pg. 9
directory in your Unix shell’s search path makes it possible
to start it by typing the command

Python to the shell. Since the choice of the directory where


the interpreter lives is an installation option, other places
are possible; check with your local Python guru or system
administrator.
(E.g., ‘/usr/local/python’ is a popular alternative location.)

Typing an end-of-file character (Control-D on Unix,


Control-Z on DOS or Windows) at the primary prompt
causes the interpreter to exit with a zero exit status. If that
doesn’t work, you can exit the interpreter by typing the
following commands: ‘import sys; sys.exit()’.

The interpreter’s line-editing features usually aren’t very


sophisticated. On Unix, whoever installed the interpreter
may have enabled support for the GNU readline library,
which adds more elaborate interactive editing and history
features. Perhaps the quickest check to see whether
commandline editing is supported is typing Control-P to
the first Python prompt you get. If it beeps, you have
command-line editing; see Appendix A for an introduction
to the keys. If nothing appears to happen, or if ^P is
echoed, command-line editing isn’t available; you’ll only

pg. 10
be able to use backspace to remove characters from the
current line.

The interpreter operates somewhat like the Unix shell:


when called with standard input connected to a tty device,
it reads and executes commands interactively; when called
with a file name argument or with a file as standard input,
it reads and executes a script from that file.

A third way of starting the interpreter is ‘python -c


command [arg] ...’, which executes the statement(s) in
command, analogous to the shell’s -c option. Since Python
statements often contain spaces or other characters that
are special to the shell, it is best to quote command in its
entirety with double quotes.
Argument Passing
When known to the interpreter, the script name and
additional arguments thereafter are passed to the script in
the variable sys.argv, which is a list of strings. Its length is
at least one; when no script and no arguments are given,
sys.argv[0] is an empty string. When the script name is
given as ’-’ (meaning standard input), sys.argv[0] is set to
’-’. When -c command is used, sys.argv[0] is set to ’-c’.
Options found after -c command are not consumed by the
Python interpreter’s option processing but left in sys.argv
for the command to handle.

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

When an error occurs, the interpreter prints an error


message and a stack trace. In interactive mode, it then
returns to the primary prompt; when input came from a
file, it exits with a nonzero exit status after printing the
stack trace. (Exceptions handled by an except clause in a
try statement are not errors in this context.) Some errors
are unconditionally fatal and cause an exit with a nonzero
exit status; this applies to internal inconsistencies and
some cases of running out of memory. All error messages
are written to the standard error stream; normal output
from the executed commands is written to standard
output.

Typing the interrupt character (usually Control-C or DEL)


to the primary or secondary prompt cancels the input and
returns to the primary prompt. Typing an interrupt while
a command is executing raises the KeyboardInterrupt
exception, which may be handled by a try statement.

Executable Python Scripts


On BSD’ish Unix systems, Python scripts can be made
directly executable, like shell scripts, by putting the
line
pg. 13
#! /usr/bin/env python
(assuming that the interpreter is on the user’s PATH) at
the beginning of the script and giving the file an executable
mode. The ‘#!’ must be the first two characters of the file.
Note that the hash, or pound, character, ‘#’, is used to start
a comment in Python.

The Interactive Startup File

When you use Python interactively, it is frequently handy


to have some standard commands executed every time the
interpreter is started. You can do this by setting an
environment variable named PYTHONSTARTUP to the
name of a file containing your start-up commands. This is
similar to the ‘.profile’ feature of the Unix shells.

This file is only read in interactive sessions, not when


Python reads commands from a script, and not when
‘/dev/tty’ is given as the explicit 10 source of commands
(which otherwise behaves like an interactive session). It is
executed in the same namespace where interactive
commands are executed, so that objects that it defines or
imports can be used without qualification in the
interactive session. You can also change the prompts
sys.ps1 and sys.ps2 in this file.

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)

An Informal Introduction to Python

In the following examples, input and output are


distinguished by the presence or absence of prompts (‘>>>
’ and ‘... ’): to repeat the example, you must type everything
after the prompt, when the prompt appears; lines that do
not begin with a prompt are output from the interpreter.
Note that a secondary prompt on a line by itself in an
example means you must type a blank line; this is used to
end a multi-line command.

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."

More Control Flow

Tools Besides the while statement just introduced, Python


knows the usual control flow statements found in other
languages, with some twists.

if Statements

Perhaps the most well-known statement type is the


statement.
For example:
>>> x= int(raw_input("Please enter an integer: "))
>>> if x< 0:
... x= 0

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

The for statement in Python differs a bit from what you


may be used to in C or Pascal. Rather than always iterating
over an arithmetic progression of numbers (like in Pascal),
or giving the user the ability to define both the iteration
step and halting condition (as C), Python’s for statement
iterates over the items of any sequence (a list or a string),
in the order that they appear in the sequence. For example
(no pun intended):
>>> # Measure some strings:
... a = [’egg’, ’chips’, ’spam’]
>>> for xin a:
pg. 17
... print x, len(x)
...
egg 3
chips 5
spam 4

It is not safe to modify the sequence being iterated over in


the loop (this can only happen for mutable sequence types,
such as lists). If you need to modify the list you are
iterating over (for example, to duplicate selected items)
you must iterate over a copy. The slice notation makes this
particularly convenient:
>>> for xin a[:]: # make a slice copy of the entire list
... if len(x) == 4: a.insert(0, x)
... >>> a
[’spam’, ’egg’, ’chips’, ’spam’]

The range() Function

If you do need to iterate over a sequence of numbers, the


built-in function range() comes in handy. It generates lists
containing arithmetic progressions:

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

“Compiled” Python files


As an important speed-up of the start-up time for short
programs that use a lot of standard modules, if a file called
‘spam.pyc’ exists in the directory where ‘spam.py’ is found,
this is assumed to contain an already- “byte-compiled”
version of the module spam. The modification time of the
version of ‘spam.py’ used to create ‘spam.pyc’ is recorded
in ‘spam.pyc’, and the ‘.pyc’ file is ignored if these don’t
match. 52 Normally, you don’t need to do anything to
create the ‘spam.pyc’ file. Whenever ‘spam.py’ is
successfully compiled, an attempt is made to write the
compiled version to ‘spam.pyc’. It is not an error if this
attempt fails; if for any reason the file is not written
completely, the resulting ‘spam.pyc’ file will be recognized
as invalid and thus ignored later. The contents of the

pg. 26
‘spam.pyc’ file are platform independent, so a Python
module directory can be shared by machines of different
architectures.

Some tips for experts:

• When the Python interpreter is invoked with the -O


flag, optimized code is generated and stored in ‘.pyo’
files. The optimizer currently doesn’t help much; it
only removes assert statements and SET LINENO
instructions. When -O is used, all bytecode is
optimized; .pyc files are ignored and .py files are
compiled to optimized bytecode.
• Passing two -O flags to the Python interpreter (-OO)
will cause the bytecode compiler to perform
optimizations that could in some rare cases result in
malfunctioning programs. Currently only doc strings
are removed from the bytecode, resulting in more
compact ‘.pyo’ files. Since some programs may rely on
having these available, you should only use this
option if you know what you’re doing.

• A program doesn’t run any faster when it is read


from a ‘.pyc’ or ‘.pyo’ file than when it is read from a
‘.py’ file; the only thing that’s faster about ‘.pyc’ or
‘.pyo’ files is the speed with which they are loaded.

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.

• The module compileall can create ‘.pyc’ files (or


‘.pyo’ files when -O is used) for all modules in a
directory

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.

Importing * From a Package


Now what happens when the user writes from
Sound.Effects import *? Ideally, one would hope that this
somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them
all. Unfortunately, this operation does not work very well
on Mac and Windows platforms, where the filesystem does
not always have accurate information about the case of a
filename! On these platforms, there is no guaranteed way
to know whether a file ‘ECHO.PY’ should be imported as a
module echo, Echo or ECHO. (For example, Windows 95
has the annoying practice of showing all file names with a
capitalized first letter.) The DOS 8+3 filename restriction
adds another interesting problem for long module names.
The only solution is for the package author to provide an
explicit index of the package. The import statement uses
the following convention: if a package’s ‘ init .py’ code
defines a list named all , it is taken to be the list of module
names that should be imported when from package import

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

Python was conceived in the late 1980[39] by Guido Van


Rossum at Centrum Wiskunde & Informatica (CWI) in the
Netherlands as a successors to the ABC programming
language, which was inspired by SETL,[40] capable of
exception handling and interfacing with the Amoeba
operating system.[10] Its implementation began in
December 1989.[41] Van Rossum shouldered sole
responsibility for the project, as the lead developer ,until
12 July 2018,whwn he announced his “permanent
vacation” from his responsibilities as python’s “benevolent
dictator for life”, a title the python community bestowed
upon him to reflect his long-term commitment as the
project’s chief decision-maker.[42] In January 2019,active
python core developers elected a five-member “Steering
Council” to lead the project.[43][44]
• Python 2.0 was released on 16 October 2000, with
many major new features, including a cycle-detecting
garbage collector (in addition to reference counting)
for memory management and support for Unicode.[45]
• Python 3.0 was released on 3 December 2008. It was
a major revision of the language that is not
completely backward-compatible.[46] Many of its
major features were backported to python 2.6.x[47]
and 2.7.x version series. Releases of python 3 include
the 2 to 3 utility, which automates the translation of
python 2 code to python 3.[48]
pg. 34
• Python 2.7’s end-of-life date was initially set at 2015
then postponed to 2020 out of concern that a large
body of existing code could not easily be forward-
ported to python 3.[49][50] No more security patches or
other improvements will be released for it.[51][52] with
python 2’s end-of-life, only python 3.6.x[53] and later
are supported
• Python 3.9.2 and 3.8.8 were expedited[54] as all
versions of python (including 2.7[55]) had security
issues, leading to possible remote code execution[56]
and web cache poisoning.[57]

Python Advantages and Disadvantages


Advantages of python:

1.Easy to read, learn and write:


Python is a high-level
programming language that has English- like syntax. This
makes it easier to read and understand the code. Python is
really easy to pickup and learn, that is why a lot of people
recommend python to beginners. You need less lines of
code to perform the same task as compared to other major
languages like C/C++ and Java
2.Improved productivity:
Python is a very productive
language. Due to the simplicity of python, developers can
focus on solving the problem. They don’t need to spend
too much time in understanding the syntax or behavior of
pg. 35
the programming languages. You write less code and get
more things done.
3.Interpreted Language:
Python is an interpreted language
which means that python directly executes the code line
by line. In case of any error, it stops further execution and
reports back the error which has occurred. Python shows
only one even if the program has multiple errors. This
makes debugging easier.
4.Dynamically Typed:
Python doesn’t know the type of
variable until we run the code. It automatically assings the
data type during execution. The programmer doesn’t need
to worry about declaring variables and their data types.
5.Free and Open-Sources:
Python comes under the OSI
approved open-sources license. This makes it free to use
and distribute. You can download the source code, modify
it and even distribute your version of python. This is
useful for organizations that want to modify some specific
behavior and use their version for development.
6.Vast Libraries support:
The standard library of python id
huge, you can find almost all the functions needed for your
task, So, you don’t have to depend on external libraries.

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

Before introducing classes, I first have to tell you


something about Python’s scope rules. Class definitions
play some neat tricks with namespaces, and you need to
know how scopes and namespaces work to fully
understand what’s going on. Incidentally, knowledge
about this subject is useful for any advanced Python
programmer.

Let’s begin with some definitions.


A namespace is a mapping from names to objects. Most
namespaces are currently implemented as Python
dictionaries, but that’s normally not noticeable in any way
(except for performance), and it may change in the future.
Examples of namespaces are: the set of built-in names
(functions such as abs(), and built-in exception names);
the global names in a module; and the local names in a
function invocation. In a sense the set of attributes of an
object also form a namespace. The important thing to
know about namespaces is that there is absolutely no
relation between names in different namespaces; for
instance, two different modules may both define a
function “maximize” without confusion — users of the
modules must prefix it with the module name.

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

Attributes may be read-only or writable. In the latter case,


assignment to attributes is possible. Module attributes are
writable: you can write assignments such as
‘modname.the answer = 42’. Writable attributes may also
be deleted with the del statement. For example, ‘del
modname.the answer’ will remove the attribute the
answer from the object named by modname.

Name spaces are created at different moments and have


different lifetimes. The namespace containing the built-in
names is created when the Python interpreter starts up,
and is never deleted. The global namespace for a module is
created when the module definition is read in; normally,
module namespaces also last until the interpreter quits.
The statements executed by the top-level invocation of the
interpreter, either read from a script file or interactively,
are considered part of a module called main , so they have

pg. 41
their own global namespace. (The built-in names actually
also live in a module; this is called builtin .)

The local namespace for a function is created when the


function is called, and deleted when the function returns
or raises an exception that is not handled within the
function. (Actually, forgetting would be a better way to
describe what actually happens.) Of course, recursive
invocations each have their own local namespace.

A scope is a textual region of a Python program where a


namespace is directly accessible. “Directly accessible” here
means that an unqualified reference to a name attempts to
find the name in the namespace.

Although scopes are determined statically, they are used


dynamically. At any time during execution, there are at
least three nested scopes whose namespaces are directly
accessible: the innermost scope, which is searched first,
contains the local names; the namespaces of any enclosing
functions, which are searched starting with the nearest
enclosing scope; the middle scope, searched next, contains
the current module’s global names; and the outermost
scope (searched last) is the namespace containing built-in
names.

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.

Usually, the local scope references the local names of the


(textually) current function. Outside of functions, the local
scope references the same namespace as the global scope:
the module’s namespace. Class definitions place yet
another namespace in the local scope.

It is important to realize that scopes are determined


textually: the global scope of a function defined in a
module is that module’s namespace, no matter from where
or by what alias the function is called. On the other hand,
the actual search for names is done dynamically, at run
time — however, the language definition is evolving
towards static name resolution, at “compile” time, so don’t
rely on dynamic name resolution! (In fact, local variables
are already determined statically.)
pg. 43
A special quirk of Python is that assignments always go
into the innermost scope. Assignments do not copy data —
they just bind names to objects. The same is true for
deletions: the statement ‘del x’ removes the binding of x all
operations that introduce new names use the local scope:
in particular, import statements and function definitions
bind the module or function name in the local scope. (The
global statement can be used to indicate that particular
variables live in the global scope.)

Random Remarks

Data attributes override method attributes with the same


name; to avoid accidental name conflicts, which may cause
hard-to-find bugs in large programs, it is wise to use some
kind of convention that minimizes the chance of conflicts.
Possible conventions include capitalizing method names,
prefixing data attribute names with a small unique string
(perhaps just an underscore), or using verbs for methods
and nouns for data attributes.

Data attributes may be referenced by methods as well as


by ordinary users (“clients”) of an object. In other words,
classes are not usable to implement pure abstract data
types. In fact, nothing in Python makes it possible to
enforce data hiding — it is all based upon convention. (On
the other hand, the Python implementation, written in C,
can completely hide implementation details and control

pg. 44
access to an object if necessary; this can be used by
extensions to Python written in C.)

Clients should use data attributes with care — clients may


mess up invariants maintained by the methods by
stamping on their data attributes. Note that clients may
add data attributes of their own to an instance object
without affecting the validity of the methods, as long as
name conflicts are avoided — again, a naming convention
can save a lot of headaches here.

There is no shorthand for referencing data attributes (or


other methods!) from within methods. I find that this
actually increases the readability of methods: there is no
chance of confusing local variables and instance variables
when glancing through a method.

Conventionally, the first argument of methods is often


called self. This is nothing more than a convention: the
name self has absolutely no special 83 meaning to Python.
(Note, however, that by not following the convention your
code may be less readable by other Python programmers,
and it is also conceivable that a class browser program be
written which relies upon such a convention.)

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.

Methods may reference global names in the same way as


ordinary functions. The global scope associated with a
method is the module containing the class definition.(The
class itself is never used as a global scope!) While one
rarely encounters a good reason for using global data in a
method, there are many legitimate uses of the global
scope: for one thing, functions and modules imported into
the global scope can be used by methods, as well as
functions and classes defined in it. Usually, the class
containing the method is itself defined in this global scope,
and in the next section we’ll find some good reasons why a
method would want to reference its own class!

pg. 46
Python Features:

Python's features include:


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

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.

Need of Python Programming


➢ Software quality
Python code is designed to be readable, and hence
reusable and maintainable— much more so than
traditional scripting languages. The uniformity of Python
code makes it easy to understand, even if you did not write
it. In addition, Python has deep support for more advanced
software reuse mechanisms, such as object-oriented (OO)
and function programming.
➢ Developer productivity
Python boosts developer productivity many times
beyond compiled or statically typed languages such as C,
C++, and Java. Python code is typically one-third to less to
debug, and less to maintain after the fact. Python
programs also run immediately, without the lengthy
compile and link steps required by some other tools,
further boosting programmer speed. Program portability
Most Python programs run unchanged on all major
computer platforms. Porting Python code between Linux
and Windows, for example, is usually just a matter of
copying a script‘s code between machines.

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.

Who Uses Python Today?


1. Google makes extensive use of Python in its web search
systems.
2. The popular YouTube video sharing service is largely
written in Python.
3. The Dropbox storage service codes both its server and
desktop client software primarily in Python.
4. The Raspberry Pi single-board computer promotes
Python as its educational language.
5. The widespread BitTorrent peer-to-peer file sharing
system began its life as a Python program.
6. Google‘s App Engine web development framework uses
Python as an application language. 7. Maya, a powerful
integrated 3D modeling and animation system, provides a
Python scripting API. 8. Intel, Cisco, Hewlett-Packard,
Seagate, Qualcomm, and IBM use Python for hardware
testing. 9. NASA, Los Alamos, Fermilab, JPL, and others use
Python for scientific programming tasks. Byte code
Compilation: Python first compiles your source code (the
statements in your file) into a format known as byte code.
Compilation is simply a translation step, and byte code is a
lowerlevel, platform independent representation of your

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.

Structure of Code is Key


Thanks to the way imports and modules are handled in
Python, it is relatively easy to structure a Python project.
Easy, here, means that you do not have many constraints
and that the module importing model is easy to grasp.
Therefore, you are left with the pure architectural task of
crafting the different parts of your project and their
interactions.
Easy structuring of a project means it is also easy to do it
poorly. Some signs of a poorly structured project include:
• Multiple and messy circular dependencies: if your classes
Table and Chair in furn.py need to import Carpenter from
workers.py to answer a question such as table.isdoneby(),
and if conversely the class Carpenter needs to import
Table and Chair to answer the question
carpenter.whatdo(), then you have a circular dependency.
In this case you will have to resort to fragile hacks such as
using import statements inside methods or functions.
• Hidden coupling: each and every change in Table’s
implementation breaks 20 tests in unrelated test cases
because it breaks Carpenter’s code, which requires very

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.

Web Applications & Frameworks


As a powerful scripting language adapted to both fast
prototyping and bigger projects, Python is widely used in
web application development.
Context
WSGI
The Web Server Gateway Interface (or “WSGI” for short) is
a standard interface between web servers and Python web
application frameworks. By standardizing behavior and
communication between web servers and Python web
frameworks, WSGI makes it possible to write portable
Python web code that can be deployed in any

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.

What is python used for?


Clearly, Python is a popular and in-
demand skill to learn. But what is python programming
used for? We’ve already briefly touched on some of the
areas it can be applied to, and we’ve expanded on these
and more python examples below. Python can be used for:
1. Al and machine learning
pg. 64
Because python is such a
stable, flexible, and simple programming language, it’s
perfect for various machine learning (ML) and artificial
intelligences(AI) projects. In fact, python is among the
favourite languages among data scientists, and there are
many python machine learning and AI libraries and
packages available.
2.Data analytics
Much like Al and machine learning, data
analytics is another rapidly developing field that utilises
python programming. At a time when we’re creating more
data than ever before, there is a need for those who can
collect, manipulate and organise the information.
Python for data science and analytics makes sense. The
language is easy-to-learn, flexible, and well-supported,
meaning it’s relatively quick and easy to use for analysing
data and carrying out repetitive tasks.
3.Data visualisation
Data visualisation is another popular
and developing area of interest. Again, it plays into many
of the strengths of python. As well as its flexibility and the
fact it’s open-source, python provides a variety of
graphing libraries with all kinds of features.
4.Programming applications
We can program all kind of
applications using python. The general-purpose language
pg. 65
can be used to read and create file directories, create GUIs
and APIs, and more. Whether it’s blockchain applications,
audio and video apps, or machine learning applications,
you can build them all with python.
5.Web development
Python is great choice foe web
development. This is largely due to the fact that there are
many python web development framework to choose
from, such as Django, pyramid, and flask. These
framework have been used to create sites and services
such as Spotify, Reddit and Mozilla.
Thanks to the extensive libraries and modules that come
with python framework, function such as database access,
content management, and data authorisation are all
possible and easily accessible. Given uts versatility, it’s
hardly surprising that python is so widely used in web
development.
6.Game development
Although far from an industry-
standard in game development, python does have its uses
in the industry. It’s possible to create simple games using
the programming language, which means it can be a
useful tool for quickly developing a prototype. Similarly,
certain functions (such as dialogue tree creation) are
possible in python.
7.Language development

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.

Thanks to Python’s popularity, you’re likely to find a


ready-made solution to any problem you may be
experiencing. The community of Python enthusiasts is
strong and they are working tirelessly on improving the
language every day.
Python also has a number of corporate sponsors, pushing
to popularize the language further still. Among them are
tech giants such as Google, which itself is using Python.

Numerous libraries and frameworks


A huge advantage of Python is the wide selection
of libraries and frameworks it offers. Your time-to-market
will improve if you leverage them, since you won’t be
coding features manually.

There’s a Python library for everything:


• data visualization,
• machine learning,
• data science,
• natural language processing,
• complex data analysis.

From NumPy to TensorFlow—you name it, Python has it.

pg. 69
The same is true for frameworks, which help get your
project off the ground and save you time and effort.

There’s a variety of frameworks to choose from,


depending on your needs, such as:
• Django,
• Flask,

• Pyramid,

• Twisted,

• Falcon.

performance

One of the biggest criticisms of Python is the runtime,


relatively slow when compared to other languages.
However, there’s a workaround to this specific challenge.

When performance takes priority, Python gives you the


ability to integrate other, higher-performing languages
into your code. Cython is a good example of such a
solution. It optimizes your speed without forcing you to
rewrite your entire code base from scratch.

Besides, the priciest resource isn’t CPU time; it’s your


developers’ time. Reducing your time-to-market should
therefore always take precedence over fast runtime
execution.

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.

What are the benefits of Python’s high


readability?
Python’s simplicity is particularly helpful in reading
code—yours or someone else’s. Because Python code has
fewer lines and mimics English, reviewing it takes a lot
less time. This is a major benefit.

Reducing the time you need to spend on code review is


invaluable, since the productivity of your developers
should be your top priority.
Reliable scalability
Scalability is unpredictable. You never know when your
user numbers surge and you find yourself prioritizing the
ability to scale over anything else.

That’s why Python is such an optimal choice, with its


reliability and scalability. Some of the biggest players on
the web, like YouTube, have bet on Python for that very
reason.
Takeaways
Why Python? Because:
• it’s popular, fast, readable, intuitive, simple, clear, and
scalable;
• it offers a ton of useful frameworks and libraries;
• it enjoys a vast and ever-growing community of
supporters and enthusiasts.
pg. 71
What type of jobs use python
• A professional who specializes in Python can hold a
number of job titles, including Python Developer,
Data Scientist, and Machine Learning Engineer. The
exact work you’ll be doing will depend on the
industry, company, and scope of the role, but
essentially you will be using code to create sites and
applications, or work with data and AI.
• Python is most commonly used in big data centers, as
well as a “binder” language between other languages.
Google, NASA, Industrial Light & Magic and id
Software all use Python because of its capabilities and
expandability. Python is frequently used by Game
Developers as the glue between C/C++ modules, or
you can use it with PyGame to make a full-blown
game. It’s also popular among Scientists and
Statisticians with SciPy and Pandas.
• Although there are many different jobs that require
Python programming skills, they have one thing in
common: they tend to pay very well. That’s probably
because employers are having a hard time finding
Python talent across a number of industries.
• According to the Developer Survey by StackOverflow,
Python was one of the most in-demand technologies
of 2018, 2019, and 2020. As of 2020, it is ranked as
the world’s fourth most popular programming
language among professional Software Developers, as
well as the first most-wanted programming language
pg. 72
Web Developer
Web Developers typically specialize in either “front-end”
(“client-side”) development or “back-end” (“server-side”)
development, with the most sought-after development
professionals, called “Full-Stack Developers,” working in
both.

In addition to layout and server-side responsibilities, Web


Developers keep sites current with fresh updates and new
content. Web Developers typically work in a collaborative
role, communicating with management and other
programmers to ensure their website looks and functions
as intended.

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.

Python Developers also support Front-End Developers by


integrating their work with the Python application.

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.

Software Engineers’ day-to-day routines usually involve


ensuring active programs run smoothly, updating
programs, fixing bugs, and creating new programs.
Software Engineers write for a wide variety of
technologies and platforms, from smart home devices to
virtual assistants.

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.

A Data Analyst uses Python libraries to carry out data


analysis, parse data, analyze datasets, and create
visualizations to communicate findings in a way that’s
helpful to the organization.

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.

Machine Learning Engineer


If you’re looking to go beyond data analysis, you can
pursue machine learning, a subset of data science and
artificial intelligence. Machine Learning Engineers
perform statistical analysis and implement machine
learning algorithms that can be used in AI.

Machine Learning Engineers are also responsible for


taking theoretical data science models and helping scale
them to production-level models capable of handling
terabytes of real-time data.

Errors and Exceptions


Until now error messages haven’t been more than
mentioned, but if you have tried out the examples you
have probably seen some. There are (at least) two
distinguishable kinds of errors: syntax errors and
exceptions.

pg. 75
Syntax Errors

Syntax errors, also known as parsing errors, are perhaps


the most common kind of complaint you get while you are
still learning Python:
>>> while 1 print ’Hello world’
File "", line 1, in ?
while 1 print ’Hello world’

SyntaxError: invalid syntax

The parser repeats the offending line and displays a little


‘arrow’ pointing at the earliest point in the line where the
error was detected. The error is caused by (or at least
detected at) the token preceding the arrow: in the
example, the error is detected at the keyword print, since
a colon (‘:’) is missing before it. The file name and line
number are printed so you know where to look in case the
input came from a script.

Exceptions

Even if a statement or expression is syntactically correct,


it may cause an error when an attempt is made to execute
it. Errors detected during execution are called exceptions
and are not unconditionally fatal: you will soon learn how
to handle them in Python programs. Most exceptions are
not handled by programs.

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).

The rest of the line is a detail whose interpretation


depends on the exception type; its meaning is dependent
on the exception type.

The preceding part of the error message shows the


context where the exception happened, in the form of a
stack backtrace. In general it contains a stack backtrace
listing source lines; however, it will not display lines read
from standard input

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.

The try statement works as follows.


• First, the try clause (the statement(s) between the try
and except keywords) is executed.
• If no exception occurs, the except clause is skipped and
execution of the try statement is finished.
• If an exception occurs during execution of the try clause,
the rest of the clause is skipped. Then if its type matches
the exception named after the except keyword, the rest of
the try clause is skipped, the except clause is executed, and
then execution continues after the try statement.
• If an exception occurs which does not match the
exception named in the except clause, it is passed on to
outer try statements; if no handler is found, it is an
unhandled exception and execution stops with a message
as shown above.
A try statement may have more than one except clause, to
specify handlers for different exceptions. At most one
handler will be executed. Handlers only handle exceptions
that occur in the corresponding try clause, not in other
handlers of the same try statement.

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.

Statement and control flow


Python’s statements include(among others):
➢ The assignment statement, using a single equals
Sign =.
➢ The if statement, which conditionally executes a block
of code, along with else and elif (a contraction of else-
if).
➢ The for statement, which iterates over an iterable
object, capturing each element to a local variable for
use by the attached block.
➢ The while statement, which executes a block of code
as long as its condition is true.
➢ The try statement, which allows exceptions raised in
its attached code block to be caught and handled by
except clauses; it also ensures that clean-up code in a
finally block will always be run regardless of how the
block exits.
➢ The raise statement, used to raise a specified
exception or re-raise a caught exception.

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

1.Easy language python is an easy language. It is


easy to read, write, learn and understand.
▪ Python has smooth learning curve. It is easy to
learn.
▪ Python has a simple syntax and python code is
easy to understand.
▪ Since it’s easy to understand, you can easily
ream and understand someone else’s code.
▪ Python is also easy to write because of its write
because of its simple syntax.
2.Readable the python language is designed to make
developers life easy. Reading a python code is like
reading English sentence. This is one of the key
reason that makes python best for beginners.

pg. 88
Student Marksheet Program In Python
Programming Language

To make a simple student mark sheet program in a


python programming language. Using this program a
student can enter their Name, Roll Number, School name,
Father’s Name, and marks of their exams. After that based
upon the marks, the program can print the mark sheet of
the student that he/she fail or pass

Conditions for a student to pass the exam

To pass the school exam a student needs to have at least a


total of 44 number or marks in all particular subjects
including first-mid-term marks and second-mid-term
marks.
Also if a student has 0 marks in the first-mid-term exam
and 44 marks in the second-mid-term exam then also a
student passes the particular subject exam.

Condition for a student to fail in the exam

a student does not have at least 44 marks in any one


subject then he fails. So we need to print the fail in the
program

pg. 89
CODING

pg. 90
INPUT

pg. 91
OUTPUT

pg. 92
Explanation of the program

Here in the above program first we define the subjects list


in which we define the subject names and then we define a
subcode list that consists of subject codes. And then we
define the two empty list first-mid-term marks and
second-mid-term marks and two variables count and
MTotal and initialize its values to zero.
After that, we are taking the input from the user name,
fname, rnumber, and school using the input method. After
that using for loop we are taking the input for the subject
marks and store them in the first-mid-marks and second-
mid-marks list using the append method.
After that using the print method we are print the school
name, student name, her/his father name, and her/his roll
number. And after that, we are printing the subject code,
first-mid-term marks, second-mid-term marks and total
number of marks in a separate line using for loop as you
could see in the given above image.
And using the count variable we are finding that if there is
any subject for which the total number of marks is less
than 44 then we print the FAIL message on the screen.
Otherwise we print the PASS message on the screen

pg. 93

You might also like