0% found this document useful (0 votes)
49 views64 pages

MC4103 Python Programming - Unit-I

MC4103 PYTHON PROGRAMMING UNIT-I

Uploaded by

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

MC4103 Python Programming - Unit-I

MC4103 PYTHON PROGRAMMING UNIT-I

Uploaded by

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

MC4103 PYTHON PROGRAMMING

UNIT I BASICS OF PYTHON 9

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 a general purpose interpreted, interactive, object-oriented and high-level programming


language. Python was created by Guido van Rossum in the late eighties and early nineties. Like
Perl, Python source code is now available under the GNU General Public License (GPL).Python
was designed to be highly readable which uses English keywords frequently where as other
languages use punctuation and it has fewer syntactical constructions than other languages.

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

• Python is Object-Oriented: This means that Python supports Object-Oriented style or


technique of programming that encapsulates code within objects.

• Python is Beginner's Language: Python is a great language for the beginner


programmers and supports the development of a wide range of applications, from simple text
processing to WWW browsers to games.

Syntax and Style:

Statements and Syntax

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.

#!/usr/bin/python # First comment

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

You can comment multiple lines as follows:

# This is a comment.

# This is a comment, too. # This is a comment, too. # I said that already.

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

if (weather_is_hot == 1) and \ (shark_warnings == 0) :


send_goto_beach_mesg_to_pager()

Multiple Statement Groups as Suites ( : )

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.

Multiple Statements on a Single Line ( ; )

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:

import sys; x = 'foo'; sys.stdout.write(x + '\n')

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

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

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 a legal expression:

>>> print 1,000,000


100

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:

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159

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:

The print statement also works with variables.

>>> print message


What's up, Doc?
>>> print n
17
>>> print pi
3.14159

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'>

The type of a variable is the type of the value it refers to.


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

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade'


SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = 'Computer Science 101'
SyntaxError: invalid syntax

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.

Python has twenty-nine keywords:

and def exec if not return


assert del finally import or try
break elif for in pass while
class else from is print yield
continue except global lambda raise
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.

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.

For example, the script

print 1
x = 2
print x

produces the output

1
2

Again, the assignment statement produces no output.

2.5 Evaluating expressions

An expression is a combination of values, variables, and operators. If you type an expression on


the command line, the interpreter evaluates it and displays the result:

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

>>> message = 'Hello, World!'


>>> message
'Hello, World!'
>>> print message
Hello, World!

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:

20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

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.

A possible solution to this problem is to calculate a percentage rather than a fraction:

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

2.7 Order of operations

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.

2.8 Operations on strings

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

message-1 'Hello'/123 message*'Hello' '15'+2


Interestingly, the + operator does work with strings, although it does not do exactly what you
might expect. For strings, the + operator represents concatenation, which means joining the two
operands by linking them end-to-end. For example:

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:

print 'Number of minutes since midnight: ', hour*60+minute

You can also put arbitrary expressions on the right-hand side of an assignment statement:

percentage = (minute * 100) / 60

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:

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end of a
line:

percentage = (minute * 100) / 60 # caution: integer division


Everything from the # to the end of the line is ignored it has no effect on the program. The
message is intended for the programmer or for future programmers who might use this code. In
this case, it reminds the reader about the ever-surprising behavior of integer division.

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.

percentage = (minute * 100) // 60

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

Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Let us have a look on all operators one by one.

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

Adds values on either side of the


+ Addition a + b = 30
operator.

Subtracts right hand operand from left


- Subtraction a – b = -10
hand operand.
* Multiplies values on either side of the
a * b = 200
Multiplication operator

Divides left hand operand by right hand


/ Division b/a=2
operand

Divides left hand operand by right hand


% Modulus b%a=0
operand and returns remainder

Performs exponential (power)


** Exponent a**b =10 to the power 20
calculation on operators

Floor Division - The division of


