MC4103 Python Programming - Unit-I
MC4103 Python Programming - Unit-I
Introduction to Python Programming – Python Interpreter and Interactive Mode– Variables and
Identifiers – Arithmetic Operators – Values and Types – Statements. Operators – Boolean Values
– Operator Precedence – Expression – Conditionals: If-Else Constructs – Loop
Structures/Iterative Statements – While Loop – For Loop – Break Statement-Continue statement
– Function Call and Returning Values – Parameter Passing – Local and Global Scope –
Recursive Functions
Introduction:
• Python is interpreted: This means that it is processed at runtime by the interpreter and
you do not need to compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive: This means that you can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Some rules and certain symbols are used with regard to statements in Python:
Symbol Description
Hash mark ( # ) Indicates Python comments
NEWLINE ( \n ) The standard line separator (one statement per line) Backslash ( \ )
Continues a line
Semicolon ( ; ) Joins two statements on a line Colon ( : ) Separates a header line from
its suite
Comments:
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the physical line end are part of the comment, and the Python interpreter ignores them.
print "Hello, Python!"; # second comment This will produce following result:
Hello, Python!
A comment may be on the same line after a statement or expression: name = "Madisetti" # This
is again comment
# This is a comment.
Continuation ( \ ):
In Python you normally have one instruction per line. Long instructions can span several lines
using the line-continuation character “\”. Some instructions, as triple quoted strings, list, tuple
and dictionary constructors or statements grouped by parentheses do not need a line-continuation
character. It is possible to write several statements on the same line, provided they are separated
by semi-colons.
# check conditions
Groups of individual statements making up a single code block are called "suites" in
Python.Compound or complex statements, such as if, while, def, and class, are those which
require a header line and a suite. Header lines begin the statement (with the keyword) and
terminate with a colon ( : ) and are followed by one or more lines which make up the suite.
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block. Here is a sample snip using the semicolon:
Example:
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.
Variable Assignment
Python variables do not have to be explicitly declared 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
Here 100, 1000.0 and "John" are the values assigned to counter, miles and name variables,
respectively. While running this program, this will produce following result:
Values and types
A value is one of the fundamental things like a letter or a number that a program
manipulates. The values we have seen so far are 2 (the result when we added 1 + 1), 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.
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 a legal expression:
Well, that's not what we expected at all! Python interprets 1,000,000 as a comma-separated list of
three integers, which it prints consecutively. 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.
2.2 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.
The assignment statement creates new variables and gives them values:
This example makes three assignments. The first assigns the string "What's up, Doc?" to a new
variable named message. The second gives the integer 17 to n, and the third gives the floating-
point number 3.14159 to pi.
Notice that the first statement uses double quotes to enclose the string. In general, single and
double quotes do the same thing, but if the string contains a single quote (or an apostrophe,
which is the same character), you have to use double quotes to enclose it.
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 assignment statements:
In each case the result is the value of the variable. Variables also have types; again, we can ask
the interpreter what they are.
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
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. Although it is legal to use uppercase letters, by convention we don't. If you
do, remember that case matters. Bruce and bruce are different variables.
The underscore character (_) can appear in a name. It is often used in names with multiple
words, such as my_name or price_of_tea_in_china.
76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains
an illegal character, the dollar sign. But what's wrong with class?
It turns out that class is one of the Python keywords. Keywords define the language's rules and
structure, and they cannot be used as variable names.
2.4 Statements
A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
When you type a statement on the command line, Python executes it and displays the result, if
there is one. The result of a print statement is a value. Assignment statements don't produce a
result.
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.
print 1
x = 2
print x
1
2
>>> 1 + 1
2
Although expressions contain values, variables, and operators, not every expression contains all
of these elements. A value all by itself is considered an expression, and so is a variable.
>>> 17
17
>>> x
2
Confusingly, evaluating an expression is not quite the same thing as printing a value.
When the Python interpreter displays the value of an expression, it uses the same format you
would use to enter a value. In the case of strings, that means that it includes the quotation marks.
But if you use a print statement, Python displays the contents of the string without the quotation
marks.
In a script, an expression all by itself is a legal statement, but it doesn't do anything. The script
17
3.2
'Hello, World!'
1+1
produces no output at all. How would you change the script to display the values of these four
expressions?
2.6 Operators and operands
Operators are special symbols that represent computations like addition and multiplication. The
values the operator uses are called operands.
The following are all legal Python expressions whose meaning is more or less clear:
The symbols +, -, and /, and the use of parenthesis for grouping, mean in Python what they mean
in mathematics. The asterisk (*) is the symbol for multiplication, and ** is the symbol for
exponentiation.
When a variable name appears in the place of an operand, it is replaced with its value before the
operation is performed.
Addition, subtraction, multiplication, and exponentiation all do what you expect, but you might
be surprised by division. The following operation has an unexpected result:
>>> 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 integer division.
When both of the operands are integers, the result must also be an integer, and by convention,
integer division always rounds down, even in cases like this where the next integer is very close.
>>> minute*100/60
98
Again the result is rounded down, but at least now the answer is approximately correct. Another
alternative is to use floating-point division, which we get to in Chapter 3.
When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. Python follows the same precedence rules for its mathematical operators
that mathematics does. The acronym PEMDAS is a useful way to remember the order of
operations:
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 though it doesn't change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is
3 and 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 yields 5 rather than 4, and
2/3-1 is -1, not 1 (remember that in integer division, 2/3=0).
Operators with the same precedence are evaluated from left to right. So in the expression
minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields
98. If the operations had been evaluated from right to left, the result would have been
59*1, which is 59, which is wrong.
In general, you cannot perform mathematical operations on strings, even if the strings look like
numbers. The following are illegal (assuming that message has type string):
fruit = 'banana'
bakedGood = ' nut bread'
print fruit + bakedGood
The output of this program is banana nut bread. The space before the word nut is part of the
string, and is necessary to produce the space between the concatenated strings.
The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is
'FunFunFun'. One of the operands has to be a string; the other has to be an integer.
On one hand, this interpretation of + and * makes sense by analogy with addition and
multiplication. Just as 4*3 is equivalent to 4+4+4, we expect 'Fun'*3 to be the same as
'Fun'+'Fun'+'Fun', and it is. On the other hand, there is a significant way in which string
concatenation and repetition are different from integer addition and multiplication. Can you think
of a property that addition and multiplication have that string concatenation and repetition do
not?
2.9 Composition
So far, we have looked at the elements of a program variables, expressions, and statements
in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building
blocks and compose them. For example, we know how to add numbers and we know how to
print; it turns out we can do both at the same time:
>>> print 17 + 3
20
In reality, the addition has to happen before the printing, so the actions aren't actually happening
at the same time. The point is that any expression involving numbers, strings, and variables can
be used inside a print statement. You've already seen an example of this:
You can also put arbitrary expressions on the right-hand side of an assignment statement:
This ability may not seem impressive now, but you will see other examples where composition
makes it possible to express complex computations neatly and concisely.
Warning: There are limits on where you can use certain expressions. For example, the left-hand
side of an assignment statement has to be a variable name, not an expression. So, the following
is illegal: minute+1 = hour.
2.10 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 are marked with the #
symbol:
In this case, the comment appears on a line by itself. You can also put comments at the end of a
line:
This sort of comment is less necessary if you use the integer division operation, //. It has the
same effect as the division operator * Note, but it signals that the effect is deliberate.
The integer division operator is like a comment that says, "I know this is integer division, and I
like it that way!"
Python - Basic Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
These operators compare the values on either sides of them and decide the relation among them.
They are also called Relational operators.
If values of two operands are not equal, (a <> b) is true. This is similar to !=
<>
then condition becomes true. operator.
%=
It takes modulus using two operands and
Modulus c %= a is equivalent to c = c % a
assign the result to left operand
AND
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following
table lists out the bitwise operators supported by Python language with an example each in those,
we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
~ Binary It is unary and has the effect of 'flipping' (~a ) = -61 (means 1100 0011 in 2's
Ones complement form due to a signed binary
Complement bits. number.
There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then
and
If both the operands are true then
Logical (a and b) is true.
condition becomes true.
AND
not
Used to reverse the logical state of its
Logical Not(a and b) is false.
operand.
NOT
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
Operator Description Example
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −
The following table lists all operators from highest precedence to lowest.
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the end of the physical line are part of the comment and the Python interpreter ignores
them.
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
Hello, Python!
You can type a comment on the same line after a statement or expression −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:
'''
This is a multiline
comment.
'''
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank line and
Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.
The following line of the program displays the prompt, the statement saying “Press the enter key
to exit”, and waits for the user to take action −
#!/usr/bin/python
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user
presses the key, the program ends. This is a nice trick to keep a console window open until the
user is done with an application.
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block. Here is a sample snip using the semicolon −
A group of individual statements, which make a single code block are called suites in Python.
Compound or complex statements, such as if, while, def, and class require a header line and a
suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are
followed by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
Many programs can be run to provide you with some basic information about how they should
be run. Python enables you to do this with -h −
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
You can also program your script in such a way that it should accept various options. Command
Line Arguments is an advanced topic and should be studied a bit later once you have gone
through rest of the Python concepts.
DEBUGGING
In software development jargon, 'debugging' term is popularly used to process of locating and
rectifying errors in a program. Python's standard library contains pdb module which is a set of
utilities for debugging of Python programs.
The debugging functionality is defined in a Pdb class. The module internally makes used of bdb
and cmd modules.
The pdb module has a very convenient command line interface. It is imported at the time of
execution of Python script by using –m switch
In order to find more about how the debugger works, let us first write a Python module (fact.py)
as follows −
def fact(x):
f=1
for i in range(1,x+1):
print (i)
f=f*i
return f
if __name__=="__main__":
print ("factorial of 3=",fact(3))
Start debugging this module from command line. In this case the execution halts at first line in
the code by showing arrow (->) to its left, and producing debugger prompt (Pdb)
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
Example
The following function takes a string as input parameter and prints it on standard screen.
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
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the calling
function. For example −
#!/usr/bin/python
Here, we are maintaining reference of the passed object and appending values in the same object.
So, this would produce the following result −
There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.
#!/usr/bin/python
The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce the
following result −
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/python
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;
My string
The following example gives more clear picture. Note that the order of parameters does not
matter.
#!/usr/bin/python
Name: miki
Age 50
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/python
Name: miki
Age 50
Name: miki
Age 35
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 this −
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call. Following is a simple example −
#!/usr/bin/python
Output is:
10
Output is:
70
60
50
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 lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
#!/usr/bin/python
Value of total : 30
Value of total : 40
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 above examples are not returning any value. You can return a value from a function as
follows −
#!/usr/bin/python
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
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
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 the
programming 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.
Python programming language provides following types of decision making statements. Click
the following links to check their detail.
Sr.No. Statement & Description
if statements
1
An if statement consists of a boolean expression followed by one or more statements.
if...else statements
2
An if statement can be followed by an optional else statement, which executes when
the boolean expression is FALSE.
nested if statements
3
You can use one if or else if statement inside another if or else if statement(s).
By default, statements in the script are executed sequentially from the first to the last. If the
processing logic requires so, the sequential flow can be altered in two ways:
Python uses the if keyword to implement decision control. Python's syntax for executing a block
conditionally is as below:
Syntax:
if [boolean expression]:
statement1
statement2
...
statementN
Any Boolean expression evaluating to True or False appears after the if keyword. Use the :
symbol and press Enter after the expression to start a block with an increased indent. One or
more statements written with the same level of indent will be executed if the Boolean expression
evaluates to True.
To end the block, decrease the indentation. Subsequent statements after the block will be
executed out of the if condition. The following example demonstrates the if condition.
Example: if Condition
price = 50
In the above example, the expression price < 100 evaluates to True, so it will execute the block.
The if block starts from the new line after : and all the statements under the if condition starts
with an increased indentation, either space or tab. Above, the if block contains only one
statement. The following example has multiple statements in the if condition.
price = 50
quantity = 5
if price*quantity < 500:
print("price*quantity is less than 500")
print("price = ", price)
print("quantity = ", quantity)
Output
Above, the if condition contains multiple statements with the same indentation. If all the
statements are not in the same indentation, either space or a tab then it will raise an
IdentationError.
Example: Invalid Indentation in the Block
price = 50
quantity = 5
if price*quantity < 500:
print("price is less than 500")
print("price = ", price)
print("quantity = ", quantity)
Output
The statements with the same indentation level as if condition will not consider in the if block.
They will consider out of the if condition.
price = 50
quantity = 5
if price*quantity < 100:
print("price is less than 500")
print("price = ", price)
print("quantity = ", quantity)
print("No if block executed.")
Output
No if block executed.
price = 100
if price > 100:
print("price is greater than 100")
if price == 100:
print("price is 100")
price is 100
Notice that each if block contains a statement in a different indentation, and that's valid because
they are different from each other.
Note
It is recommended to use 4 spaces or a tab as the default indentation level for more readability.
ADVERTISEMENT
else Condition
Along with the if statement, the else condition can be optionally used to define an alternate block
of statements to be executed if the boolean expression in the if condition evaluates to False.
Syntax:
if [boolean expression]:
statement1
statement2
...
statementN
else:
statement1
statement2
...
statementN
As mentioned before, the indented block starts after the : symbol, after the boolean expression. It
will get executed when the condition is True. We have another block that should be executed
when the if condition is False. First, complete the if block by a backspace and write else, put add
the : symbol in front of the new block to begin it, and add the required statements in the block.
price = 50
In the above example, the if condition price >= 100 is False, so the else block will be executed.
The else block can also contain multiple statements with the same indentation; otherwise, it will
raise the IndentationError.
Note that you cannot have multiple else blocks, and it must be the last block.
elif Condition
Use the elif condition is used to include multiple conditional expressions after the if condition or
between the if and else conditions.
Syntax:
if [boolean expression]:
[statements]
elif [boolean expresion]:
[statements]
elif [boolean expresion]:
[statements]
else:
[statements]
price = 100
price is 100
In the above example, the elif conditions are applied after the if condition. Python will evalute
the if condition and if it evaluates to False then it will evalute the elif blocks and execute the elif
block whose expression evaluates to True. If multiple elif conditions become True, then the first
elif block will be executed.
price = 50
if price > 100:
print("price is greater than 100")
elif price == 100:
print("price is 100")
else price < 100:
print("price is less than 100")
Output
All the if, elif, and else conditions must start from the same indentation level, otherwise it will
raise the IndentationError.
price = 50
Python supports nested if, elif, and else condition. The inner condition must be with increased
indentation than the outer condition, and all the statements under the one block should be with
the same indentation.
Example: Nested if-elif-else Conditions
price = 50
quantity = 5
amount = price*quantity
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 −
2
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
nested loops
3
You can use one or more loop inside any another while, for or do..while loop.
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.
1
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
pass statement
3
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 while Loop Statements
A while loop statement in Python programming language repeatedly executes a target statement
as long as a given condition is true.
Syntax
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
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.
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when
using while loops because of the possibility that this condition never resolves to a FALSE value.
This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.
#!/usr/bin/python
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
Above example goes in an infinite loop and you need to use CTRL+C to exit the program.
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.
#!/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
Similar to the if statement syntax, if your while clause consists only of a single statement, it may
be placed on the same line as the while header.
#!/usr/bin/python
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"
It is better not try above example because it goes into infinite loop and you need to press
CTRL+C keys to exit.
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
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!
An alternative way of iterating through each item is by index offset into the sequence itself.
Following is a simple example −
#!/usr/bin/python
Here, we took the assistance of the len() built-in function, which provides the total number of
elements in the tuple as well as the range() built-in function to give us the actual sequence to
iterate over.
If the else statement is used with a for loop, the else statement is executed when the loop
has exhausted iterating the list.
The following example illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
Live Demo
#!/usr/bin/python
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
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax
The syntax for a nested while loop statement in Python programming language is as follows −
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#!/usr/bin/python
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!