0% found this document useful (0 votes)
50 views39 pages

2 Unit

Uploaded by

lokgenie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views39 pages

2 Unit

Uploaded by

lokgenie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

2.

1 Python 3 – Overview

Python is a high-level, interpreted, interactive and object-oriented scripting language.


Python is designed to be highly readable. It uses English keywords frequently whereas the
other languages use punctuations. It has fewer syntactical constructions than other languages.
 Python is Interpreted: Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.
 Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginnerlevel
programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.

2.1.1 History of 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.
 Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
 Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.
 Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.

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

2.1.3 Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed and which
version is installed.

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/

2.1.4 Setting up PATH


Programs and other executable files can be in many directories. Hence, the operating
systems provide a search path that lists the directories that it searches for executables.
The important features are-
 The path is stored in an environment variable, which is a named string maintained
by the operating system. This variable contains information available to the
command shell and other programs.
 The path variable is named as PATH in Unix or Path in Windows (Unix is case
sensitive;Windows is not).
 In Mac OS, the installer handles the path details. To invoke the Python interpreter
from any particular directory, you must add the Python directory to your path.

Setting Path at Unix/Linux


To add the Python directory to the path for a particular session in Unix-
 In the csh shell: type setenv PATH "$PATH:/usr/local/bin/python3" and press Enter.
 In the bash shell (Linux): type export PATH="$PATH:/usr/local/bin/python3"
and press Enter.
 In the sh or ksh shell: type PATH="$PATH:/usr/local/bin/python3" and press
Enter.
Note: /usr/local/bin/python3 is the path of the Python directory.

Setting Path at Windows


To add the Python directory to the path for a particular session in Windows-
At the command prompt : type
path %path%;C:\Python and press Enter.
Note: C:\Python is the path of the Python directory.
Python Environment Variables
Here are important environment variables, which are recognized by Python-
wVariable Description

PYTHONPATH It has a role similar to PATH. This variable


tells the Python
interpreter where to locate the module files
imported into a
program. It should include the Python source
library directory and
the directories containing Python source code.
PYTHONPATH is
sometimes, preset by the Python installer.

PYTHONSTARTUP It contains the path of an initialization file


containing Python
source code. It is executed every time you start
the interpreter. It
is named as .pythonrc.py in Unix and it
contains commands that
load utilities or modify PYTHONPATH.
PYTHONCASEOK It is used in Windows to instruct Python to find
the first caseinsensitive
match in an import statement. Set this variable
to any
value to activate it.
PYTHONHOME It is an alternative module search path. It is
usually embedded in
the PYTHONSTARTUP or PYTHONPATH
directories to make
switching module libraries easy.

2.1.5 Running Python


There are three different ways to start Python-
(1) Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a commandline
interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
Here is the list of all the available command line options-
(2) Script from the Command-line
A Python script can be executed at the command line by invoking the interpreter on your
application, as shown in the following example.
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C:>python script.py # Windows/DOS
Note: Be sure the file permission mode allows execution.

(3) Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have
a GUI application on your system that supports Python.
 Unix: IDLE is the very first Unix IDE for Python.
 Windows: PythonWin is the first Windows interface for Python and is an IDE with
a GUI.
 Macintosh: The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files. If you are
not able to set up the environment properly, then you can take the help of your
system admin. Make sure the Python environment is properly set up and working
perfectly fine.

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!

2.2.1 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. All error messages are written to the standard error
stream; normal output from executed commands is written to standard output.

2.2.2 Source Code Encoding


Python source files are treated as encoded in UTF-8. In that encoding, characters of most
languages in the world can be used simultaneously in string literals, identifiers and comments
It is also possible to specify a different encoding for source files. In order to do this, put one
more special comment line right after the #! line to define the source file encoding:
# -*- coding: encoding -*-
For example, if your editor of choice does not support UTF-8 encoded files and insists on using
some other encoding, say Windows-1252, you can write:
# -*- coding: cp-1252 -*-
and still use all characters in the Windows-1252 character set in the source files.
2.2.3 The Interactive Startup File
Some standard commands are executed every time when interpreter is started. These start up
commands will be put on a separate file and environment variable named PYTHONSTARTUP
is set to the name of a file containing your start-up commands. This file is only read in
interactive sessions. 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.

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

