Yogesh Report
Yogesh Report
INDUSTRIAL TRAININGREPORT
ON
“PROGRAMING WITH PYTHON”
submitted
inpartialfulfilment
fortheawardoftheDegreeof
BachelorofTechnology
In Department of Information Technology Engg.
SUBMITTED BY SUBMITTED TO
Avinash Tiwari Mr.Sachin Yadav(Training Incharge)
17EARIT011 Dr. Akhil Pandey
(Head of Department)
SettingupPATH ........................................................................................................................... 7
RunningPython ........................................................................................................................... 9
2.4.1) Script from theCommandline ............................................................................................ 11
IntegratedDevelopmentEnvironment ...................................................................................... 11
PythonCodeExecution ................................................................................................................12
FirstPythonProgram .................................................................................................................. 12
Chapter 3: StandardDataType……………………………………………………...20-37
PythonNumbers............................................................................................................................20
PythonStrings ............................................................................................................................... 21
PythonLists ................................................................................................................................... 22
PythonTuples ................................................................................................................................ 23
PythonDictionary ......................................................................................................................... 24
DataTypeConversion ................................................................................................................... 24
DecisionMaking ............................................................................................................................ 27
LoopingStatements ....................................................................................................................... 28
Overview ofOOPs Terminology................................................................................................... 30
Chapter4… .................................................................... …………………………………...…38-39
Summary ....................................................................................................................................... 38
Python, an open source scripting language, has become the most popular introductory
teaching language at top U.S. universities, especially Georgia Tech University.
Because it is a scripting language, Python automates tasks that would otherwise need
to be performed manually. Python programs also tend to be shorter than equivalent
programs written in Java because of its built-in high-level data types and its dynamic
typing. John Guttag, professor of electrical engineering and computer science at MIT,
believes more colleges are using Python as an introductory programming language is
that it has a very large set of highly useful libraries that have been built over the years
that support things that are easy to use from language proper. Shriram Krishnamurthi, a
professor of computer science at Brown University, agrees Python has made people
feel more comfortable about exposing programming to a much broader audience of
students. Krishnamurthi says Python may be fashionable right now, but he believes it
lacks staying power.
CHAPTER 1
INTRODUCTION
1.1 PYTHON
Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
1
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• A broad standard library: Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
2
Chapter 2
OPERTORS
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
3
// Floor Division - The division of operands where the 9//2 = 4 and
result is the quotient in which the digits after the
9.0//2.0 = 4.0,
decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away -11//3 = -4,
from zero (towards negative infinity): 11.0//3 = -4.0
2.2ASSIGNMENT OPERATOR
Table 2.1: Assignment Operators
+= Add AND It adds right operand to the left operand and c += a is equivalent
assign the result to left operand to c
=c+ a
-= Subtract AND It subtracts right operand from the left operand c -= a is equivalent
and assign the result to left operand to c=c
–a
*= Multiply AND It multiplies right operand with the left operand c *= a is equivalent
and assign the result to left operand to c = c * a
4
/= Divide AND It divides left operand with the right operand
and assign the result to left operand c /= a is equivalent
to c = c / ac /= a is
equivalent to c =
c/a
5
is not Evaluates to false if the variables on either side of the x is not y, here
operator point to the same object and true otherwise. is not results in
1 if id(x) is not
equal to id(y
& Binary Operator copies a bit to the result if it exists (a & b) (means 0000
^ Binary It copies the bit if it is set in one operand but not (a ^ b) = 49 (means
XOR both. 0011 0001)
~ Binary It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means
Ones 1100 0011 in 2's
complement form due
Complement to a signed binary
number.
6
>> Binary The left operands value is moved right by the a >> 2 = 15 (means
Right Shift number of bits specified by the right operand.
0000 1111)
and Logical If both the operands are true then condition becomes (a and b) is true.
AND true.
not Logical Used to reverse the logical state of its operand. Not(a and b) is
NOT false.
7
not in Evaluates to true if it does not finds a variable in the x not in y, here not
specified sequence and false otherwise. in results in a
1 if x is not a
member of
sequence y.
Operator Description
~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)
8
^| Bitwise exclusive `OR' and regular `OR'
= %= Assignment operators
/=//= -=
+= *= =*
9
Chapter3
COLLECTION IN PYTHON
3.1 LIST
The list is a most versatile data type available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.
Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
10
for x in [1, 2, 3]: print x, 123 Iteration
1 list.append(obj)
2 list.count(obj)
3 list.index(obj)
4 list.insert(index, obj)
5 list.pop(obj=list[-1])
6 list.remove(obj)
11
7 list.reverse()
8 list.sort([func])
3.3 TUPLES
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
tup2 = (1, 2, 3, 4, 5 );
tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and
so on.
12
Accessing Values in Tuples:
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example –
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples:
Tuples are immutable which means you cannot update or change the values of tuple
elements. We are able to take portions of existing tuples to create new tuples as the
following example demonstrates −
print tup3
13
Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements discarded.
3.4 DICTIONARY
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
14
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −
Result –
Updating Dictionary
We can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
15
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example –
print "dict['Age']:
dict['School']
16
CHAPTER 4
FUNCTIONS IN PYTHON
• Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
• The code block within every function starts with a colon (:) and is indented.
17
4.2 CALLING A FUNCTION
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code. Once the basic structure
of a function is finalized, you can execute it by calling it from another function or
directly from the
Python prompt. Following is the example to call printme() function
str return;
You can call a function by using the following types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.The scope of a variable
determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python –
18
CHAPTER 5
The simplest way to produce output is using the print statement where you can pass
zero or more expressions separated by commas. This function converts the
expressions you pass into a string and writes the result to standard output as follows
it?"
Result:
Python provides two built-in functions to read a line of text from standard input,
which by default comes from the keyboard. These functions are −
• raw_input
• input
The raw_input([prompt]) function reads one line from standard input and returns it
as a string (removing the trailing newline).
19
This prompts you to enter any string and it would display same string on the screen.
When I typed "Hello Python!", its output is like this −
This would produce the following result against the entered input −
Until now, you have been reading and writing to the standard input and output.
Now, we will see how to use actual data files.
Before you can read or write a file, you have to open it using Python's builtinopen()
function. This function creates a file object, which would be utilized to call other
support methods associated with it. Syntax
20
file object = open(file_name [, access_mode][, buffering])
• file_name: The file_name argument is a string value that contains the name
of the file that you want to access.
• access_mode: The access_mode determines the mode in which the file has
to be opened, i.e., read, write, append, etc. A complete list of possible values
is given below in the table. This is optional parameter and the default file
access mode is read (r).
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of
the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at
the beginning of the file. This is the default mode.
21
r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and
writing.
wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not exist, creates
a new file for reading and writing.
A Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
Ab Opens a file for appending in binary format. The file pointer is at the end of
the file if the file exists. That is, the file is in the append mode. If the file
does not exist, it creates a new file for writing.
22
a+ Opens a file for both appending and reading. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does
not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading and writing.
The close() method of a file object flushes any unwritten information and closes the
file object, after which no more writing can be done.Python automatically closes a
file when the reference object of a file is reassigned to another file. It is a good
practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
23
5.3 READING AND WRITING FILES
The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.The write() method does not
add a newline character ('\n') to the end of the string Syntax
fileObject.write(string);
The read() method reads a string from an open file. It is important to note that
Python strings can have binary data. apart from text data. Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it
tries to read as much as possible, maybe until the end of file.
CHAPTER 6
Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them −
24
• Exception Handling: This would be covered in this tutorial.
Here is a list standard Exceptions available in
Python:StandardExceptions.
EXCEPTION DESCRIPTION
NAME
StopIteration Raised when the next() method of an iterator does not point to
any object.
StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
25
OverflowError Raised when a calculation exceeds maximum limit for a numeric
type.
ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.
26
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
IOError
does not exist.
SystemError Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
27
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
CHAPTER 7
28
(class variables and instance variables) and methods, accessed via dot
notation.
29
7.2 CREATING CLASSES
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:
ClassName.__doc__.
Instead of starting from scratch, you can create a class by deriving it from a
preexisting class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those
attributes as if they were defined in the child class. A child class can also override
data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base
classes to inherit from is given after the class name −
30
7.4 OVERRIDING METHODS
You can always override your parent class methods. One reason for overriding
parent's methods is because you may want special or different functionality in your
subclass. Example
myMethod(self):
myMethod(self):
Following table lists some generic functionality that you can override in your own
classes –
31
1 __init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call :obj = className(args)
2 __del__( self )
Destructor, deletes an object
Sample Call :delobj
3 __repr__( self )
Evaluatable string representation
Sample Call :repr(obj)
4 __str__( self )
Printable string representation
Sample Call :str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call :cmp(obj, x)
Suppose you have created a Vector class to represent two-dimensional vectors, what
happens when you use the plus operator to add them? Most likely Python will yell at
you.
32
You could, however, define the __add__ method in your class to perform vector
addition and then the plus operator would behave as per expectation −
7.7 DATA HIDING
An object's attributes may or may not be visible outside the class definition. You
need to name attributes with a double underscore prefix, and those attributes then
are not be directly visible to outsiders.
Example
class JustCounter:
__secretCount = 0
def count(self):
print counter._JustCounter__secretCount
33
Chapter 8
DJANGO
• Versatile: Django can be (and has been) used to build almost any type of
website — from content management systems and wikis, through to social
networks and news sites. It can work with any client-side framework, and
can deliver content in almost any format (including HTML, RSS feeds,
JSON, XML, etc). The site you are currently reading is based on Django!
Internally, while it provides choices for almost any functionality you might
want (e.g. several popular databases, templating engines, etc.), it can also be
extended to use other components if needed.
34
storing passwords rather than a password hash. A password hash is a
fixedlength value created by sending the password through acryptographic
hashfunction.Django can check if an entered password is correct by running
it through the hash function and comparing the output to the stored hash
value.
However due to the "one-way" nature of the function, even if a stored hash
value is compromised it is hard for an attacker to work out the original
password.
35
In a traditional data-driven website, a web application waits for HTTP requests
from the web browser (or other client). When a request is received the application
works out what is needed based on the URL and possibly information in POST
data or GET data. Depending on what is required it may then read or write
information from a database or perform other tasks required to satisfy the request.
The application will then return a response to the web browser, often dynamically
creating an HTML page for the browser to display by inserting the retrieved data
into placeholders in an HTML template.
Django web applications typically group the code that handles each of these steps
into separate files:
36
Explanation of parts of flow chart is as follows:
• URLs: While it is possible to process requests from every single URL via a
single function, it is much more maintainable to write a separate view
function to handle each resource. A URL mapper is used to redirect HTTP
requests to the appropriate view based on the request URL. The URL mapper
can also match particular patterns of strings or digits that appear in an URL,
and pass these to a view function as data.
37
CHAPTER 9
38
Fig 9.2: New Banking User Page
39
User Table Page: -
40
User Edit Page: -
SignIn Page: -
41
SignUp Page: -
CHAPTER 10
FLASK
If you're developing a web app in Python, chances are you're leveraging a framework. A
framework "is a code library that makes a developer's life easier when building reliable,
scalable, and maintainable web applications" by providing reusable code or extensions
for common operations. There are a number of frameworks for Python, including Flask,
Tornado, Pyramid, and Django.
Flask is a small and powerful web framework for Python. It's easy to learn and simple to
use, enabling you to build your web app in a short amount of time.
In this article, I'll show you how to build a simple website, containing two static pages
with a small amount of dynamic content. While Flask can be used for building complex,
databasedriven websites, starting with mostly static pages will be useful to introduce a
workflow, which we can then generalize to make more complex pages in the future.
42
Upon completion, you'll be able to use this sequence of steps to jumpstart your next
Flask app.
Installing FLASK
Before getting started, we need to install Flask. Because systems vary, things can
sporadically go wrong during these steps. If they do, like we all do, just Google the error
message or leave a comment describing the problem.
Install virtualenv
Virtualenv is a useful tool that creates isolated Python development environments where
you can do all your development work.
We'll use virtualenv to install Flask. Virtualenv is a useful tool that creates isolated
Python development environments where you can do all your development work.
Suppose you come across a new Python library that you'd like to try. If you install it
system-wide, there is the risk of messing up other libraries that you might have
installed. Instead, use virtualenv to create a sandbox, where you can install and use the
library without affecting the rest of your system. You can keep using this sandbox for
ongoing development work, or you can simply delete it once you've finished using it.
Either way, your system remains organized and clutter-free.
It's possible that your system already has virtualenv. Refer to the command line, and try
running: $ virtualenv –version
Install flask
After installing virtualenv, you can create a new isolated development environment, like
so: $ virtualenvflaskapp
Here, virtualenv creates a folder, flaskapp/, and sets up a clean copy of Python inside for
you to use. It also installs the handy package manager, pip.
Enter your newly created development environment and activate it so you can begin
working within it.
$ cd flaskapp
$ . bin/activate
Now, you can safely install Flask:
43
$ pip install Flask
01 .
02 .
03 ├── app
04 │ ├── static
05 │ │ ├── css
06 │ │ ├── img
07 │ │ └── js
08 │ ├── templates
09 │ ├── routes.py
10 │ └── README.md
Within flaskapp/, create a folder, app/, to contain all your files. Inside app/, create a
folder static/; this is where we'll put our web app's images, CSS, and JavaScript files, so
create folders for each of those, as demonstrated above. Additionally, create another
folder, templates/, to store the app's web templates. Create an empty Python file
routes.py for the application logic, such as URL routing.
And no project is complete without a helpful description, so create a README.md file
as well.
CONCLUSION
In programming the constructs we have learnt (loops, conditions, data structures)
mean that we are far more expressive as programmers. Combined with abstractions
we can compose and recompose new programs. Building on our previously defined
concept of a house we now use repetition to define a row of houses.
Computers are complex. Even the smallest operation hides layers of incredible
complexity. Programming is not only about getting a computer to do things. It is
44
about writing code that is useful to humans. Good programming is harnessing
complexity by writing code that rhymes with our intuitions. Good code is code that
we can use with a minimal amount of context and already be productive.
• the definition of the function object called square is shorter clearer and truer
to its mathematical (conceptual) definition.
In design we have gone from step by step instructions to defining blocks of code in
such a way as to define higher level concepts. Defining reusable components and
the ability to repeat them is immensely powerful.
Think of everything you can make from Lego bricks. Minecraft is a world build
with cubes. In the real world think of all the components and repetition you
typically find in a skyscraper.
This is where programming starts to become creative. You can define the universe
of things that is of interest to you.
REFERENCES
[1.]Training Manual
[2.]http://python.org
[3.]http://diveintopython.org
45
[4.]http://djangoproject.com
[5.]http://GeeksForGeeks.com
46