Chapter 1
Python is a high-level, interpreted, interactive
and object-oriented scripting language. Python is designed to be highly
readable. It uses English keywords frequently where as other languages use
punctuation, and 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.
·
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 beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW browsers to
games.
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 Features
Python's features include:
·
Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the language
quickly.
·
Easy-to-read: Python code is more clearly defined and visible
to the eyes.
·
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
·
A
broad standard library: Python's bulk of the
library is very portable and 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.
·
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, 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 type checking.
·
IT supports automatic
garbage collection.
Getting Python
The most up-to-date and current source code, binaries,
documentation, news, etc., is available on the official website of Python https://www.python.org/
You can download Python documentation from https://www.python.org/doc/.
The documentation is available in HTML, PDF, and PostScript formats.
Installing Python
Python distribution is available for a wide variety of platforms.
You need to download only the binary code applicable for your platform and
install Python.
If the binary code for your platform is not available, you need a
C compiler to compile the source code manually. Compiling the source code
offers more flexibility in terms of choice of features that you require in your
installation.
Here is a quick overview of installing Python on various platforms
−
Unix and Linux Installation
Here are the simple steps to install Python on Unix/Linux machine.
·
Open a Web browser and go to https://www.python.org/downloads/.
·
Follow the link to download zipped source code available for
Unix/Linux.
·
Download and extract files.
·
Editing the Modules/Setup file if you want to customize some
options.
·
run ./configure script
·
make
·
make install
This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.
Windows Installation
Here are the steps to install Python on Windows machine.
·
Open a Web browser and go to https://www.python.org/downloads/.
·
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need
to install.
·
To use this installer python-XYZ.msi,
the Windows system must support Microsoft Installer 2.0. Save the installer
file to your local machine and then run it to find out if your machine supports
MSI.
·
Run the downloaded file. This brings up the Python install wizard,
which is really easy to use. Just accept the default settings, wait until the
install is finished, and you are done.
irst Python Program
Let us execute programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a
parameter brings up the following prompt −
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter:
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to
use print statement with parenthesis as in print
("Hello, Python!");. However in Python version 2.4.3, this
produces the following result:
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution
of the script and continues until the script is finished. When the script is
finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files
have extension .py. Type
the following source code in a test.py file:
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable.
Now, try to run this program as follows −
$ python test.py
This produces the following result:
Hello, Python!
Let us try another way to execute a Python script. Here is the
modified test.py file −
#!/usr/bin/python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin
directory. Now, try to run this program as follows −
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result −
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable,
function, class, module or other object. An identifier starts with a letter A
to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and %
within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in
Python.
Here are naming conventions for Python identifiers −
·
Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
·
Starting an identifier with a single leading underscore indicates
that the identifier is private.
·
Starting an identifier with two leading underscores indicates a
strongly private identifier.
·
If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved
words and you cannot use them as constant or variable or any other identifier
names. All the Python keywords contain lowercase letters only.
|
and
|
exec
|
not
|
|
assert
|
finally
|
or
|
|
break
|
for
|
pass
|
|
class
|
from
|
print
|
|
continue
|
global
|
raise
|
|
def
|
if
|
return
|
|
del
|
import
|
try
|
|
elif
|
in
|
while
|
|
else
|
is
|
with
|
|
except
|
lambda
|
yield
|
Python
Variable Types
Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
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 variables, you can store integers, decimals
or characters in these variables.
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. For example −
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This produces
the following result −
100
1000.0
John
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 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
variables a and b respectively, and one string object with the value
"john" is assigned to the variable c.
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 Numbers
Number data types store numeric values. Number objects are created
when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the
del statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the
del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
·
int (signed integers)
·
long (long integers, they can also be represented in octal and
hexadecimal)
·
float (floating point real values)
·
complex (complex numbers)
Examples
Here are some examples of numbers −
|
int
|
long
|
float
|
complex
|
|
10
|
51924361L
|
0.0
|
3.14j
|
|
100
|
-0x19323L
|
15.20
|
45.j
|
|
-786
|
0122L
|
-21.9
|
9.322e-36j
|
|
080
|
0xDEFABCECBDAECBFBAEl
|
32.3+e18
|
.876j
|
|
-0490
|
535633629843L
|
-90.
|
-.6545+0J
|
|
-0x260
|
-052318172735L
|
-32.54e100
|
3e+26J
|
|
0x69
|
-4721885298529L
|
70.2-E12
|
4.53e-7j
|
·
Python allows you to use a lowercase l with long, but it is
recommended that you use only an uppercase L to avoid confusion with the number
1. Python displays long integers with an uppercase L.
·
A complex number consists of an ordered pair of real
floating-point numbers denoted by x + yj, where x and y are the real numbers
and j is the imaginary unit.
Python Strings
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows for either pairs 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 at the end.
The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator. For example −
#!/usr/bin/python
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Variable Expressions and Statements
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.
The print statement also works for integers.
>>>
print 4
4
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:
>>>
print 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,
which it prints with spaces between.
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
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 π 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). This diagram shows the result of the
previous example:

To display the value of
a variable, you can use a print statement:
>>>
print n
17
>>>
print pi
3.14159265359
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'>
Exercise 1 If you type an integer with
a leading zero, you might get a confusing error:
>>>
zipcode = 02492
^
SyntaxError:
invalid token
Other numbers seem to
work, but the results are bizarre:
>>>
zipcode = 02132
>>>
print zipcode
1114
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 (you’ll see why later).
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.
>>>
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 has 31 keywords1:
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
You might want to keep this list handy. If
the interpreter complains about one of your variable names and you don’t know
why, see if it is on this list.
Statements
A statement is a unit of
code that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
When you type a statement in interactive mode,
the interpreter executes it and displays the result, if there is one.
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.
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.
>>> 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 division2.
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.
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
Expressions
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 (assuming that the
variable x has been assigned a
value):
x
x + 17
If you type an
expression in interactive mode, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
But in a script, an
expression all by itself doesn’t do anything! This is a common source of
confusion for beginners.
Exercise 2 Type the following
statements in the Python interpreter to see what they do:
5
x = 5
x + 1
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:
P : Parentheses
E : Exponentiation
M: Multiplication
D: Division
A: Addition
S: Subtraction
- Parentheses have the highest precedence and can be used
to force an expression to evaluate in the 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 2 π, you can use parentheses or write degrees / 2 / pi.
Variable Expressions and Statements
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.
>>>
print 4
4
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
'float'>
What about values
like '17' and '3.2'? They look like numbers, but they are in
quotation marks like strings.
<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:
>>>
print 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,
which it prints with spaces between.
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.
PYTHON
OBJECTS: MUTABLE VS. IMMUTABLE
Not all python objects
are created equal. Some objects are mutable, meaning they can be altered, while
others are immutable; pretty much the opposite of mutable
. So what does this mean for
you when writing code in python? This post will talk about
(a) the mutability of common data types and
(b) instances where mutability matters.
MUTABILITY
OF COMMON TYPES
The way one like to
remember which types are mutable and which are not is that containers and user-defined types are generally
mutable while everything else is immutable. Then one can take careof the exceptions like tuple which is an immutable container and frozen
set which is an
immutable version of set (which makes sense, so you just have
to remember tuple).
The following are immutable objects:
- Numeric types:
int, float, complex
- string
- tuple
- frozen set
- bytes
T
he following objects are mutable:
- list
- dict
- set
- byte array
Taking input( using raw_input() and input())
raw_input() function reads a line from
input (i.e. the user) and returns a string by stripping a trailing newline.
The syntax is as
follows for Python v2.x:
|
mydata = raw_input('Prompt :')
print (mydata)
|
The syntax is as
follows for Python v3.x as raw_input() was renamed to input() :
|
mydata = input('Prompt :')
print (mydata)
|
Examples In this example, read the user name using raw_input() and
display back on the screen using print():
|
#!/usr/bin/python
name=raw_input('Enter your name : ')
print ("Hi %s, Let us be friends!" % name);
|
Sample output
Enter your name : Shilpa
Hi shilpa, Let us be friends!
!/usr/bin/python
# Version 1
## Show menu ##
print (30 * '-')
print (" M A I N - M E N U")
print (30 * '-')
print ("1. Backup")
print ("2. User management")
print ("3. Reboot the server")
print (30 * '-')
## Get input ###
choice = raw_input('Enter your choice [1-3] : ')
### Convert string to int type ##
choice = int(choice)
### Take action as per selected menu-option ###
if choice == 1:
print ("Starting backup...")
elif choice == 2:
print ("Starting user management...")
elif choice == 3:
print ("Rebooting the server...")
else: ## default ##
print ("Invalid number. Try again...")
Displying output with Print
print('We are the
{} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say
"Ni!"
The brackets and characters within
them (called format fields) are replaced with the objects passed into the str.format() method.
A number in the brackets can be used to refer to the position of the object
passed into the str.format() method.
>>>
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
If keyword arguments are used in
the str.format() method,
their values are referred to by using the name of the argument.
>>>
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely
horrible'))
This spam is absolutely
horrible.
Positional and keyword arguments can
be arbitrarily combined:
>>> print('The story
of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred,
and Georg.
Comments in Python
Python has two ways to
annotate Python code.
One is by using comments to
indicate what some part of the code does.
Single-line comments begin
with the hash character ("#") and are terminated by
the end of line.
Python is ignoring all text
that comes after the # to the end of the line,
they are not part of the
command.
Comments spanning more than
one line are achieved by inserting a multi-line string
(with """ as
the delimiter one each end) that is not used in assignment or
otherwise evaluated, but sits
in between other statements.
They are meant as
documentation for anyone reading the code.
Example
Let's show this by using an
example
#this is a comment in Python
print "Hello World"
#This is also a comment in Python
""" This is an
example of a multiline
comment that spans multiple
lines
"""
'''
This is a multiline
comment.
'''
print 2
Python: Volume of a Sphere
A sphere is a
three-dimensional solid with no face, no edge, no base and no vertex. It is a
round body with all points on its surface equidistant from the center. The
volume of a sphere is measured in cubic units.
The volume of the sphere
is : V = 4/3 × Ï€ × r3 = Ï€ × d3/6.
pi = 3.14
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the
sphere is: ',V)
Chapter
2
Conditional and looping
Construct
If-else statement and
nested if –else while, for, use of range function in for ,Nested loops
Decision making is anticipation of conditions
occurring while execution of the program and specifying actions taken according
to the conditions.
Decision structures evaluate multiple
expressions which produce TRUE or FALSE as outcome. You need to determine which
action to take and which statements to execute if outcome is TRUE or FALSE
otherwise.
Following is the general form of a typical
decision making structure found in most of ng languages

Python programming language assumes any non-zero and non-null values
as TRUE, and if it is either zero or null, then it
is assumed as FALSE value.
In general, statements are executed
sequentially: The first statement in a function is executed first, followed by
the second, and so on. There may be a situation when you need to execute a
block of code several number of times.
Programming languages provide various control
structures that allow for more complicated execution paths.
A loop statement allows us to execute a
statement or group of statements multiple times. The following diagram
illustrates a loop statement −
Python programming language provides following
types of loops to handle looping requirements.
|
Loop Type
|
Description
|
|
Repeats a statement
or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
|
|
|
Executes a sequence
of statements multiple times and abbreviates the code that manages the loop
variable.
|
|
|
You can use one or
more loop inside any another while, for or do..while loop.
|
Loop Control Statements
Loop control statements change execution from
its normal sequence. When execution leaves a scope, all automatic objects that
were created in that scope are destroyed.
Python supports the following control statements.
Click the following links to check their detail.
|
Control Statement
|
Description
|
|
Terminates the loop
statement and transfers execution to the statement immediately following the
loop.
|
|
|
Causes the loop to
skip the remainder of its body and immediately retest its condition prior to
reiterating.
|
|
|
The pass statement
in Python is used when a statement is required syntactically but you do not
want any command or code to execute.
|
Python programming language provides following
types of decision making statements. Click the following links to check their
detail.
|
Statement
|
Description
|
|
An if statement consists of a Boolean expression followed by
one or more statements.
|
|
|
An if statement can be followed by an optional else statement, which executes when the Boolean expression
is FALSE.
|
|
|
You can use one if or else
if statement inside
another if or else if statement(s).
|
Let us go through each decision making briefly −
Single Statement Suites
If the suite of an if clause
consists only of a single line, it may go on the same line as the header
statement.
Here is an example of a one-line if clause
−
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
When the above code is executed, it produces the
following result −
Value
of expression is 100
Good
bye!
# If the number is
positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive
number.")
print("This is always
printed.")
num = -1
if num > 0:
print(num, "is a positive
number.")
print("This is also
always printed.")
It
is frequently the case that you want one thing to happen when a condition it
true, and something
else to happen
when it is false. For that we have the if else statement.
if food == 'spam':
print('Ummmm, my favorite!')
else:
print("No, I won't have it. I want spam!")
Here,
the first print statement will execute if food is equal to 'spam', and the print statement indented under the elseclause will get
executed when it is not.
Flowchart
of a if else statement

The
syntax for an if else statement looks like this:
if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Each
statement inside the if block of an if else statement is executed in order if the boolean
expression evaluates to True. The entire block of statements is skipped
if the boolean expression evaluates to False, and instead all the statements under the else clause are executed.
There
is no limit on the number of statements that can appear under the two clauses
of an if else statement, but there has to be at least one
statement in each block. Occasionally, it is useful to have a section with no
statements (usually as a place keeper, or scaffolding, for code you haven’t
written yet). In that case, you can use the pass statement, which does nothing except act as a
placeholder.
if True: # This is always true
pass # so this is always executed, but it does nothing
else:
pass
example:1
temperature = float(input('What is the temperature? '))
if temperature > 70:
print('Wear shorts.')
else:
print('Wear long pants.')
print('Get some exercise outside.')
A final alternative for if statements: if-elif-.... with no else. This would mean changing
the syntax forif-elif-else above so the final else: and the block after it
would be omitted. It is similar to the basic ifstatement without an else, in that it is possible for no indented block to be executed. This
happens if none of the conditions in the tests are
true.
With an else included, exactly one of the indented blocks is
executed. Without an else, at most one of the indented blocks is
executed.
if weight > 120:
print('Sorry, we can not take a suitcase that heavy.')
elif weight > 50:
print('There is a $25 charge for luggage that heavy.')
Chained
conditionals
Sometimes there are more than two possibilities and we
need more than two branches. One way to express a computation like that is a chained conditional:
if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C
Flowchart of this chained conditional

elif is
an abbreviation of else if. Again, exactly one branch will be executed.
There is no limit of the number of elifstatements
but only a single (and optional) final else statement
is allowed and it must be the last branch in the statement:
if choice == 'a':
print("You
chose 'a'.")
elif choice == 'b':
print("You
chose 'b'.")
elif choice == 'c':
print("You
chose 'c'.")
else:
print("Invalid
choice.")
Each
condition is checked in order. If the first is false, the next is checked, and
so on. If one of them is true, the corresponding branch executes, and the
statement ends. Even if more than one condition is true, only the first true
branch executes.
create a program with python that calculate the cost for shipping.
total = raw_input('What is the total amount for your online shopping?')
country = raw_input('Shipping within the US or Canada?')
if country == "US":
if total <= "50":
print "Shipping Costs $6.00"
elif total <= "100":
print "Shipping Costs $9.00"
elif total <= "150":
print "Shipping Costs $12.00"
else:
print "FREE"
if country == "Canada":
if total <= "50":
print "Shipping Costs $8.00"
elif total <= "100":
print "Shipping Costs $12.00"
elif total <= "150":
print "Shipping Costs $15.00"
else:
print "FREE"
while loop
A while loop statement in Python programming
language repeatedly executes a target statement as long as a given condition is
true.
Syntax
The syntax of a while loop in Python programming language is
−
while expression:
statement(s)
Here, statement(s) may be a single statement or a block
of statements. The condition may be any expression, and true is any
non-zero value. The loop iterates while the condition is true.
When the condition becomes
false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of
character spaces after a programming construct are considered to be part of a
single block of code. Python uses indentation as its method of grouping
statements.
Flow Diagram

Here, key point of the while loop is that the loop might not ever
run. When the condition is tested and the result is false, the loop body will
be skipped and the first statement after the while loop will be executed.
Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
When the above code is executed, it produces the following result
−
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements,
is executed repeatedly until count is no longer less than 9. With each
iteration, the current value of the index count is displayed and then increased
by 1.
Using else Statement
with while Loops
Python supports to have an else statement
associated with a loop statement.
·
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the
list.
·
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
The following example illustrates the
combination of an else statement with a while statement that prints a number as
long as it is less than 5, otherwise else statement gets executed.p>
#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less
than 5"
When the above code is executed, it produces the
following result −
0
is less than 5
1
is less than 5
2
is less than 5
3
is less than 5
4
is less than 5
5
is not less than 5
For loop
It has the ability to iterate over the items of any sequence, such
as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first.
Then, the first item in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned to iterating_var,
and the statement(s) block is executed until the entire sequence is exhausted.
Flow Diagram

Example
#!/usr/bin/python
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
When the above code is executed, it produces the following result –
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
The range() function
The
range() function has two sets of
parameters, as follows:range(stop)stop: Number of integers (whole numbers) to generate, starting from zero. eg.range(3) == [0, 1, 2].
range([start], stop[, step])start: Starting number of the sequence.stop: Generate numbers up to, but not including this number.step: Difference between each number in the sequence.
Note that:
- All parameters must be
integers.
- All parameters can be
positive or negative.
range()(and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list ismylist[0]. Therefore the last integer generated byrange()is up to, but not including,stop. For examplerange(0, 5)generates integers from 0 up to, but not including, 5.
Python's range()
Function Examples
for i in range(5):
... print(i)
...
0
1
2
3
4
>>> # Two parameters
>>> for i in range(3, 6):
... print(i)
...
3
4
5
>>> # Three parameters
>>> for i in range(4, 10, 2):
... print(i)
...
4
6
8
>>> # Going backwards
>>> for i in range(0, -10, -2):
... print(i)
...
0
-2
-4
-6
-8
Break,
continue, pass statement in python:
You
might face a situation in which you need to exit a loop completely when an
external condition is triggered or there may also be a situation when you want
to skip a part of the loop and start next execution.
Python provides break and continue statements to handle such situations
and to have good control on your loop.
This tutorial will discuss the break,
continue and pass statements available in Python.
The break Statement:
The break statement in Python terminates the
current loop and resumes execution at the next statement, just like the
traditional break found in C.
The most common use for break is when some external
condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
Example:
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
This will produce the
following result:
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
The continue Statement:
The continue statement in Python returns the
control to the beginning of the while loop. The continue statement rejects all the remaining
statements in the current iteration of the loop and moves the control back to
the top of the loop.
The continue statement can be used in both while and for loops.
Example:
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
This will produce following
result:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Good bye!
The else Statement Used with Loops
Python supports to have an else statement associated with a loop
statements.
·
If the else statement is used with a for loop, the else statement is executed when the loop
has exhausted iterating the list.
·
If the else statement
is used with a while loop, the else statement
is executed when the condition becomes false.
·
Example:
The following example
illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
#!/usr/bin/python
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
This will produce following
result:
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
Similar way you can use else statement with while loop.
The pass Statement:
The pass statement in Python is used when a
statement is required syntactically but you do not want any command or code to
execute.
The pass statement is a null operation; nothing happens when it
executes. The pass is also useful in places where your
code will eventually go, but has not been written yet
Example:
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
This will produce following
result:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
The preceding code does not execute any statement or
code if the value of letter is 'h'. The pass statement is helpful when you have
created a code block but it is no longer required.
You
can then remove the statements inside the block but let the block remain with a
pass statement so that it doesn't interfere with other parts of the code.
Use of compound
expression in conditional constructs Functions:
Compound statements
contain (groups of) other statements; they affect or control the execution of
those other statements in some way. In general, compound statements span
multiple lines, although in simple incarnations a whole compound statement may
be contained in one line.
The if, while and for statements implement traditional
control flow constructs. try specifies exception handlers and/or
cleanup code for a group of statements. Function and class definitions are also
syntactically compound statements.
Compound statements
consist of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’
The clause headers of a particular compound statement are all at the same
indentation level. Each clause header begins with a uniquely identifying
keyword and ends with a colon. A suite is a group of statements controlled by a
clause. A suite can be one or more semicolon-separated simple statements on the
same line as the header, following the header’s colon, or it can be one or more
indented statements on subsequent lines. Only the latter form of suite can
contain nested compound statements; the following is illegal, mostly because it
wouldn’t be clear to which if clause a following else clause would belong:
if test1: if test2: print x
Also note that the
semicolon binds tighter than the colon in this context, so that in the
following example, either all or none of the print statements are executed:
if x < y < z: print x; print y; print z
The while statement
is used for repeated execution as long as an expression is true:
while_stmt
::= "while" expression ":" suite
["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes
the first suite; if the expression is false (which may be the first time it is
tested) the suite of the else clause,
if present, is executed and the loop terminates.
A break statement
executed in the first suite terminates the loop without executing the else clause’s
suite. A continue statement
executed in the first suite skips the rest of the suite and goes back to
testing the expression.
The for statement
The for statement
is used to iterate over the elements of a sequence (such as a string, tuple or
list) or other iterable object:
for_stmt
::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
The expression list is evaluated once; it should yield an iterable
object. An iterator is created for the result of the expression_list. The suite is then executed once for each item
provided by the iterator, in the order of ascending indices. Each item in turn
is assigned to the target list using the standard rules for assignments, and
then the suite is executed. When the items are exhausted (which is immediately
when the sequence is empty), the suite in the else clause,
if present, is executed, and the loop terminates.
Built-In Function, invoking built in functions:
There are a number of functions
that are always available to use. These functions are functions are known as
built-in functions in Python.

A function is a group of statements that
perform a specific task. They can either be user-defined or already built into
Python interpreter.
Functions that come built into the
Python language itself are called built-in functions and are readily available
to us.
Functions
like print(), input(), eval() etc. that we have been using, are some
examples of the built-in function. There are 68 built-in functions defined in
Python 3.5.2. They are listed below alphabetically along with a brief
description.
|
Python built-in functions
|
|
|
Built-in Function
|
Description
|
|
abs()
|
Return the absolute
value of a number.
|
|
all()
|
Return True if all elements of the iterable are
true (or if the iterable is empty).
|
|
any()
|
Return True if any element of the iterable is
true. If the iterable is empty, return False.
|
|
ascii()
|
Return a string
containing a printable representation of an object, but escape the non-ASCII
characters.
|
|
bin()
|
Convert an integer
number to a binary string.
|
|
bool()
|
Convert a value to a
Boolean.
|
|
bytearray()
|
Return a new array
of bytes.
|
|
bytes()
|
Return a new
"bytes" object.
|
|
callable()
|
Return True if the object argument appears
callable, False if not.
|
|
chr()
|
Return the string
representing a character.
|
|
classmethod()
|
Return a class
method for the function.
|
|
compile()
|
Compile the source
into a code or AST object.
|
|
complex()
|
Create a complex
number or convert a string or number to a complex number.
|
|
delattr()
|
Deletes the named
attribute of an object.
|
|
dict()
|
Create a new
dictionary.
|
|
dir()
|
Return the list of
names in the current local scope.
|
|
divmod()
|
Return a pair of
numbers consisting of quotient and remainder when using integer division.
|
|
enumerate()
|
Return an enumerate
object.
|
|
eval()
|
The argument is
parsed and evaluated as a Python expression.
|
|
exec()
|
Dynamic execution of
Python code.
|
|
filter()
|
Construct an
iterator from elements of iterable for which function returns true.
|
|
float()
|
Convert a string or
a number to floating point.
|
|
format()
|
Convert a value to a
"formatted" representation.
|
|
frozenset()
|
Return a new frozenset object.
|
|
getattr()
|
Return the value of
the named attribute of an object.
|
|
globals()
|
Return a dictionary
representing the current global symbol table.
|
|
hasattr()
|
Return True if the name is one of the object's
attributes.
|
|
hash()
|
Return the hash
value of the object.
|
|
help()
|
Invoke the built-in
help system.
|
|
hex()
|
Convert an integer
number to a hexadecimal string.
|
|
id()
|
Return the
"identity" of an object.
|
|
input()
|
Reads a line from
input, converts it to a string (stripping a trailing newline), and returns
that.
|
|
int()
|
Convert a number or
string to an integer.
|
|
isinstance()
|
Return True if the object argument is an instance.
|
|
issubclass()
|
Return True if class is a subclass.
|
|
iter()
|
Return an iterator
object.
|
|
len()
|
Return the length
(the number of items) of an object.
|
|
list()
|
Return a list.
|
|
locals()
|
Update and return a
dictionary representing the current local symbol table.
|
|
map()
|
Return an iterator
that applies function to every item of iterable, yielding the results.
|
|
max()
|
Return the largest
item in an iterable.
|
|
memoryview()
|
Return a
"memory view" object created from the given argument.
|
|
min()
|
Return the smallest
item in an iterable.
|
|
next()
|
Retrieve the next
item from the iterator.
|
|
object()
|
Return a new
featureless object.
|
|
oct()
|
Convert an integer
number to an octal string.
|
|
open()
|
Open file and return
a corresponding file object.
|
|
ord()
|
Return an integer
representing the Unicode.
|
|
pow()
|
Return power raised
to a number.
|
|
print()
|
Print objects to the
stream.
|
|
property()
|
Return a property
attribute.
|
|
range()
|
Return an iterable
sequence.
|
|
repr()
|
Return a string
containing a printable representation of an object.
|
|
reversed()
|
Return a reverse
iterator.
|
|
round()
|
Return the rounded
floating point value.
|
|
set()
|
Return a new set
object.
|
|
setattr()
|
Assigns the value to
the attribute.
|
|
slice()
|
Return a slice
object.
|
|
sorted()
|
Return a new sorted
list.
|
|
staticmethod()
|
Return a static
method for function.
|
|
str()
|
Return a str version
of object.
|
|
sum()
|
Sums the items of an
iterable from left to right and returns the total.
|
|
super()
|
Return a proxy object
that delegates method calls to a parent or sibling class.
|
|
tuple()
|
Return a tuple
|
|
type()
|
Return the type of
an object.
|
|
vars()
|
Return the __dict__ attribute for a module, class,
instance, or any other object.
|
|
zip()
|
Make an iterator
that aggregates elements from each of the iterables.
|
|
__import__()
|
This function is
invoked by the import statement.
|
Python Module:
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.Simply, a module is a file consisting of Python code. A module
can define functions, classes and variables. A module can also include runnable
code.
Example
The Python code for a module named aname normally resides in a file
named aname.py. Here's an
example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
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/python
# Import module
support
import support
# Now you can call
defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the
following result −
Hello : Zara
A module is loaded only once, regardless of the
number of times it is imported. This prevents the module execution from
happening over and over again if multiple imports occur.
The from...import Statement
Python's from statement lets
you import specific attributes from a module into the current namespace.
The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci
from the module fib, use the following statement −
from fib import fibonacci
This statement does not import the entire module
fib into the current namespace; it just introduces the item fibonacci from the
module fib into the global symbol table of the importing module.
The from...import
* Statement:
It is also possible to import all names from a
module into the current namespace by using the following import statement −
from modname import *
This provides an easy way to import all the items from a module
into the current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the
module in the following sequences −
·
The current directory.
·
If the module isn't
found, Python then searches each directory in the shell variable PYTHONPATH.
·
If all else fails,
Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as
the sys.path variable. The sys.path variable contains the
current directory, PYTHONPATH, and the installation-dependent default.
from
random import randrange
import
datetime
def
random_date(start,l):
current = start
while l >= 0:
curr = current +
datetime.timedelta(minutes=randrange(60))
yield curr
l-=1
startDate
= datetime.datetime(2013, 9, 20,13,00)
for x in
random_date(startDate,10):
print x.strftime("%d/%m/%y %H:%M")
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.
As you already know, Python gives you many built-in functions like
print(), etc. but you can also create your own functions. These functions are
called user-defined functions.
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 standard screen.
def printme( str ):
"This prints a
passed string into this function"
print str
return
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 −
#!/usr/bin/python
# 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("I'm first call
to user defined function!")
printme("Again second
call to the same function")
I'm first call to user defined function!
Again second call to the same function
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/python
# 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 more clear picture.
Note that the order of parameters does not matter.
#!/usr/bin/python
# 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
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/python
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
Fruitful
functions or function returning values
Return
values
The
built-in functions we have used, such as abs, pow, and max, have produced
results. Calling each of these functions generates a value, which we usually
assign to a variable or use as part of an expression.
biggest = max(3, 7, 2, 5)
print biggest
But
so far, none of the functions we have written has returned a value.
In
this chapter, we are going to write functions that return values, which we will
call fruitful
functions, for want of a better name. The first example is area, which returns the
area of a circle with the given radius:
def area(radius):
temp = 3.14159 * radius**2
return temp
Void functions
Void functions might display something on
the screen or have some other effect, but they don’t have a return value. If
you try to assign the result to a variable, you get a special value called None. Void functions does not return any
value.