operands where the result is the quotient
in which the digits after the decimal
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -
// point are removed. But if one of the
11.0//3 = -4.0
operands is negative, the result is
floored, i.e., rounded away from zero
(towards negative infinity) −

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them.
They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

If the values of two operands are equal,


== (a == b) is not true.
then the condition becomes true.

!= If values of two operands are not equal, (a != b) is true.


then condition becomes true.

If values of two operands are not equal, (a <> b) is true. This is similar to !=
<>
then condition becomes true. operator.

If the value of left operand is greater than


> the value of right operand, then condition (a > b) is not true.
becomes true.

If the value of left operand is less than the


< value of right operand, then condition (a < b) is true.
becomes true.

If the value of left operand is greater than


>= or equal to the value of right operand, then (a >= b) is not true.
condition becomes true.

If the value of left operand is less than or


<= equal to the value of right operand, then (a <= b) is true.
condition becomes true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

Assigns values from right side operands to


= c = a + b assigns value of a + b into c
left side operand

+= Add It adds right operand to the left operand


c += a is equivalent to c = c + a
AND and assign the result to left operand

-= It subtracts right operand from the left c -= a is equivalent to c = c - a


Subtract operand and assign the result to left
AND operand

*= It multiplies right operand with the left


Multiply operand and assign the result to left c *= a is equivalent to c = c * a
AND operand

It divides left operand with the right


/= Divide
operand and assign the result to left c /= a is equivalent to c = c / a
AND
operand

%=
It takes modulus using two operands and
Modulus c %= a is equivalent to c = c % a
assign the result to left operand
AND

**= Performs exponential (power) calculation


Exponent on operators and assign value to the left c **= a is equivalent to c = c ** a
AND operand

//= Floor It performs floor division on operators and


c //= a is equivalent to c = c // a
Division assign value to the left operand
Python Bitwise Operators

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example

& Binary Operator copies a bit to the result if it


(a & b) (means 0000 1100)
AND exists in both operands

It copies a bit if it exists in either


| Binary OR (a | b) = 61 (means 0011 1101)
operand.

^ Binary It copies the bit if it is set in one


(a ^ b) = 49 (means 0011 0001)
XOR operand but not both.

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

The left operands value is moved left by


<< Binary
the number of bits specified by the right a << 2 = 240 (means 1111 0000)
Left Shift
operand.

The left operands value is moved right


>> Binary
by the number of bits specified by the a >> 2 = 15 (means 0000 1111)
Right Shift
right operand.

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then

Operator Description Example

and
If both the operands are true then
Logical (a and b) is true.
condition becomes true.
AND

or Logical If any of the two operands are non-zero


(a or b) is true.
OR then condition becomes true.

not
Used to reverse the logical state of its
Logical Not(a and b) is false.
operand.
NOT

Python Membership Operators

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

Evaluates to true if it finds a variable in


x in y, here in results in a 1 if x is a
in the specified sequence and false
member of sequence y.
otherwise.

Evaluates to true if it does not finds a


x not in y, here not in results in a 1 if x is
not in variable in the specified sequence and
not a member of sequence y.
false otherwise.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −

Operator Description Example

Evaluates to true if the variables on either


x is y, here is results in 1 if id(x) equals
is side of the operator point to the same
id(y).
object and false otherwise.

Evaluates to false if the variables on either


x is not y, here is not results in 1 if id(x) is
is not side of the operator point to the same
not equal to id(y).
object and true otherwise.
Python Operators Precedence

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

Sr.No. Operator & Description


**
1
Exponentiation (raise to the power)
~+-
2
Complement, unary plus and minus (method names for the last two are +@ and -@)
* / % //
3
Multiply, divide, modulo and floor division
+-
4
Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'
^|
7
Bitwise exclusive `OR' and regular `OR'
<= < > >=
8
Comparison operators
<> == !=
9
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
Comments in Python

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

This produces the following result −

Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

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

Waiting for the User

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

raw_input("\n\nPress the enter key to exit.")

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.

