You are on page 1of 36

[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

UNIT II DATA, EXPRESSIONS, STATEMENTS


Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and
arguments; Illustrative programs: exchange the values of two variables, circulate the values of
n variables, distance between two points.

2.1 PYTHON PROGRAMMING


2.1.1 Overview of Python
 Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language.
 It was developed by Guido Van Rossum in the early 1990s.
 Python runs on many Unix variants, on the Mac and on Windows 2000 and later.

2.1.2 Why is it called Python?


 When he began implementing Python, Guido van Rossum was also reading the
published scripts from “Monty Python's Flying Circus”, a BBC comedy series from
the 1970s.
 Van Rossum thought he needed a name that was short, unique, and slightly
mysterious, so he decided to call the language Python

2.1.3 Features of Python


Simple and Easy to Learn:
 Python is simple and Python program feels almost like reading English.
 The pseudocode nature of python is one of its greatest strengths.
Extensible:
 Part of code written in C or C++ can be used in our Python program easily.
Portable:
 Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.

Scalable:
 Python provides a better structure and support for large programs than shell scripting

PPG INSTITUTE OF TECHNOLOGY Page 1


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Interpreted
 Python Program is processed at runtime by interpreter
Interactive:
 We can interact with python interpreter by writing programs/instructions to it
Interpreter:
 Python does not need compilation to binary.
 Internally python converts the source code into an intermediate form called byte code
and then translates this into the native language of our computer and then runs it.
Object-Oriented:
 Python Supports Object-Oriented technique of programming that encapsulates code
within objects

2.1.4 What is a program?


 A program is a sequence of instructions that specifies how to perform a computation.
 The computation such as solving a system of equations or finding the roots of a
polynomial, searching and replacing text in a document or something graphical, like
processing an image or playing a video.
 Following are the basic instructions that appear in most of the programming
languages:
Input:
Get data from the keyboard, a file, or some other device
Output:
Display data on the screen or send data to a file or other device
Process:
Perform basic mathematical operations like addition and multiplication
Conditional Execution:
Check for certain conditions and executes the appropriate code.
Repetition:
Perform some action repeatedly
2.1.5 Applications for Python
 Web and Internet Development
 Scientific and Numeric
 Education
PPG INSTITUTE OF TECHNOLOGY Page 2
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Desktop GUIs
 Software Development
 Business Applications
 Game Programming
 Distributed Programming

2.2 PYTHON INTERPRETER AND INTERACTIVE MODE


2.2.1 Interactive Mode Programming:
 Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory.
 The symbol (>>>), is a prompt the interpreter uses to indicate that it is running in
interactive mode.
 Interactive mode allows us to test and see the working principle of python.
 A sample interactive session:
>>> 5
5
>>> print(5*7)
35
>>> "hello" * 4
'hellohellohellohello'

2.2.2 Script Mode Programming


 A script mode can store code in a file and it uses the interpreter to execute the
contents of file.
 Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished.
 Python script names always ends with .py extension.
 In script mode, Python doesn’t display the results automatically.
 Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file:
print(“Hello,Python!”)
 There are several ways we can start the Python interpreter and have it evaluate our
script file.
PPG INSTITUTE OF TECHNOLOGY Page 3
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

1. Explicitly from the command line.


2. Implicitly from the command line.
3. Manually from within IDLE.

2.2.3 Explicit Command Line


 The simplest way to execute a script is to provide the script file name as a parameter
to the python interpreter.
 In this style, we explicitly name both the interpreter and the input script. Here's an
example.
python example1.py

 This will provide the example1.py file to the Python interpreter for execution.

2.2.4 Implicit Command-Line Execution


 In this case, use either the GNU/Linux shell command or depend on the file
association in windows.
 For POSIX-standard operating systems (GNU/Linux, UNIX and MacOS), we make
the script file itself executable and directing the shell to locate the Python interpreter
for us.
 For Windows users, we associate our script file with the python.exe interpreter.
 Example:
#!/usr/bin/env python
print (“Hello World”)

2.2.5 Execution of Python Program

PPG INSTITUTE OF TECHNOLOGY Page 4


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Let’s assume that we write a Python Program first.py, where first is the name of the
program and .py is the extension
 Next step is to compile the program using the python compiler. The python compiler
converts the python program into Byte code
 Byte code is the fixed set of instructions that represent all operations which run on
any operating systems.
 These byte code instructions are contained in the file first.pyc, python compiled file
 Python Virtual Machine (PVM) uses an interpreter which understands the byte code
and converts it into machine code.
 These machine codes are then executed by the processor and results are displayed.

2.3 VALUES AND TYPES


 A value is one of the basic things a program works with, like a letter or a number.
 Following are the various basic types of a value:

S No Types Example
1 int 10,100,-256,789656
2 float 3.14,2.56789,-21.9
3 boolean True or False
4 string “Hai” or ‘Hi’
5 list [0,1,2,3,4]

 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.
 If we are not sure what type a value has, the interpreter can tell us.
>>>type('Hello, World!')
< class 'str'>

PPG INSTITUTE OF TECHNOLOGY Page 5


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

>>>type(17)
< class 'int'>
 Numbers with a decimal point belong to a type called float, because these numbersare
represented in a format called floating-point.
>>>type(3.2)
<class 'float'>
 Values like '17' and '3.2' are strings since they are quoted eventhough they look like
numbers.
>>>type('17')
<class 'str'>
>>>type('3.2')
<class 'str'>
2.3.1 Variables
 Variables are defined as reserved memory locations to store values.
 Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory.
 Therefore, by assigning different data types to the variables, we can store integers,
decimals or characters in these variables.

2.3.1.1 Rules for Naming Variables


 Variable names can contain letters,symbols like underscore (__) and numbers,
 They begin with a letter not numbers.
 Both uppercase and lowercase letters are different
 Keywords cannot be used as variable names.
Example for valid identifier
abc, xy12, good_start
Example for non-valid identifier
12xy, x$y

2.3.1.2 Assigning Values to Variables


 Python variables do not need explicit declaration to reserve memory space.
 The declaration happens automatically when we assign a value to a variable.
 The equal sign = is used to assign values to variables.
PPG INSTITUTE OF TECHNOLOGY Page 6
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 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 −

counter=100 # An integer assignment


miles=1000.0 # A floating point
name="John" # A string

print(counter)
print(miles)
print(name)

This produces the following result −

100
1000.0
John

2.3.1.3 Multiple Assignment


 Python allows us to assign a single value to several variables simultaneously.
 For example −

a = b = c =1

 Here, an integer object is created with the value 1, and all the three variables are
assigned to the same memory location.
 We can also assign multiple objects to multiple variables. For example −

a, b, c =1,2,"john"

 Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

2.3.2 Standard Data Types


Python has five standard data types −
 Numbers

PPG INSTITUTE OF TECHNOLOGY Page 7


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 String
 List
 Tuple
 Dictionary

1. Python Numbers
 Number data types store numeric values. Number objects are created when we assign
a value to them.
 For example −

var1 =1
var2 =10

 Python supports three different numerical types −


 int – signed integers
Ex: 10, -786, 158976
 float – floating point real values
Ex: 3.14, -21.9, 32.3+e18
 complex – complex numbers
Ex: 3.14j, -3+4j, 3.2+6.78J
 All integers in Python3 are represented as long integers. Hence, there is no separate
number type as long.

2. Python Strings
 Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
 Python allows either pair of single or double quotes.
 Subsets of strings can be taken using the slice operator [] and [:] with indexes starting
at 0 in the beginning of the string and working their way from -1 to the end.
 The plus (+) sign is the string concatenation operator and the asterisk (∗) is the
repetition operator.
 For example −

#!/usr/bin/python3

PPG INSTITUTE OF TECHNOLOGY Page 8


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

str='Hello World!'
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str*2) # Prints string two times
print(str+"TEST") # Prints concatenated string