2.2.4 The Customization Modules


Python provides two hooks to customize it: sitecustomize and usercustomize. To work with
this ,it is necessary to find the location of your user site-packages directory. Start Python and run
this code:
>>> import site
>>> site.getusersitepackages()

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

2.2.5. Basic Example for Interactive mode and script mode


One of the benefits of working with an interpreted language is that you can test bits of
code in interactive mode before you put them in a script.
For example, if Python is using as a calculator, we might type
>>> miles = 26.2
>>> miles * 1.61
42.182
The first line assigns a value to miles, but it has no visible effect. The second line is an
expression, so the interpreter evaluates it and displays the result. So we learn that a marathon
is about 42 kilometers. But if you type the same code into a script and run it, you get no output at
all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the
expression,but it doesn’t display the value unless you tell it to:
miles = 26.2
print miles * 1.61

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

produces the output


1
2
The assignment statement produces no output.

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

2.3 Values and types


A value is one of the basic things a program works with, like a letter or a number. The
values we have seen so far are 1, 2, and 'Hello, World!'.These values belong to different types: 2
is an integer, and 'Hello, World!' is a string, so-called because it contains a “string” of letters.
You (and the interpreter) can identify strings because they are enclosed in quotation marks.
If you are not sure what type a value has, the interpreter can tell you.
>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
Not surprisingly, strings belong to the type str and integers belong to the type int. Less
obviously, numbers with a decimal point belong to a type called float, because these numbers
are represented in a format called floating-point.
>>> type(3.2)
<type 'float'>
What about values like '17' and '3.2'? They look like numbers, but they are in quotation
marks like strings.
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
They’re strings.
When you type a large integer, you might be tempted to use commas between groups of
three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

Figure 2.1: State diagram


>>> 1,000,000
(1, 0, 0)

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.

2.3.1 Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used
to assign values to variables.The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in the variable.

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

Python supports three different numerical types −


 int (signed integers)
 float (floating point real values)
 complex (complex numbers)
All integers in Python 3 are represented as long integers. Hence, there is no separate
number type as long.
Examples
Here are some examples of numbers

A complex number consists of an ordered pair of real floating-point numbers denoted by


x + yj, where x and y are real numbers and j is the imaginary unit.
2.3.3. Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of strings
can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example-

This will produce the following result-

2.3.4. Python Lists


Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists are
similar to arrays in C. One of the differences between them is that all the items belonging
to a list can be of different data type. The values stored in a list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way
to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
For example-

This produces the following result-

2.3.5 Python Tuples


A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parenthesis.The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-only lists. For example-
This produces the following result-

The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −

2.3.6 Python Dictionary


Python's dictionaries are kind of hash-table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([]). For example-
This produces the following result-

2.3.7 Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type-name as a function.
There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.
2.4 Variables
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value.
An assignment statement creates new variables and gives them values:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932
This example makes three assignments. The first assigns a string to a new variable named
message; the second gives the integer 17 to n; the third assigns the (approximate) value of
p to pi.
A common way to represent variables on paper is to write the name with an arrow pointing
to the variable’s value. This kind of figure is called a state diagram because it shows what
state each of the variables is in (think of it as the variable’s state of mind). Figure 2.1 shows
the result of the previous example.
The type of a variable is the type of the value it refers to.
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

2.4.1 Variable names and keywords


Programmers generally choose names for their variables that are meaningful—they document
what the variable is used for. Variable names can be arbitrarily long. They can contain both
letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it
is a good idea to begin variable names with a lowercase letter The underscore character, _, can
appear in a name. It is often used in names with multiple words, such as my_name or
airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax

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.

Python 2 has 31 keywords:


and ,del ,from, not, while, as, elif ,global, or, with,assert, else if, pass, yield, break, except,
import, print,class, exec, in, raise,continue, finally, is, return,def, for, lambda, try
In Python 3, exec is no longer a keyword, but nonlocal is.

2.4.2 Operators and operands


Operators are special symbols that represent computations like addition and multiplication.
The values the operator is applied to are called operands. The operators +, -, *, / and ** perform
addition, subtraction, multiplication, division and exponentiation, as in the following examples:
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator
called XOR. I won’t cover bitwise operators in this book, but you can read about them at
http://wiki.python.org/moin/BitwiseOperators.
In Python 2, the division operator might not do what you expect:
>>> minute = 59
>>> minute/60
0
The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0.
The reason for the discrepancy is that Python is performing floor division. When both of
the operands are integers, the result is also an integer; floor division chops off the fraction
part, so in this example it rounds down to zero.
In Python 3, the result of this division is a float. The new operator // performs floor
division.If either of the operands is a floating-point number, Python performs floating-point
division,and the result is a float:
>>> minute/60.0
0.98333333333333328

2.4.3 Expressions and statements


An expression is a combination of values, variables, and operators. A value all by itself
is considered an expression, and so is a variable, so the following are all legal expressions
17
x
x + 17
A statement is a unit of code that the Python interpreter can execute. We have seen two
kinds of statement: print and assignment. Technically an expression is also a statement, but it is
probably simpler to think of them as different things. The important difference is that an
expression has a value; a statement does not.

2.4.4 Order of operations


When more than one operator appears in an expression, the order of evaluation depends
on the rules of precedence. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:
 Parentheses have the highest precedence and can be used to force an expression to
evaluate inthe order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression
easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is
3, not 27.
 Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not