Multiple Statements on a Single Line

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 −

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites

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

Command Line Arguments

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

The Python Debugger (pdb)


PythonProgrammingServer Side Programming

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

python –m pdb script.py

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)

C:\python36>python -m pdb fact.py


> c:\python36\fact.py(1)<module>()
-> def fact(x):
(Pdb)
Python - Functions

A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.

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

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


I'm first call to user defined function!
Again second call to the same function

Pass by reference vs value

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

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the same object.
So, this would produce the following result −

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

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

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

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 −

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

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

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

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

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

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

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

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

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

Name: miki
Age 50
Name: miki
Age 35

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 −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of all 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

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

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

Output is:
10
Output is:
70
60
50

The Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by
using the def keyword. You can use the lambda keyword to create small anonymous functions.

 Lambda forms can take any number of arguments but return just one value in the form of
an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an
expression
 Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.
 Although it appears that 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 −

lambda [arg1 [,arg2,.....argn]]:expression

Following is the example to show how lambda form of function works −

#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −

Value of total : 30
Value of total : 40
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

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

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

Inside the function : 30


Outside the function : 30

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
Python – Conditional (Decision Making)

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

Python - if, elif, else Conditions

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

if price < 100:


print("price is less than 100")
Output

price is less than 100

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.

Example: Multiple Statements in the if Block

price = 50
quantity = 5
if price*quantity < 500:
print("price*quantity is less than 500")
print("price = ", price)
print("quantity = ", quantity)
Output

price*quantity is less than 500


price = 50
quantity = 5

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

print("quantity = ", quantity)


^
IdentationError: unexpected indent

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.

Example: Out of Block Statements

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.

The following example demonstrates multiple if conditions.

Example: Multiple if Conditions

price = 100
if price > 100:
print("price is greater than 100")

if price == 100:
print("price is 100")

if price < 100:


print("price is less than 100")
Output

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.

Example: else Condition

price = 50

if price >= 100:


print("price is greater than 100")
else:
print("price is less than 100")
Output

price is less than 100

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]

The elif block is executed if the specified condition evaluates to True.

Example: if-elif Conditions

price = 100

if price > 100:


print("price is greater than 100")
elif price == 100:
print("price is 100")
elif price < 100:
print("price is less than 100")
Output

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.

The following example demonstrates if, elif, and else conditions.

Example: if-elif-else Conditions

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

price is less than 100

All the if, elif, and else conditions must start from the same indentation level, otherwise it will
raise the IndentationError.

Example: Invalid Indentation

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

elif price == 100:


^
IdentationError: unindent does not match any outer indentation level

Nested if, elif, else Conditions

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

if amount > 100:


if amount > 500:
print("Amount is greater than 500")
else:
if amount < 500 and amount > 400:
print("Amount is")
elif amount < 500 and amount > 300:
print("Amount is between 300 and 500")
else:
print("Amount is between 200 and 500")
elif amount == 100:
print("Amount is 100")
else:
print("Amount is less than 100")
Output

Amount is between 200 and 500


Python - Iterations (Loops)

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.

Sr.No. Loop Type & Description


1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
for loop

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

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.

Let us go through the loop control statements briefly

Sr.No. Control Statement & Description


break statement

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

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.

The Infinite Loop

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

print "Good bye!"


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

Enter a number :20


You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt

Above example goes in an infinite loop and you need to use CTRL+C to exit the program.

Using else Statement with While Loop

Python supports to have an else statement associated with a loop statement.

 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

Single Statement Suites

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.

Here is the syntax and example of a one-line while clause −

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

Python for Loop Statements

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!

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself.
Following is a simple example −

#!/usr/bin/python

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"

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

Current fruit : banana


Current fruit : apple
Current fruit : mango
Good bye!

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.

Using else Statement with For Loop

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.

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

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'
break

When the above code is executed, it produces the 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

Python nested loops

Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.

Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

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

print "Good bye!"

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

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!

You might also like