This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

3. Python Lists
 It is an ordered sequence of values of any data type like string, integer, float etc.
Values in the list are called elements/items.
 A list contains items separated by commas and enclosed within square brackets [].
 The values stored in a list can be accessed using the slice operator [] and [:] with
indexes starting at 0 in the beginning of the list and working their way to end -1.
 The plus (+) sign is the list concatenation operator, and the asterisk  (∗)is the
repetition operator.
 For example −

#!/usr/bin/python3
list=['abcd',786,2.23,'john',70.2]
tinylist=[123,'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element

PPG INSTITUTE OF TECHNOLOGY Page 9


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print(tinylist*2) # Prints list two times


print(list +tinylist) # Prints concatenated lists

This produces the following result −

['abcd', 786, 2.23, 'john', 70.200000000000003]


abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

4. Python Boolean
 Boolean is the type of the built-in values True and False.
 Useful in conditional expressions, and anywhere else we want to represent the true or
false of some condition.
 Mostly interchangeable with the integers 1 and 0.
 The type object for this new type is named bool
>>> bool(1)
True
>>> bool(0)
False
>>>type(2>3)
class ‘bool’

2.3.3 Python Keywords


 Keywords are the reserved words that cannot be used for any identifier names.
 Python has the following 33 keywords:
and del from not while
as elif global or with
assert else if pass yield
break except import print True
class nonlocal in raise False
continue finally is return

PPG INSTITUTE OF TECHNOLOGY Page 10


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

def for lambda try

2.4 OPERATORS
 Operators are special symbols that represent computations like addition and
multiplication.
 The values the operator is applied to are called operands.

2.4.1 Types of Operator


Python language supports the following types of operators −
 Arithmetic Operators
 Comparison Operators
 Relational Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

1. Python Arithmetic Operators


 Performs basic arithmetic operations like addition, subtraction, multiplication and
division.
 Assume variable a holds the value 10 and variable b holds the value 21, then −

Operator Description Example

+ Performs addition on two operands


a + b = 31
Addition

- Performs subtraction on two operands


a – b = -11
Subtraction

* Multiplication Performs multiplication on two operands a * b = 210

/ Performs division on two operands


b / a = 2.1
Division

PPG INSTITUTE OF TECHNOLOGY Page 11


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

% Performs division and returns remainder


b%a=1
Modulus

** Performs exponential power calculation on operands


a**2 =100
Exponent

Performs division and returns quotient. If the quotient value 9//2 = 4 and
// is decimal value then it is rounded to lowest whole integer. 9.0//2.0 = 4.0,
Floor Division -11//3 = -4,
-11.0//3 = -4.0
Example:
a=4
b=2
print ("Sum = ", a+b)
print ("Difference = ", a-b )
print ("Product = ", a*b)
print ("Division = ", a/b )
print ("Modulus = ", a%b)
print ("Exponent = ", a**b)
print ("Floor Division = ", a//b)
Output:
Sum = 6
Difference = 2
Product = 8
Division = 2.0
Modulus = 0
Exponent = 16
Floor Division = 2

2. Python Comparison Operators


 These operators compare the values on either side of them and decide the relation
among them. They are also called Relational operators.
 Assume variable a holds the value 10 and variable b holds the value 20, then –

PPG INSTITUTE OF TECHNOLOGY Page 12


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Operator Description Example

If the values of two operands are equal, then the condition becomes true. a==b is not
==
true.

!= If values of two operands are not equal, then condition becomes true. a!=b is true.

If the value of left operand is greater than the value of right operand, a>b is not
>
then condition becomes true. true.

If the value of left operand is less than the value of right operand, then
< a<b is true.
condition becomes true.

If the value of left operand is greater than or equal to the value of right a>=b is not
>=
operand, then condition becomes true. true.

If the value of left operand is less than or equal to the value of right a<=b is
<=
operand, then condition becomes true. true.
Example:
x=40
y=5
print("Greater than = ",(x>y))
print("Less than = ",(x<y))
print("Equals to = ",(x==y))
print("Not Equals to = ",(x!=y))
print("Greater than or equal to =",(x>=y))
print("Less than or equal to = ",(x<=y))
Output:
Greater than = True
Less than = False
Equals to = False
Not Equals to = True
Greater than or equal to = True
Less than or equal to = False

PPG INSTITUTE OF TECHNOLOGY Page 13


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

3. Python Assignment Operators


Operator Description Example

Assigns values from right side operands to left side operand c=a+b
= assigns value of
a + b into c

Performs addition of two operands and assign the result to c += a


+=
left operand is equivalent to
Add AND
c=c+a

Performs subtraction of two operands and assign the result c -= a


-=
to left operand is equivalent to
Subtract AND
c=c-a

Performs multiplication of two operands and assign the c *= a


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

Performs division of two operands and assign the result to c /= a is equivalent


/=
left operand to
Divide AND
c=c/a

Performs Modulo division of two operands and assign the c %= a


%=
result to left operand is equivalent to
Modulus AND
c=c%a

Performs exponential power calculation on operators and c **= a


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

Performs floor division on operators and assign value to the c //= a


//=
left operand is equivalent to
Floor Division
c = c // a
Example:
PPG INSTITUTE OF TECHNOLOGY Page 14
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

a=4
b=2
a+=b
print ("Sum = ", a)
a-=b
print ("Difference = ", a)
a*=b
print ("Product = ", a)
a/=b
print ("Division = ", a )
b=3
a%=b
print ("Modulus = ", a)
a**=b
print ("Exponent = ", a)
a//=b
print ("Floor Division = ", a)

Output:
Sum = 6
Difference = 4
Product = 8
Division = 4.0
Modulus = 1.0
Exponent = 1.0
Floor Division = 0.0

4. Python Bitwise Operators


 Bitwise operator works on bits and performs bit-by-bit operation.
 Assume if a = 60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
PPG INSTITUTE OF TECHNOLOGY Page 15
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
 Python's built-in function bin can be used to obtain binary representation of an integer
number.
 The following Bitwise operators are supported by Python language −

Operator Description Example

Returns 1 if both the operands are 1. Otherwise 0. a & b 


&
means
Binary AND
00001100

Returns 1 if any one of the operands is 1. Otherwise a|b=61 


|
0. means
Binary OR
00111101

Returns 1 if both the operands are different. a^b = 49 


^
Otherwise 0. means
Binary XOR
00110001

Returns 1 if the value is 0. Otherwise 0  ~a = -61


means 1100 0011
~
in 2's complement
Binary Ones
form due to a
Complement
signed binary
number.

The left operand's value is moved left by the number a << = 240 
<<
of bits specified by the right operand. means
Binary Left Shift
11110000

The left operand's value is moved right by the a >> = 15 


>>
number of bits specified by the right operand. means
Binary Right Shift
00001111

5. Python Logical Operators


PPG INSTITUTE OF TECHNOLOGY Page 16
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 The following logical operators are supported by Python language. Assume


variable a holds True and variable b holds False then –

Operator Description Example

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

or If any of the two operands are non-zero then condition


a or b is True.
Logical OR becomes true.

not Used to reverse the logical state of its operand. not(a and b) is
Logical NOT True.
Program:
x=14
y=7
print(x>y and x==y)
print(x>y or x<y)
print(not(x<y))

Output:
False
True
True

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

Operator Description Example

in Evaluates to true if it finds a variable in the specified x in y,


sequence and false otherwise. here in results in a 1 if x
is a member of sequence

PPG INSTITUTE OF TECHNOLOGY Page 17


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

y.

Evaluates to true if it does not finds a variable in the x not in y,


specified sequence and false otherwise. here not in results in a 1
not in
if x is not a member of
sequence y.
Example
a=1
b = 20
list = [1, 2, 3, 4, 5 ]
print(a in list)
print(a not in list)

Output:
True
False

7. Python Identity Operators


 Identity operators compare the memory locations of two objects. There are two
Identity operators as explained below –

Operator Description Example

Evaluates to true if the variables on either side of the operator point x is y,


to the same object and false otherwise. here is results in
is
1 if id xx equals
id yy.

Evaluates to false if the variables on either side of the operator point x is not y,
to the same object and true otherwise. here is
is not not results in 1
if id xx is not
equal to id yy.
Example:

PPG INSTITUTE OF TECHNOLOGY Page 18


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

x=15
y=15
z=10
print(x is y)
print(y is z)
print(x is z)
print(x is not y)
print(y is not z)
print(x is not z)
Output:
True
False
False
False
True
True
2.4 EXPRESSIONS AND STATEMENTS
 An expression is a combination of values, variables, and operators.
 A value itself is considered an expression, and so is a variable, so the following are all
legal expressions
 Examples:
 17
 x
 x + 17
 A statement is a unit of code that the Python interpreter can execute.

2.5 PYTHON OPERATORS PRECEDENCE


2.5.1 Order of operations
 When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence.
 The acronym PEMDAS is a useful way to remember the rules:
 Parentheses have the highest precedence
 2 * (3-1) is 4, and
PPG INSTITUTE OF TECHNOLOGY Page 19
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 (1+1)**(5-2) is 8.
 Exponentiation has the next highest precedence
 2**1+1 is 3, not 4, and
 3*1**3 is 3, not 27.
 Multiplication and Division have the same precedence, which is higher
thanAddition and Subtraction, which also have the same precedence.
 2*3-1 is 5, not4, and
 6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right (except
exponentiation).
 So in the expression degrees / 2 * pi, the division happens first and
the result is multiplied by pi.
 The following table lists all operators from highest precedence to the lowest.

S.No. Operator & Description

**
1
Exponentiation raise to the power

~ +-
2
Complement, unary plus and minus 

* / % //
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 <= <> >=

PPG INSTITUTE OF TECHNOLOGY Page 20


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

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

2.6 COMMENTS
 A comment is a piece of program text that the interpreter ignores but that provides
useful documentation to programmers.
 Comments start with the # symbol
 Example:
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
 In this case, the comment appears on a line by itself. We can also put comments at the
end of a line:
percentage = (minute * 100) / 60 # percentage of an hour
 We can also use triple single (‘’’) or triple double quotes (“””) at the start and end of a
multiple-line comment.
 Example:
‘’’ Multiline Comment
This is an example’’’
print(“Hello World”)

PPG INSTITUTE OF TECHNOLOGY Page 21


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

2.7 TUPLE ASSIGNMENT


 Python has a very powerful tuple assignment feature that allows a tuple of variables
on the left of an assignment to be assigned values from a tuple on the right of the
assignment.
 One requirement is that the number of variables on the left must match the number of
elements in the tuple.
 Once in a while, it is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable.
 For example, to swap a and b:

temp = a
a=b
b = temp

 Tuple assignment solves this problem neatly:

(a,b) = (b,a)

 The left side is a tuple of variables; the right side is a tuple of values.
 Each value is assigned to its respective variable.
 All the expressions on the right side are evaluated before any of the assignments.
 Naturally, the number of variables on the left and the number of values on the right
have to be the same.

>>>(a,b,c,d)=(1,2,3)
ValueError: need more than 3 values to unpack

2.8 FUNCTIONS
 A function is a block of organized, reusable code that is used to perform a single,
related action.
 Functions provide better modularity for our application and a high degree of code
reusing.
 Types of Functions:
 Built-in Function

PPG INSTITUTE OF TECHNOLOGY Page 22


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 These are functions are already pre-defined.


 Ex: print(),int(),float(), str()
 User-Defined Function
 These functions are defined by user.
2.8.1 Type conversion functions
 Python provides built-in functions that convert values from one type to another.
 The int function takes any value and converts it to an integer,
>>>int('32')
32
>>>int('Hello')
ValueError: invalid literal for int(): Hello
 int can convert floating-point values to integers, but it doesn’t round off; it chops off
the fraction part:
>>>int(3.99999)
3
>>>int(-2.3)
-2
 float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
 Finally, str converts its argument to a string:
>>>str(32)
'32'
>>>str(3.14159)
'3.14159'
2.8.2 Defining a Function
 We 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 ( ).

PPG INSTITUTE OF TECHNOLOGY Page 23


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Any input parameters or arguments should be placed within these


parentheses.
 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_suite
return[expression]

Example

def printme(str):
print (str)
return

2.8.3 Parameters:
 When a function is invoked, a value is passed to the parameter. This value is referred
to as actual parameter or argument. Parameters provide the data communication
between calling function and called function.
 Two types:
 Actual parameters:
These are the parameters transferred from the calling function [main function]
to the called function [user defined function].
 Formal parameters:
Passing the parameters from the called functions [user defined function] to the
calling functions [main function].
Note:
 Actual parameter – This is the argument which is used in function call.
 Formal parameter – This is the argument which is used in function definition.

PPG INSTITUTE OF TECHNOLOGY Page 24


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

2.8.4 Calling a Function


 Once the basic structure of a function is finalized, we can execute it by calling it
from another function or directly from the Python prompt by specifying its name.
 Following is the example to call printme() function −

def printme(str):
print (str)
return
# Now you can call printme function
printme("First Call")
printme("Second call")

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

First Call
Second Call

2.8.5 Passing parameters


 Python uses a mechanism, which is known as "Call-by-Object", sometimes also
called "Call by Object Reference” or “Call by Sharing”.
 If we pass immutable arguments like integers, strings or tuples to a function, the
object reference is passed to the function parameters and they can't be changed
within the function, because they can't be changed at all, i.e. they are immutable.
 If we pass mutable arguments like lists, they are passed by object reference, but
they can be changed in the function.
 If we pass a list to a function, we have to consider two cases:
 Elements of a list can be changed in place, i.e. the list will be changed even in
the caller's scope.
 If a new list is assigned to the name, the old list will not be affected, i.e. the list
in the caller's scope will remain untouched
 Example 1: Element of a list changed in the function and thus reflected in caller

def changeme( mylist ):


print ("Values inside the function before change: ", mylist)
mylist[2]=50

PPG INSTITUTE OF TECHNOLOGY Page 25


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print ("Values inside the function after change: ", 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. Therefore, this would produce the following result −

Values inside the function before change: [10, 20, 30]


Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]

Example 2: List assigned to new value and thus changes will not be reflected in caller

# Function definition is here


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

# Now we 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]

2.9 FLOW OF EXECUTION

PPG INSTITUTE OF TECHNOLOGY Page 26


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 The order in which statements are executed, which is called the flow of execution.
 Execution always begins at the first statement of the program.
 Statements are executed one at a time, in order from top to bottom.
 Function definitions do not alter the flow of execution of the program, but statements
inside the function are not executed until the function is called.
 A function call is like a detour in the flow of execution.
 Instead of going to the next statement, the flow jumps to the body of the function,
executes all the statements there, and then comes back to pick up where it left off.

2.10 FUNCTION ARGUMENTS


 We can call a function by using the following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
1. 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(), we definitely need to pass one argument, otherwise it
gives a syntax error as follows −

# Function definition is here


def printme( ):
#This prints a passed string into this function
print (str)
return
# Now we 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>

PPG INSTITUTE OF TECHNOLOGY Page 27


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

printme();
TypeError:printme() takes exactly 1 argument (0 given)

2. Keyword arguments
 Keyword arguments are related to the function calls.
 When we use keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
 This allows us 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.
 Example:

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

# Now we can call printme function


printme(str="My string")

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

Mystring

The following example gives clearer picture. Note that the order of parameters does not
matter.

# Function definition is here


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

# Now we can call printinfo function


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

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

PPG INSTITUTE OF TECHNOLOGY Page 28


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Name: miki
Age: 50

3. 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.
 Example;

# 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 we 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
Age50
Name:miki
Age35

4. Variable-length arguments
 We may need to process a function for more arguments than we specified while
defining the function.
 These arguments are called variable-length arguments and are not named in the
function definition
 Syntax for a function with variable length argument −

def functionname([formal_args,]*var_args_tuple):
function_suite
return[expression]

PPG INSTITUTE OF TECHNOLOGY Page 29


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 An asterisk (*) is placed before the variable name that holds the values of all variable
length arguments.
 This tuple remains empty if no additional arguments are specified during the
function call.
 Following is a simple example −

# 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 we can call printinfo function
printinfo(10)
printinfo(70,60,50)

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

Output is:
10
Output is:
70
60
50

2.10.1 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.
 Example

# Function definition is here


def sum( arg1, arg2 ):

PPG INSTITUTE OF TECHNOLOGY Page 30


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

# Add both the parameters and return them.


total = arg1 + arg2
print ("Inside the function : ", total)
return total
# Now we can call sum function
total = sum(10,20)
print ("Outside the function : ", total)

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

Inside the function : 30


Outside the function : 30

2.11 SCOPE OF VARIABLES


 All variables in a program may not be accessible at all locations in that program.
 This depends on where we have declared a variable.
 The scope of a variable determines the portion of the program where we can access a
particular identifier.
 There are two basic scopes of variables in Python −
 Global variables
 Local variables

2.11.1 Global vs. Local variables


Local Variables Global Variables
Variables are defined inside a function Variables are defined outside of any
body function
Local variables can be accessed only Global variables can be accessed
inside the function in which they are throughout the program body by all
declared functions.
 Following is a simple example −

#!/usr/bin/python
total =0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):

PPG INSTITUTE OF TECHNOLOGY Page 31


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

# 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 we can call sum function
sum(10,20)
print ("Outside the function global total : ", total )

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

Inside the function local total : 30


Outside the function global total : 0

2.12 ADVANTAGES OF USING FUNCTIONS


 Makes our program easier to read and debug.
 Functions can make a program smaller by eliminating repetitive code.
 Dividing a long program into functions allows us to debug the parts one at a time
and then assemble them into a working whole.
 Well-designed functions are often useful for many programs. Once we write and
debug one, we can reuse it.

2.13 MODULES
 A module allows us to logically organize our 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 we can bind and
reference.
 Simply, a module is a file consisting of Python code.
 A module can define functions, classes and variables.
 A module can also include runnable code.
Example

def print_func( par ):


print ("Hello : ", par)

PPG INSTITUTE OF TECHNOLOGY Page 32


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

return

2.13.1 The import Statement
 We can use any Python source file as a module by executing an import statement in
some other Python source file.
 The import has the following syntax:

import module1[, module2[,...moduleN]

 When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
 For example, to import the module support.py, we need to put the following
command at the top of the script −

#!/usr/bin/python
# Import module support
import support
# Now we can call defined function that module as follows
support.print_func("Zara")

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

Hello:Zara

 A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple
imports occur.
2.13.2 The from...import Statement
 Python's from statement lets us import specific attributes from a module into the
current namespace.
 The from...import has the following syntax −

from modname import name1[, name2[,...nameN]]

 For example, to import the function fibonacci from the module fib, use the following
statement −

from fib import fibonacci

PPG INSTITUTE OF TECHNOLOGY Page 33


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table of
the importing module.

2.13.3 The from...import * Statement:


 It is also possible to import all names from a module into the current namespace by
using the following import statement −

from modname import*

 This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

2.13.4 The dir( ) Function


 The dir() built-in function returns a sorted list of strings containing the names
defined by a module.
 The list contains the names of all the modules, variables and functions that are
defined in a module.
 Following is a simple example −

# Import built-in module math


import math
content =dir(math)
print (content)

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

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

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

2.14 ILLUSTRATIVE PROBLEMS

PPG INSTITUTE OF TECHNOLOGY Page 34


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

1. Exchange the values of two variables


Program
x = input("Enter value of x:")
y = input("Enter value of y:")
temp = x
x=y
y = temp
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)

Output
Enter value of x:6
Enter value of y:7
The value of x after swapping: 7
The value of y after swapping: 6

2. Circulate the values of n variables


Program
mylist=[1,2,3,4,5,6,7]
n=int(input("Enter number of times to circulate "))
a=len(mylist)
b=n%a
newlist=mylist[b:]+mylist[:b]
print("Before Circulate=",mylist)
print("After Circulate=",newlist)
Output
Enter number of times to circulate1
Before Circulate= [1, 2, 3, 4, 5, 6, 7]
After Circulate= [2, 3, 4, 5, 6, 7, 1]

3. Distance between two points


Program
import math
PPG INSTITUTE OF TECHNOLOGY Page 35
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

x1=int(input("Enter the X-Coordinate of first point"))


y1=int(input("Enter the Y-Coordinate of first point"))
x2=int(input("Enter the X-Coordinate of Second point"))
y2=int(input("Enter the Y-Coordinate of Second point"))
distance = math.sqrt( ((x1-x2)**2)+((y1-y2)**2) )
print(distance)

Output
Enter the X-Coordinate of first point 4
Enter the Y-Coordinate of first point 0
Enter the X-Coordinate of Second point 6
Enter the Y-Coordinate of Second point 6
6.324555320336759

PPG INSTITUTE OF TECHNOLOGY Page 36

You might also like