4, and 6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right (except
exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the
result is multiplied by pi. To divide by 2p, you can use parentheses or write degrees
/ 2 / pi.

Python Operators Precedence


The following table lists all the operators from highest precedence to the lowest.

Operator precedence affects the evaluation of an expression. For example, x = 7 + 3 * 2; here, x


is assigned 13, not 20 because the operator * has higher precedence than +, so it first multiplies
3*2 and then is added to 7.
Here, the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Example

When you execute the above program, it produces the following result

2.4.5 Tuples are immutable


A tuple is a sequence of values. The values can be any type, and they are indexed by
integers, so in that respect tuples are a lot like lists. The important difference is that tuples
are immutable. Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
<class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<class 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates
an empty tuple:
>>> t = tuple()
>>> t
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:
>>> t = tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, you should avoid using it as a variable
name.Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> t[0]
'a'
And the slice operator selects a range of elements.
>>> t[1:3]
('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
Because tuples are immutable, you can’t modify the elements. But you can replace one
tuple with another:
>>> t = ('A',) + t[1:]
>>> t
('A', 'b', 'c', 'd', 'e')
This statement makes a new tuple and then makes t refer to it.
The relational operators work with tuples and other sequences; Python starts by comparing
the first element from each sequence. If they are equal, it goes on to the next elements, and
so on, until it finds elements that differ. Subsequent elements are not considered .
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True

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

def print_func( par ):


print "Hello : ", par
return

2.6.1 The import Statement


You can use any Python source file as a module by executing an import statement in some
other Python source file. The import has the following syntax
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module
is present in the search path. A search path is a list of directories that the interpreter
searches before importing a module. For example, to import the module hello.py, you
need to put the following command at the top of the script-
#!/usr/bin/python3
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Mary")

When the above code is executed, it produces the following result-


Hello : Mary
For one more instance, use your favorite text editor to create a file called fibo.py in the current
directory with the following contents:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=’ ’)
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
>>> import fibo
This does not enter the names of the functions defined in fibo directly in the current symbol
table; it only enters the
module name fibo there. Using the module name you can access the functions:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
’fibo’
If you intend to use a function often you can assign it to a local name:
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

2.6.1 More on Modules


A module can contain executable statements as well as function definitions. These statements are
intended to initialize the module. They are executed only the first time the module is imported
somewhere. Each module has its own private symbol table, which is used as the global symbol
table by all functions defined in the module. Thus, the author of a module can use global
variables in the module without worrying about accidental clashes with a user’s global variables.
On the other hand, if you know what you are doing you can touch a module’s global variables
with the same notation used to refer to its functions, modname.itemname.Modules can import
other modules. It is customary but not required to place all import statements at the beginning
of a module (or script, for that matter). The imported module names are placed in the importing
module’s global symbol table.There is a variant of the import statement that imports names from
a module directly into the importing module’s symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the local symbol
table .There is even a variant to import all names that a module defines:
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

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.

2.6.2 Executing modules as scripts


When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the __name__ set to
"__main__". That means that by adding this code at the end of your module:
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module, because the code that
parses the command line only runs if the module is executed as the “main” file:
$ python fibo.py 50
1 1 2 3 5 8 13 21 34
If the module is imported, the code is not run:
>>> import fibo
>>>
This is often used either to provide a convenient user interface to a module, or for testing
purposes.

2.6.3 The Module Search Path


When a module named spam is imported, the interpreter first searches for a built-in module with
that name. If not found, it then searches for a file named spam.py in a list of directories given by
the variable sys.path. sys.path is initialized from these locations:
• the directory containing the input script (or the current directory).
• PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
• the installation-dependent default.
After initialization, Python programs can modify sys.path. The directory containing the
script being run is placed at the beginning of the search path, ahead of the standard library path.
This means that scripts in that directory will be loaded instead of modules of the same name in
the library directory. This is an error unless the replacement is intended.

2.6.4 “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.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 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. 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.• 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.

2.6.5 Standard Modules


Python comes with a library of standard modules, described in a separate document, the Python
Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter;
these provide access to operations that are not part of the core of the language but are
nevertheless built in, either for efficiency or to provide access to operating system primitives
such as system calls. The set of such modules is a configuration option which also depends on
the underlying platform For example, the winreg module is only provided on Windows systems.
One particular module deserves some attention: sys, which is built into every Python interpreter.
The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:
>>> import sys
>>> sys.ps1
’>>> ’
>>> sys.ps2
’... ’
>>> sys.ps1 = ’C> ’
C> print(’Yuck!’)
Yuck!
C>
These two variables are only defined if the interpreter is in interactive mode.The variable
sys.path is a list of strings that determines the interpreter’s search path for modules. It is
initialized to a default path taken from the environment variable PYTHONPATH, or from a
built-in default if PYTHONPATH is not set. You can modify it using standard list operations:
>>> import sys
>>> sys.path.append(’/ufs/guido/lib/python’)
2.6.6 The dir( ) Function
The dir() built-in function returns a sorted list of strings containing the names defined by
a module.The list contains the names of all the modules, variables and functions that are defined
in a module. Following is a simple example-

#!/usr/bin/python3
# Import built-in module math
import math
content = dir(math)
print (content)

When the above code is executed, it produces the following result-


['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.

2.6.7 The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and
local namespaces depending on the location from where they are called.
 If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
 If globals() is called from within a function, it will return all the names that can
be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function.

2.6.8 The reload() Function


When a module is imported into a script, the code in the top-level portion of a module is
executed only once. Therefore, if you want to reexecute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously imported module again.

The syntax of the reload() function is this


reload(module_name)
Here, module_name is the name of the module you want to reload and not the string
containing the module name.

2.6.9 Packages in Python


A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has the following line of
source code-

#!/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

Pots import Pots


from Isdn import Isdn
from G3 import G3

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

When the above code is executed, it produces the following result

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single function in each file, but you
can keep multiple functions in your files. You can also define different Python classes in
those files and then you can create your packages out of those classes.

2.6.10 Intra-package References


When packages are structured into subpackages ,you can use absolute imports to refer to
submodules of siblings packages. 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.
You can also write relative imports, with the from module import name form of import
statement. These imports use leading dots to indicate the current and parent packages involved in
the relative import. From the surround module for example, you might use:
from . import echo
from .. import formats
from ..filters import equalizer
Note that relative imports are based on the name of the current module. Since the name of the
main module is always
"__main__", modules intended for use as the main module of a Python application must always
use absolute imports.

2.6.11 Packages in Multiple Directories


Packages support one more special attribute, __path__. This is initialized to be a list containing
the name of the directory holding the package’s __init__.py before the code in that file is
executed. This variable can be modified; doing so affects future searches for modules and
subpackages contained in the package.

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.

2.7.1 Defining a Function


You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
Example
The following function takes a string as input parameter and prints it on the standard
screen.
def printme( str ):
"This prints a passed string into this function"
print (str)
return

2.7.2 Calling a Function


Defining a function 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 an example to call the printme() function-
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme()
printme("This is first call to the user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result-


This is first call to the user defined function!
Again second call to the same function

2.7.3 Type conversion functions


Python provides built-in functions that convert values from one type to another. The int
function takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
int can convert floating-point values to integers, but it doesn’t round off; it chops off the
fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'

2.7.4 Math functions


Python has a math module that provides most of the familiar mathematical functions. A
module is a file that contains a collection of related functions.Before we can use the module, we
have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you
get some information about it:
>>> print math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To access
one of the functions, you have to specify the name of the module and the name of the
function, separated by a dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that
signal_power and noise_power are defined). The math module also provides log, which
computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin
and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert
from degrees to radians, divide by 360 and multiply by 2p:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
The expression math.pi gets the variable pi from the math module. The value of this
variable is an approximation of p, accurate to about 15 digits.If you know your trigonometry, you
can check the previous result by comparing it to the square root of two divided by two:
>>> math.sqrt(2) / 2.0
0.707106781187

2.7.5 Function Arguments


You can call a function by using the following types of formal arguments-
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows-
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme()

When the above code is executed, it produces the following result-


Traceback (most recent call last):
File "test.py", line 11, in <module>
printme()
TypeError: printme() missing 1 required positional argument: 'str'

2.7.6 Keyword Arguments


Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.This allows you to skip
arguments or place them out of order because the Python interpreter is able to use the keywords
provided to match the values with parameters. You can also make keyword calls to the printme()
function in the following ways-
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result-
My string
The following example gives a clearer picture. Note that the order of parameters does not
matter.
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result-


Name: miki
Age 50
2.7.7 Default Arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument. The following example gives an idea on default arguments,
it prints default age if it is not passed.
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result-


Name: miki
Age 50
Name: miki
Age 35

2.7.8 Variable-length Arguments


You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is given below
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all non keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call. Following is a simple example-
#!/usr/bin/python3
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result-


Output is:
10
Output is:
70
60
50

2.7.9 The Anonymous Functions


These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
 Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an
expression.
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation
by passing function, during invocation for performance reasons.
Syntax
The syntax of lambda function contains only a single statement, which is as follows
lambda[arg1 [,arg2,.....argn]]:expression

Following is an example to show how lambda form of function works-


#!/usr/bin/python3
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
When the above code is executed, it produces the following result
Value of total : 30
Value of total : 40

2.7.10 The return Statement


The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
All the examples given above are not returning any value. You can return a value from a
function as follows-
#!/usr/bin/python3
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total
# Now you can call sum function
total = sum( 10, 20 )
print ("Outside the function : ", total )

When the above code is executed, it produces the following result-


Inside the function : 30
Outside the function : 30

2.7.11 Scope of Variables


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-
 Global variables
 Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared inside it are
brought into scope.
Following is a simple example-
#!/usr/bin/python3
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )

When the above code is executed, it produces the following result-


Inside the function local total : 30
Outside the function global total : 0

2.8 Illustrative programs:

Exchange the values of two variables

# Python program to swap two variables


# To take input from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')
x=5
y = 10
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

#output:
The value of x after swapping: 10
The value of y after swapping: 5

Circulate the values of n variables

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]

Distance between two points


import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

#output:
6.324555320336759

You might also like