Python Module 1 Notes
Python Module 1 Notes
Python Module 1 Notes
MODULE I
CONDITIONAL EXECUTION
FUNCTIONS
Function calls, Built-in functions, Type conversion functions, Random numbers, Math functions,
Adding new functions , Definitions and uses, Flow of execution, Parameters and arguments , Fruitful
functions and void functions , Why functions?
MODULE I
Operations specified by the program instructions. CPU will perform the given tasks with a
tremendous speed. Hence, the good programmer has to keep the CPU busy by providing
enough tasks to it.
Main Memory: It is the storage area to which the CPU has a direct access. Usually, the
programs stored in the secondary storage are brought into main memory before the execution.
The processor (CPU) will pick a job from the main memory and performs the tasks. Usually,
information stored in the main memory will be vanished when the computer is turned-off.
What
Next?
Software
Main Secondary
Memory Memory
Secondary Memory: The secondary memory is the permanent storage of computer. Usually,
the size of secondary memory will be considerably larger than that of main memory. Hard disk,
USB drive etc can be considered as secondary memory storage.
I/O Devices: These are the medium of communication between the user and the computer.
Keyboard, mouse, monitor, printer etc. are the examples of I/O devices.
Network Connection: Nowadays, most of the computers are connected to network and hence
they can communicate with other computers in a network. Retrieving the information from
other computers via network will be slower compared to accessing the secondary memory.
Moreover, network is not reliable always due to problem in connection.
The programmer has to use above resources sensibly to solve the problem.
Usually, a programmer will be communicating with CPU by telling it „what to do next‟. The usage
of main memory, secondary memory, I/O devices also can be controlled by the programmer.
To communicate with the CPU for solving a specific problem, one has to write a set of instructions.
Such a set of instructions is called as a program.
Understanding Programming
A programmer must have skills to look at the data/information available about a problem, analyze
it and then to build a program to solve the problem. The skills to be possessed by a good
programmer includes –
Thorough knowledge of programming language: One needs to know the vocabulary and
grammar (technically known as syntax) of the programming language. This will help in
constructing proper instructions in the program.
Skill of implementing an idea: A programmer should be like a „story teller‟. That is, he must
be capable of conveying something effectively. He/she must be able to solve the problem by
designing suitable algorithm and implementing it. And, the program must provide appropriate
output as expected.
Thus, the art of programming requires the knowledge about the problem‟s requirement and the
strength/weakness of the programming language chosen for the implementation. It is always
advisable to choose appropriate programming language that can cater the complexity of the problem
to be solved.
Words and Sentences
Every programming language has its own constructs to form syntax of the language.
Basic constructs of a programming language includes set of characters and keywords that it
supports.
The keywords have special meaning in any language and they are intended for doing specific task.
Python has a finite set of keywords as given in Table below.
Because, there are separate set of editors (IDE) available for different OS like Window, UNIX,
Ubuntu, Soloaris, Mac, etc. The basic Python can be downloaded from the link:
https://www.python.org/downloads/
Python has rich set of libraries for various purposes like large-scale data processing, predictive
analytics, scientific computing etc. Based on one‟s need, the required packages can be downloaded.
But, there is a free open source distribution Anaconda, which simplifies package management and
deployment.
Hence, it is suggested for the readers to install Anaconda from the below given link, rather than just
installing a simple Python.
https://anaconda.org/anaconda/python
Successful installation of anaconda provides you Python in a command prompt, the default editor
IDLE and also a browser-based interactive computing environment known as jupyter notebook.
The prompt >>> (usually called as chevron) indicates the system is ready to take Python
instructions.
If you would like to use the default IDE of Python, that is, the IDLE, then you can just run IDLE
and you will get the editor as shown in Figure.
Here, after typing the first line of code and pressing the enter key, we could able to get the output
of that line immediately. Then the prompt (>>>) is returned on the screen. This indicates, Python is
ready to take next instruction as input for processing.
Once we are done with the program, we can close or terminate Python by giving quit() command as
shown –
>>> quit() #Python terminates
Here, x, y and z are variables storing respective values. As each line of code above is processed
immediately after the line, the variables are storing the given values.
Observe that, though each line is treated independently, the knowledge (or information) gained in the
previous line will be retained by Python and hence, the further lines can make use of previously used
variables.
Thus, each line that we write at the Python prompt are logically related, though they look
independent.
NOTE that, Python do not require variable declaration (unlike in C, C++, Java etc) before its use. One
can use any valid variable name for storing the values. Depending on the type (like number, string etc)
of the value being assigned, the type and behavior of the variable name is judged by Python.
Writing a Program
As Python is interpreted language, one can keep typing every line of code one after the other (and
What is a Program?
A program is a sequence of instructions intended to do some task.
For example, if we need to count the number of occurrences of each word in a text document, we
can write a program to do so.
Writing a program will make the task easier compared to manually counting the words in a
document.
Moreover, most of the times, the program is a generic solution. Hence, the same program may be
used to count the frequency of words in another file.
The person who does not know anything about the programming also can run this program to count
the words.
Programming languages like Python will act as an intermediary between the computer and the
programmer. The end-user can request the programmer to write a program to solve one‟s problem.
Reuse: When we write the programs for general-purpose utility tasks, it is better to write them
with a separate name, so that they can be used multiple times whenever/wherever required.
This is possible with the help of functions.
The art of programming involves thorough understanding of the above constructs and using them
legibly.
After understanding some important concepts about programming and programming languages, we
will now move on to learn Python as a programming language with its syntax and constructs.
In the above four examples, one can make out various types str, int and float.
Observe the 4th example – it clearly indicates that whatever enclosed within a double quote is a
string.
Variables
A variable is a named-literal which helps to store a value in the program.
Variables may take value that can be modified wherever required in the program.
Note that, in Python, a variable need not be declared with a specific type before its usage.
Whenever we want a variable, just use it. The type of it will be decided by the value assigned to it.
A value can be assigned to a variable using assignment operator (=).
Consider the example given below–
>>> x=10
>>> print(x)
10 #output
>>> type(x)
<class 'int'> #type of x is integer
>>> y="hi"
>>> print(y)
hi #output
>>> type(y)
<class 'str'> #type of y is string
It is observed from above examples that the value assigned to variable determines the type of that
variable.
It is a good programming practice to name the variable such that its name indicates its purpose in
the program.
There are certain rules to be followed while naming a variable –
Variable name must not be a keyword
They can contain alphabets (lowercase and uppercase) and numbers, but should not
start with a number.
It may contain a special character underscore(_), which is usually used to combine
variables with two words like my_salary, student_name etc. No other special
characters like @, $ etc. are allowed.
Variable names can start with an underscore character, but we generally avoid it.
As Python is case-sensitive, variable name sum is different from SUM, Sum etc.
Examples:
>>> 3a=5 #starting with a number
SyntaxError: invalid syntax
>>> a$=10 #contains $
SyntaxError: invalid syntax
>>> if=15 #if is a keyword
SyntaxError: invalid syntax
Statements
A statement is a small unit of code that can be executed by the Python interpreter.
It indicates some action to be carried out.
In fact, a program is a sequence of such statements.
Two kinds of statements are: print being an expression statement and assignment statement
Following are the examples of statements –
>>> print("hello") #printing statement
hello
>>> x=5 #assignment statement
Relational or Comparison Operators are used to check the relationship (like less than, greater than
etc) between two operands. These operators return a Boolean value – either True or False.
Assignment Operators: Apart from simple assignment operator = which is used for assigning
values to variables, Python provides compound assignment operators.
For example,
x=x+y can be written as x+=y
Now, += is compound assignment operator. Similarly, one can use most of the arithmetic and
bitwise operators (only binary operators, but not unary) like *, /, %, //, &, ^ etc. as compound
assignment operators.
For example,
>>> x=3
>>> y=5
>>> x+=y #x=x+y
>>> print(x)
8
NOTE:
1. Python has a special feature – one can assign values of different types to multiple variables in
a single statement.
For example,
>>> x, y, st=3, 4.2, "Hello"
>>> print("x= ", x, " y= ",y, " st= ", st)
x=3 y=4.2 st=Hello
2. Python supports bitwise operators like &(AND), | (OR), ~(NOT), ^(XOR), >>(right shift)
and <<(left shift). These operators will operate on every bit of the operands. Working
procedure of these operators is same as that in other languages like C and C++.
3. There are some special operators in Python viz. Identity operator (is and is not) and
membership operator (in and not in). These will be discussed in further Modules.
Expressions
A combination of values, variables and operators is known as expression.
Following are few examples of expression –
x=5
y=x+10
z= x-y*3
The Python interpreter evaluates simple expressions and gives results even without print().
For example,
>>> 5
5 #displayed as it is
>>> 1+2
3 #displayed the sum
But, such expressions do not have any impact when written into Python script file.
Order of Operations
When an expression contains more than one operator, the evaluation of operators depends on the
precedence of operators.
The Python operators follow the precedence rule (which can be remembered as PEMDAS) as given
below –
Parenthesis have the highest precedence in any expression. The operations within
parenthesis will be evaluated first. For example, in the expression (a+b)*c, the
addition has to be done first and then the sum is multiplied with c.
Exponentiation has the 2nd precedence. But, it is right associative. That is, if there are two
exponentiation operations continuously, it will be evaluated from right to left (unlike
most of other operators which are evaluated from left to right).
For example,
>>> print(2**3) #It is 23
8
2
>>> print(2**3**2) #It is 512 i.e., 23
Multiplication and Division are the next priority. Out of these two operations, whichever
comes first in the expression is evaluated.
>>> print(5*2/4) #multiplication and then division 2.5
>>> print(5/4*2) #division and then multiplication 2.5
Addition and Subtraction are the least priority. Out of these two operations, whichever
appears first in the expression is evaluated i.e., they are evaluated from left to right
String Operations
String concatenation can be done using + operator as shown below –
>>> x="32"
>>> y="45"
>>> print(x+y)
3245
Observe the output: here, the value of y (a string “45”, but not a number 45) is placed just in
front of value of x( a string “32”). Hence the result would be “3245” and its type would be
string.
NOTE: One can use single quotes to enclose a string value, instead of double quotes.
There are several such other utility functions in Python, which will be discussed later.
Comments
It is a good programming practice to add comments to the program wherever required.
This will help someone to understand the logic of the program.
Comment may be in a single line or spread into multiple lines.
A single-line comment in Python starts with the symbol #.
Multiline comments are enclosed within a pair of 3-single quotes.
Ex2.
basic=10000
da=0.3*basic
gross_sal=basic+da
print("Gross Sal = ",gross_sal) #output is 13000
One can observe that both of these two examples are performing same task.
But, compared to Ex1, the variables in Ex2 are indicating what is being calculated.
That is, variable names in Ex2 are indicating the purpose for which they are being used in the
program. Such variable names are known as mnemonic variable names. The word mnemonic
means memory aid. The mnemonic variables are created to help the programmer to remember the
purpose for which they have been created.
Python can understand the set of reserved words (or keywords), and hence it flashes an error when
such words are used as variable names by the programmer
.
Moreover, most of the Python editors have a mechanism to show keywords in a different color.
Hence, programmer can easily make out the keyword immediately when he/she types that word.
Debugging
Some of the common errors a beginner programmer may make are syntax errors.
Though Python flashes the error with a message, sometimes it may become hard to understand the
cause of errors. Some of the examples are given here –
Here, there is a space between the terms avg and sal, which is not allowed.
Ex2. >>>m=09
SyntaxError: invalid token
As shown in above examples, the syntax errors will be alerted by Python. But, programmer is
responsible for logical errors or semantic errors. Because, if the program does not yield into
expected output, it is due to mistake done by the programmer, about which Python is unaware of.
CONDITIONAL EXECUTION
Boolean Expressions
A Boolean Expression is an expression which results in True or False.
The True and False are special values that belong to class bool.
Check the following –
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Boolean expression may be as below –
>>> 10==12
False
>>> x=10
>>> y=10
>>> x==y
True
Various comparison operations are shown in Table.
Examples:
>>> a=10
>>> b=20
>>> x= a>b
>>> print(x)
False
>>> print(a==b)
False
>>> print("a<b is ", a<b)
a<b is True
>>> print("a!=b is", a!=b)
a!=b is True
>>> 10 is 20
False
>>> 10 is 10
True
NOTE: For a first look, the operators ==and is look same. Similarly, the operators !=and is not look
the same. But, the operators == and != does the equality test. That is, they will compare the values
stored in the variables. Whereas, the operators is and is not does the identity test. That is, they will
compare whether two objects are same. Usually, two objects are same when their memory locations
are same. This concept will be more clear when we take up classes and objects in Python.
Logical Operators
There are 3 logical operators in Python as shown in Table
NOTE:
4. Logical operators treat the operands as Boolean (True or False).
5. Python treats any non-zero number as True and zero as False.
6. While using and operator, if the first operand is False, then the second operand is not
evaluated by Python. Because False and’ed with anything is False.
7. In case of or operator, if the first operand is True, the second operand is not evaluated.
Because True or’ed with anything is True.
Conditional Execution
The basic level of conditional execution can be achieved in Python by using if statement.
Entry
if condition: False
Statement block condition?
Consider an example –
>>> x=10
>>> if x<40:
print("Fail") #observe indentation after if
Fail #output
Alternative Execution
A second form of if statement is alternative execution, in which there are two possibilities based on
condition evaluation.
Here, when the condition is true, one set of statements will be executed and when the condition is
false, another set of statements will be executed.
The syntax and flowchart are as given below –
True False
Condition?
if condition:
Statement block -1
else: Statement Statement
block -2
Statement block -2 block-1
Sample output:
Enter x: 13
x is odd
Nested Conditionals
The conditional statements can be nested.
That is, one set of conditional statements can be nested inside the other.
It can be done in multiple ways depending on programmer’s requirements.
Examples are given below –
Sample Output:
Enter marks:68
First Class
Here, the outer condition marks>=60 is checked first. If it is true, then there are two branches for the
inner conditional. If the outer condition is false, the above code does nothing.
if gender == "M" :
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F":
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")
Sample Output:
Enter gender: F
Enter age: 17
NOTE: Nested conditionals make the code difficult to read, even though there are proper
indentations. Hence, it is advised to use logical operators like and to simplify the nested
conditionals. For example, the outer and inner conditions in Ex1 above can be joined as -
if marks>=60 and marks<70:
#do something
Chained Conditionals
Some of the programs require more than one possibility to be checked for executing a set of
statements.
That means, we may have more than one branch. This is solved with the help of chained
conditionals.
The syntax and flowchart is given below – F
F F
Cond1 Cond2 Condn
if condition1:
Statement Block-1
T T T
elif condition2:
Statement Block-2 Statement Statement Statement Statement
Block-1 Block-2 Block-n Block-(n+1)
|
|
|
|
elif condition_n:
Statement Block-n
else:
Statement Block-(n+1)
The conditions are checked one by one sequentially. If any condition is satisfied, the respective
statement block will be executed and further conditions are not checked. Note that, the last else
block is not necessary always.
else:
print("Fail")
Sample Output:
Enter marks: 78
First Class
Output:
Enter a:12
Enter b:0
SSM/DrKKS/SWM, Dept of CSE, GAT Page 24
Python Application Programming (15CS664) Module I
Here, the expression x<10 and x+y>25 involves the logical operator and. Now, x<10 is evaluated
first, which results to be False. As there is an and operator, irrespective of the result of x+y>25, the
whole expression will be False.
In such situations, Python ignores the remaining part of the expression. This is known as short-
circuiting the evaluation.
When the first part of logical expression results in True, then the second part has to be evaluated to
know the overall result.
The short-circuiting not only saves the computational time, but it also leads to a technique known
as guardian pattern.
Consider following sequence of statements –
>>> x=5
>>> y=0
>>> x>=10 and (x/y)>2
False
>>> x>=2 and (x/y)>2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module> x>=2 and (x/y)>2
ZeroDivisionError: division by zero
Here, when we executed the statement x>=10 and (x/y)>2, the first half of logical expression itself
was False and hence by applying short-circuit rule, the remaining part was not executed at all.
Whereas, in the statement x>=2 and (x/y)>2, the first half is True and the second half is resulted in
runtime-error. Thus, in the expression x>=10 and (x/y)>2, short-circuit rule acted as a guardian by
preventing an error.
One can construct the logical expression to strategically place a guard evaluation just before the
evaluation that might cause an error as follows:
>>> x=5
>>> y=0
>>> x>=2 and y!=0 and(x/y)>2
False
Here, x>=2 results in True, but y!=0 evaluates to be False. Hence, the expression (x/y)>2is never
reached and possible error is being prevented from happening.
Debugging
One can observe from previous few examples that when a runtime error occurs, it displays a term
Traceback followed by few indications about errors.
A traceback is a stack trace from the point of error-occurrence down to the call-sequence till the
point of call.
This is helpful when we start using functions and when there is a sequence of multiple function calls
from one to other.
Then, traceback will help the programmer to identify the exact position where the error occurred.
Most useful part of error message in traceback are –
What kind of error it is
Where it occurred
Compared to runtime errors, syntax errors are easy to find, most of the times. But, whitespace errors
in syntax are quite tricky because spaces and tabs are invisible.
For example –
>>> x=10
>>> y=15
SyntaxError: unexpected indent
The error here is because of additional space given before y. As Python has a different meaning
(separate block of code) for indentation, one cannot give extra spaces as shown above.
In general, error messages indicate where the problem has occurred. But, the actual error may be
before that point, or even in previous line of code.
FUNCTIONS
Function Calls
A function is a named sequence of instructions for performing a task.
When we define a function we will give a valid name to it, and then specify the instructions for
performing required task.
Later, whenever we want to do that task, a function is called by its name.
Consider an example:
>>> type(15)
<class 'int'>
Here type is a function name, 15 is the argument to a function and <class 'int'> is the result of
the function.
Usually, a function takes zero or more arguments and returns the result.
Built-in Functions
Python provides a rich set of built-in functions for doing various tasks.
The programmer/user need not know the internal working of these functions; instead, they need to
know only the purpose of such functions.
Some of the built in functions are given below –
max(): This function is used to find maximum value among the arguments. It can be used for
numeric values or even to strings.
o max(10, 20, 14, 12) #maximum of 4 integers
20
o max("hello world")
'w' #character having maximum ASCII code
o max(3.5, -2.1, 4.8, 15.3, 0.2)
15.3 #maximum of 5 floating point values
len(): This function takes a single argument and finds its length. The argument can be a string, list,
tuple etc
o len(“hello how are you?”)
18
There are many other built-in functions available in Python. They are discussed in further Modules,
wherever they are relevant.
Random Numbers
Most of the programs that we write are deterministic.
That is, the input (or range of inputs) to the program is pre-defined and the output of the program is
one of the expected values.
But, for some of the real-time applications in science and technology, we need randomly generated
output. This will help in simulating certain scenario.
Random number generation has important applications in games, noise detection in electronic
communication, statistical sampling theory, cryptography, political and business prediction etc.
These applications require the program to be nondeterministic.
There are several algorithms to generate random numbers. But, as making a program completely
nondeterministic is difficult and may lead to several other consequences, we generate pseudo-
random numbers.
That is, the type (integer, float etc) and range (between 0 and 1, between 1 and 100 etc) of the
random numbers are decided by the programmer, but the actual numbers are unknown.
Moreover, the algorithm to generate the random number is also known to the programmer. Thus,
the random numbers are generated using deterministic computation and hence, they are known as
pseudo-random numbers!!
Python has a module random for the generation of random numbers. One has to import this
module in the program. The function used is also random().
By default, this function generates a random number between 0.0 and 1.0 (excluding 1.0).
For example –
print(random.random())
0.5287778188896328 #one more random number
Importing a module creates an object.
Using this object, one can access various functions and/or variables defined in that module.
Functions are invoked using a dot operator.
There are several other functions in the module random apart from the function random(). (Do not
get confused with module name and function name. Observe the parentheses while referring a
function name).
Few are discussed hereunder:
randint(): It takes two arguments low and high and returns a random integer between these two
arguments (both low and high are inclusive). For example,
>>>random.randint(2,20)
14 #integer between 2 and 20 generated
>>> random.randint(2,20) 10
choice(): This function takes a sequence (a list type in Python) of numbers as an argument and
returns one of these numbers as a random number. For example,
>>> t=[1,2, -3, 45, 12, 7, 31, 22] #create a list t
>>> random.choice(t) #t is argument to choice()
12 #one of the elements in t
>>> random.choice(t)
1 #one of the elements in t
Various other functions available in random module can be used to generate random numbers
following several probability distributions like Gaussian, Triangular, Uniform, Exponential, Weibull,
Normal etc.
Math Functions
Python provides a rich set of mathematical functions through the module math.
To use these functions, the math module has to be imported in the code.
Some of the important functions available in math are given hereunder
sqrt(): This function takes one numeric argument and finds the square root of that argument.
>>> math.sqrt(34) #integer argument
5.830951894845301
>>> math.sqrt(21.5) #floating point argument
4.636809247747852
log10(): This function is used to find logarithm of the given argument, to the base 10.
>>> math.log10(2)
0.3010299956639812
log(): This is used to compute natural logarithm (base e) of a given number.
>>> math.log(2)
0.6931471805599453
sin(): As the name suggests, it is used to find sine value of a given argument. Note that, the
argument must be in radians (not degrees). One can convert the number of degrees into radians by
multiplying pi/180 as shown below –
>>>math.sin(90*math.pi/180) #sin(90) is 1
1.0
0.9999999999999999
pow(): This function takes two arguments x and y, then finds x to the power of y.
>>> math.pow(3,4)
81.0
Adding New Functions (User-defined Functions)
Python facilitates programmer to define his/her own functions.
The function written once can be used wherever and whenever required.
The syntax of user-defined function would be –
def fname(arg_list):
statement_1
statement_2
……………
Statement_n
return value
The first line in the function def fname(arg_list)is known as function header/definition. The
remaining lines constitute function body.
The function header is terminated by a colon and the function body must be indented.
To come out of the function, indentation must be terminated.
Unlike few other programming languages like C, C++ etc, there is no main()
function or specific location where a user-defined function has to be called.
The programmer has to invoke (call) the function wherever required.
Consider a simple example of user-defined function –
SSM/DrKKS/SWM, Dept of CSE, GAT Page 31
Python Application Programming (15CS664) Module I
def myfun():
print("Hello")
print("Inside the function")
Observe indentation
print("Example of function")
myfun()
Statements outside the print("Example over")
function without indentation.
myfun()is called here.
Here, the first output indicates that myfun is an object which is being stored at the memory address
0x0219BFA8 (0x indicates octal number).
The second output clearly shows myfunis of type function.
(NOTE: In fact, in Python every type is in the form of class. Hence, when we apply type on any
variable/object, it displays respective class name. The detailed study of classes will be done in
Module 4.)
The flow of execution of every program is sequential from top to bottom, a function can be invoked
only after defining it.
Usage of function name before its definition will generate error. Observe the following code:
print("Example of function")
myfun() #function call before definition
print("Example over")
def myfun():
print("Inside myfun()")
The output is –
Example of function Inside
myfun() Inside repeat()
Inside myfun() Example
over
Observe the output of the program to understand the flow of execution of the program.
Initially, we have two function definitions myfun()and repeat()one after the other. But, functions
are not executed unless they are called (or invoked). Hence, the first line to execute in the above
program is –
print("Example of function")
Then, there is a function call repeat(). So, the program control jumps to this function. Inside
repeat(), there is a call for myfun().
Now, program control jumps to myfun()and executes the statements inside and returns back to
repeat() function. The statement print(“Inside repeat()”) is executed.
Once again there is a call for myfun()function and hence, program control jumps there. The
function myfun() is executed and returns to repeat().
As there are no more statements in repeat(), the control returns to the original position of its call.
Now there is a statement print("Example over")to execute, and program is terminated.
def test(var):
print("Inside test()")
print("Argument is ",var)
In the above program, var is called as parameter and x and y are called as arguments.
The argument is being passed when a function test() is invoked. The parameter receives the
argument as an input and statements inside the function are executed.
As Python variables are not of specific data types in general, one can pass any type of value to the
function as an argument.
Python has a special feature of applying multiplication operation on arguments while passing them
to a function. Consider the modified version of above program –
def test(var):
print("Inside test()")
print("Argument is ",var)
One can observe that, when the argument is of type string, then multiplication indicates that string
is repeated 3 times.
Whereas, when the argument is of numeric type (here, integer), then the value of that argument is
literally multiplied by 3.
def sum(a,b):
return a+b
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
s=sum(x,y)
print("Sum of two numbers:",s)
In the above example, The function sum() take two arguments and returns their sum to the
receiving variable s.
When a function returns something and if it is not received using a LHS variable, then the return
value will not be available.
For instance, in the above example if we just use the statement sum(x,y) instead of s=sum(x,y),
then the value returned from the function is of no use.
On the other hand, if we use a variable at LHS while calling void functions, it will receive None.
For example,
p= test(var) #function used in previous example
print(p)
Now, the value of p would be printed as None. Note that, None is not a string, instead it is of type
class 'NoneType'. This type of object indicates no value.
Why Functions?
Functions are essential part of programming because of following reasons –
Creating a new function gives the programmer an opportunity to name a group of statements,
which makes the program easier to read, understand, and debug.
Functions can make a program smaller by eliminating repetitive code. If any modification is
required, it can be done only at one place.
Dividing a long program into functions allows the programmer to debug the independent functions
separately and then combine all functions to get the solution of original problem.
Well-designed functions are often useful for many programs. The functions written once for a
specific purpose can be re-used in any other program.
Observe that the two values are separated by a space without mentioning anything specific. This is
possible because of the existence of an argument sep in the print() function whose default value is
SSM/DrKKS/SWM, Dept of CSE, GAT Page 36
Python Application Programming (15CS664) Module I
white space. This argument makes sure that various values to be printed are separated by a space for
a better representation of output.
The programmer has a liberty in Python to give any other character(or string) as a separator by
explicitly mentioning it in print() as shown below –
We can observe that the values have been separated by hyphen, which is given as a value for the
argument sep. Consider one more example –
>>> college="SVIT"
>>> address=”BANGALORE"
>>> print(college, address, sep='@')
SVIT@BANGALORE
If you want to deliberately suppress any separator, then the value of sep can be set with empty string
as shown below –
>>> print("Hello","World", sep='')
HelloWorld
You might have observed that in Python program, the print() adds a new line after printing the data.
In a Python script file, if you have two statements like –
print(“Hello”)
print(“World”)
then, the output would be
Hello
World
This may be quite unusual for those who have experienced programming languages like C, C++ etc.
In these languages, one has to specifically insert a new-line character (\n) to get the output in
different lines. But, in Python without programmer‟s intervention, a new line will be inserted. This is
possible because, the print() function in Python has one more special argument end whose default
value itself is new-line. Again, the default value of this argument can be changed by the programmer
as shown below (Run these lines using a script file, but not in the terminal/command prompt) –
print(“Hello”, end= „@‟)
print(“World”)
Ex1: When multiple variables have to be displayed embedded within a string, the format()
function is useful as shown below –
>>> x=10
>>> y=20
>>> print("x={0}, y={1}".format(x,y))
x=10, y=20
While using format() the arguments of print() must be numbered as 0, 1, 2, 3, etc. and they must be
provided inside the format() in the same order.
Ex2: The format() function can be used to specify the width of the variable (the number of
spaces that the variable should occupy in the output) as well. Consider below given example
which displays a number, its square and its cube.
for x in range(1,5):
print("{0:1d} {1:3d} {2:4d}".format(x,x**2, x**3))
Output:
1 1 1
2 4 8
3 9 27
4 16 64
Here, 1d, 3d and 4d indicates 1-digit space, 2-digit space etc. on the output screen.
Ex3: One can use % symbol to have required number of spaces for a variable. This will be useful
in printing floating point numbers.
>>> x=19/3
>>> print(x)
6.333333333333333 #observe number of digits after dot
>>> print("%.3f"%(x)) #only 3 places after decimal point 6.333
>>> x=20/3
>>> y=13/7
>>> print("x= ",x, "y=",y) #observe actual digits
x=6.666666666666667 y= 1.8571428571428572