2 Unit
2 Unit
1 Python 3 – Overview
Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and
preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of
Python 3.
2.1.2 Python Features
Python's features include-
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a 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, 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.
Apart from the above-mentioned features, Python has a big list of good features. A few
are listed below-
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building
large applications.
It provides very high-level dynamic data types and supports dynamic typechecking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. –
Getting Python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available .
The following different installation options are available.
Windows x86-64 embeddable zip file
Windows x86-64 executable installer
Windows x86-64 web-based installer
Windows x86 embeddable zip file
Windows x86 executable installer
Windows x86 web-based installer
Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1.
For versions 3.0 to 3.4.x, Windows XP is acceptable.ie
Linux platform
Different flavors of Linux use different package managers for installation of new packages.
On Ubuntu Linux, Python 3 is installed using the following command from the terminal.
$sudo apt-get install python3-minimal
Installation from source Download Gzipped source tarball from Python's download URL:
https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
Extract the tarball
tar xvfz Python-3.5.1.tgz
Configure and Install:
cd Python-3.5.1
./configure --prefix=/opt/python3.5.1
make
sudo make install
Mac OS
Download Mac OS installers from this URL:https://www.python.org/downloads/mac-osx/
Mac OS X 64-bit/32-bit installer : python-3.5.1-macosx10.6.pkg
Mac OS X 32-bit i386/PPC installer : python-3.5.1-macosx10.5.pkg
Double click this package file and follow the wizard instructions to install.
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python:
Python Official Website : http://www.python.org/
You can download Python documentation from the following site. The documentation is
available in HTML, PDF and PostScript formats.
Python Documentation Website : www.python.org/doc/
Key Points :
Way of Handling different types of files:
- The interpreter operates 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.
- To execute statements in command, python -c command [arg] ..., will be used. Since
Python statements often contain spaces or other characters that are special to the shell, it
is usually advised to quote command in its entirety with single quotes.
- When Python modules are used as scripts, python -m module [arg] ..., is used to invoke
which executes the source file for module.
- When a script file is used, it is sometimes useful to be able to run the script and enter
interactive mode afterwards. This can be done by passing -i before the script.
2.2 Interactive Interpreter and 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:
$ python3.2
Python 3.2 (py3k, Sep 12 2007, 12:21:02)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
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!
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):
exec(open(filename).read())
’/home/user/.local/lib/python3.2/site-packages’
Now a file named usercustomize.py can be created in that directory and can put anything in it.
It will affect every invocation of Python, unless it is started with the -s option to disable the
automatic import.
A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
For example, the script
print 1
x=2
print x
Exercise 2.1. Type the following statements in the Python interpreter to see what they do:
5
x=5
x+1
Now put the same statements into a script and run it. What is the output? Modify the script by
transforming each expression into a print statement and then run it again
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma separated
sequence of integers. This is the first example we have seen of a semantic error:the code runs
without producing an error message, but it doesn’t do the “right” thing.Variables are nothing but
reserved memory locations to store values. It means that when you create a variable, you reserve
some space in the memory.Based on the data type of a variable, the interpreter allocates memory
and decides what can be stored in the reserved memory. Therefore, by assigning different data
types to the variables, you can store integers, decimals or characters in these variables.
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example
a=b=c=1
Here, an integer object is created with the value 1, and all the three variables are assigned
to the same memory location. You can also assign multiple objects to multiple variables.
For example
a,b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
2.3.2 Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them
and the storage method for each of them.
Python has five standard data types-
Numbers
String
List
Tuple
Dictionary
The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −
76trombones is illegal because it does not begin with a letter. more@ is illegal because it
contains an illegal character, @. But what’s wrong with class?
It turns out that class is one of Python’s keywords. The interpreter uses keywords to
recognize the structure of the program, and they cannot be used as variable names.
When you execute the above program, it produces the following result
Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you
have to use a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value
is assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments. The number of variables on the left and the number of values on
the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For example,
to split an email address into a user name and a domain, you could write:
>>> addr = '[email protected]'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>> uname
'monty'
>>> domain
'python.org'
2.5 Comments
As programs get bigger and more complicated, they get more difficult to read. Formal
languages are dense, and it is often difficult to look at a piece of code and figure out what
it is doing, or why.For this reason, it is a good idea to add notes to your programs to explain in
natural language what the program is doing. These notes are called comments, and they start
with the # symbol:
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end
of a line:
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the # to the end of the line is ignored—it has no effect on the program.
Comments are most useful when they document non-obvious features of the code. It is
reasonable to assume that the reader can figure out what the code does; it is much more
useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read, so there is a tradeoff.
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows-
2.6 Modules
A module is a file containing Python definitions and statements. The file name is the module
name with the suffix .py appended. Within a module, the module’s name (as a string) is available
as the value of the global variable __name__.A module allows you to logically organize your
Python code. Grouping related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can bind and reference.
Here is an example of a simple module, support.py
This imports all names except those beginning with an underscore (_). In most cases Python
programmers do not use this facility since it introduces an unknown set of names into the
interpreter, possibly hiding some things you have already defined.Note that in general the
practice of importing * from a module or package is frowned upon, since it often causes poorly
readable code. However, it is okay to use it to save typing in interactive sessions.
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.• 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.
It is possible to have a file called spam.pyc (or spam.pyo when -O is used) without a file
spam.py for the same module. This can be used to distribute a library of Python code in a
form that is moderately hard to reverse engineer.
The module compileall can create .pyc files (or .pyo files when -O is used) for all
modules in a directory.
#!/usr/bin/python3
# Import built-in module math
import math
content = dir(math)
print (content)
Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.
#!/usr/bin/python3
def Pots():
print ("I'm Pots Phone")
Similarly, we have other two files having different functions with the same name as above.
They are −
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now, create one more file __init__.py in the Phone directory-
Phone/__init__.py
To make all of your functions available when you have imported Phone, you need to put
explicit import statements in __init__.py as follows from
After you add these lines to __init__.py, you have all of these classes available when you
import the Phone package.
#!/usr/bin/python3
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
2.7 Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.In the context of programming, a function is a named sequence of statements that
performs a computation. When you define a function, you specify the name and the sequence of
statements.:
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of
the function. The result, for this function, is the type of the argument. It is common to say that a
function “takes” an argument and “returns” a result. The result is called the return value.
#output:
The value of x after swapping: 10
The value of y after swapping: 5
lst=[10,20,30,40,50,60,70,80]
n=input('How many positions to shift')
if n == 0:
print("shift position should be greater than 0")
else:
for x in range(n):
temp = lst[0]
for index in range(len(lst) - 1):
lst[index] = lst[index + 1]
lst[index + 1] = temp
print('After shifting '+str(n)+' times')
print(lst)
#output:
How many positions to shift 2
After shifting 2 times
[30, 40, 50, 60, 70, 80, 10, 20]
#output:
6.324555320336759