Module1 Python 15CS664
Module1 Python 15CS664
Module1 Python 15CS664
1
Notes for Python Application Programming (Open Elective - 15CS664)
MODULE – 1
1.1 WHY SHOULD YOU LEARN TO WRITE PROGRAMS
Programs are generally written to solve the real-time arithmetic/logical problems.
Nowadays, computational devices like personal computer, laptop, and cell phones are
embedded with operating system, memory and processing unit. Using such devices one
can write a program in the language (which a computer can understand) of one’s choice to
solve various types of problems. Humans are tend get bored by doing computational tasks
multiple times. Hence, the computer can act as a personal assistant for people for doing
their job!! To make a computer to solve the required problem, one has to feed the proper
program to it. Hence, one should know how to write a program!!
There are many programming languages that suit several situations. The programmer must
be able to choose the suitable programming language for solving the required problem
based on the factors like computational ability of the device, data structures that are
supported in the language, complexity involved in implementing the algorithm in that
language etc.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 2
Notes for Python Application Programming (Open Elective - 15CS664)
What
Next?
Software
Main Secondary
Memory Memory
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 3
Notes for Python Application Programming (Open Elective - 15CS664)
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.
A programmer may use variables to store the values in a program. Unlike many other
programming languages, a variable in Python need not be declared before its use.
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 4
Notes for Python Application Programming (Open Elective - 15CS664)
The jupyter notebook allows the programmer to create notebook documents including live
code, interactive widgets, plots, equations, images etc. To code in Python using jupyter
notebook, search for jupyter notebook in windows search (at Start menu). Now, a browser
window will be opened similar to the one shown in Figure 1.2.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 5
Notes for Python Application Programming (Open Elective - 15CS664)
You can choose the working directory of your choice for storing your work. To open a
notebook for Python programming, click on New button at the right-side of the screen. Now
select Python 3 from the drop-down list. A new notebook (or workbook will be created as
shown in Figure 1.3. Type a command of your choice and press Ctrl+Enter to run that
command. One can give headings/subheadings etc for the commands being typed, store
the entire workbook for future reference etc. Readers are advised to try and experience
various options/menu’s available.
After understanding the basics of few editors of Python, let us start our communication with
Python, by saying Hello World. The Python uses print() function for displaying the contents.
Consider the following code –
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 6
Notes for Python Application Programming (Open Elective - 15CS664)
Once we are done with the program, we can close or terminate Python by giving quit()
command as shown –
A compiler translates the source code of high-level programming language into machine
level language. For this purpose, the source code must be a complete program stored in a
file (with extension, say, .java, .c, .cpp etc). The compiler generates executable files
(usually with extensions .exe, .dll etc) that are in machine language. Later, these
executable files are executed to give the output of the program.
On the other hand, interpreter performs the instructions directly, without requiring them to
be pre-compiled. Interpreter parses (syntactic analysis) the source code ant interprets it
immediately. Hence, every line of code can generate the output immediately, and the
source code as a complete set, need not be stored in a file. That is why, in the previous
section, the usage of single line print(“Hello World”) could able to generate the
output immediately.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 7
Notes for Python Application Programming (Open Elective - 15CS664)
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.
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 8
Notes for Python Application Programming (Open Elective - 15CS664)
Input: Every program may take some inputs from outside. The input may be through
keyboard, mouse, disk-file etc. or even through some sensors like microphone, GPS
etc.
Output: Purpose of a program itself is to find the solution to a problem. Hence,
every program must generate at least one output. Output may be displayed on a
monitor or can be stored in a file. Output of a program may even be a music/voice
message.
Sequential Execution: In general, the instructions in the program are sequentially
executed from the top.
Conditional Execution: In some situations, a set of instructions have to be
executed based on the truth-value of a variable or expression. Then conditional
constructs (like if) have to be used. If the condition is true, one set of instructions will
be executed and if the condition is false, the true-block is skipped.
Repeated Execution: Some of the problems require a set of instructions to be
repeated multiple times. Such statements can be written with the help of looping
structures like for, while etc.
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.
Note that, some of textbooks/authors refer logical and semantic error both as same,
as the distinction between these two is very small.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 9
Notes for Python Application Programming (Open Elective - 15CS664)
NOTE: There is one more type of error – runtime error, usually called as exceptions.
It may occur due to wrong input (like trying to divide a number by zero), problem in
database connectivity etc. When a run-time error occurs, the program throws some
error, which may not be understood by the normal user. And he/she may not
understand how to overcome such errors. Hence, suspicious lines of code have to
be treated by the programmer himself by the procedure known as exception
handling. Python provides mechanism for handling various possible exceptions like
ArithmeticError, FloatingpointError, EOFError, MemoryError etc. A brief idea about
exception handling is there in Section 1.3.7 later in this Module. For more details,
interested readers can go through the links –
https://docs.python.org/3/tutorial/errors.html and
https://docs.python.org/2/library/exceptions.html
>>> type("hello")
<class 'str'> #output
>>> type(3)
<class 'int'>
>>> type(10.5)
<class 'float'>
>>> type("15")
<class 'str'>
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.
1.2.2 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 you 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
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 10
Notes for Python Application Programming (Open Elective - 15CS664)
>>> 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.
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
1.2.4 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. Following are the examples of statements –
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 11
Notes for Python Application Programming (Open Elective - 15CS664)
Arithmetic Operators are used to perform basic operations as listed in Table 1.2.
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
>>> y//=2 #y=y//2
>>> print(y)
2 #only integer part will be printed
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
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 12
Notes for Python Application Programming (Open Elective - 15CS664)
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.
1.2.6 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.
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
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 13
Notes for Python Application Programming (Open Elective - 15CS664)
Addition and Subtraction are the least priority. Out of these two operations,
whichever appears first in the expression is evaluated.
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.
When input() function is used, the curser will be blinking to receive the data. For a better
understanding, it is better to have a prompt message for the user informing what needs to
be entered as input. The input() function itself can be used to do so, as shown below –
>>> str1=input("Enter a string: ")
Enter a string: Hello
>>> print("You have entered: ",str1)
You have entered: Hello
One can use new-line character \n in the function input() to make the cursor to appear in
the next line of prompt message –
>>> str1=input("Enter a string:\n")
Enter a string:
Hello #cursor is pushed here
The key-board input received using input() function is always treated as a string type. If you
need an integer, you need to convert it using the function int(). Observe the following
example –
>>> x=input("Enter x:")
Enter x:10 #x takes the value “10”, but not 10
>>> type(x) #So, type of x would be str
<class 'str'>
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 14
Notes for Python Application Programming (Open Elective - 15CS664)
A function float() is used to convert a valid value enclosed within quotes into float number
as shown below –
A function chr() is used to convert an integer input into equivalent ASCII character.
>>> a=int(input("Enter an integer:"))
Enter an integer:65
>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ",ch)
Character Equivalent of 65 is A
There are several such other utility functions in Python, which will be discussed later.
1.2.10 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.
Python (and all programming languages) ignores the text written as comment lines. They
are only for the programmer’s (or any reader’s) reference.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 15
Notes for Python Application Programming (Open Elective - 15CS664)
Ex1.
a=10000
b=0.3*a
c=a+b
print(c) #output is 13000
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.
1.2.12 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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 16
Notes for Python Application Programming (Open Elective - 15CS664)
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 17
Notes for Python Application Programming (Open Elective - 15CS664)
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.
NOTE:
1. Logical operators treat the operands as Boolean (True or False).
2. Python treats any non-zero number as True and zero as False.
3. 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.
4. 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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 18
Notes for Python Application Programming (Open Elective - 15CS664)
if condition:
Statement block False
condition?
True
Observe the colon symbol after condition. When the
condition is true, the Statement block will be Statement Block
executed. Otherwise, it is skipped. A set (block) of
statements to be executed under if is decided by the
indentation (tab space) given. Exit
Consider an example –
>>> x=10
>>> if x<40:
print("Fail") #observe indentation after if
Fail #output
Usually, the if conditions have a statement block. In any case, the programmer feels to do
nothing when the condition is true, the statement block can be skipped by just typing pass
statement as shown below –
>>> if x<0:
pass #do nothing when x is negative
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 19
Notes for Python Application Programming (Open Elective - 15CS664)
if condition:
Statement block -1
True False
else: Condition?
Statement block -2
Example:
x=int(input("Enter x:"))
if x%2==0:
print("x is even")
else:
print("x is odd")
Sample output:
Enter x: 13
x is odd
if condition1:
Statement Block-1
F
elif condition2: F F
Cond1 Cond2 Condn
Statement Block-2
|
| T T T
|
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 20
Notes for Python Application Programming (Open Elective - 15CS664)
Sample Output:
Enter marks: 78
First Class
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:
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 21
Notes for Python Application Programming (Open Elective - 15CS664)
Sample Output:
Enter gender: F
Enter age: 17
Girl, Not Eligible for Marriage
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
When you run the above code, one of the possible situations would be –
Enter a:12
Enter b:0
Traceback (most recent call last):
File "C:\Users\Chetana\Dropbox\PythonNotes\p1.py", line 154,
in <module>
c=a/b
ZeroDivisionError: division by zero
For the end-user, such type of system-generated error messages is difficult to handle. So
the code which is prone to runtime error must be executed conditionally within try block.
The try block contains the statements involving suspicious code and the except block
contains the possible remedy (or instructions to user informing what went wrong and what
could be the way to get out of it). If something goes wrong with the statements inside try
block, the except block will be executed. Otherwise, the except-block will be skipped.
Consider the example –
a=int(input("Enter a:"))
b=int(input("Enter b:"))
try:
c=a/b
print(c)
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 22
Notes for Python Application Programming (Open Elective - 15CS664)
except:
print("Division by zero is not possible")
Output:
Enter a:12
Enter b:0
Division by zero is not possible
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
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 23
Notes for Python Application Programming (Open Elective - 15CS664)
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)>2 is never reached and possible error is being prevented from happening.
1.3.9 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.
1.4 FUNCTIONS
Functions are the building blocks of any programming language. A sequence of instructions
intended to perform a specific independent task is known as a function. In this section, we
will discuss various types of built-in functions, user-defined functions, applications/uses of
functions etc.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 24
Notes for Python Application Programming (Open Elective - 15CS664)
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.
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 25
Notes for Python Application Programming (Open Elective - 15CS664)
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 and 1 (excluding 1). For example –
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 26
Notes for Python Application Programming (Open Elective - 15CS664)
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
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.
log10(): This function is used to find logarithm of the given argument, to the base
10.
>>> math.log10(2)
0.3010299956639812
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 27
Notes for Python Application Programming (Open Elective - 15CS664)
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
pow(): This function takes two arguments x and y, then finds x to the power of y.
>>> math.pow(3,4)
81.0
The first line in the function def fname(arg_list)is known as function header. 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()
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 28
Notes for Python Application Programming (Open Elective - 15CS664)
def myfun():
print("Hello")
Observe indentation print("Inside the function")
The function definition creates an object of type function. In the above example, myfun is
internally an object. This can be verified by using the statement –
>>>print(myfun) # myfun without parenthesis
<function myfun at 0x0219BFA8>
>>> type(myfun) # myfun without parenthesis
<class 'function'>
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
myfun is 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")
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 29
Notes for Python Application Programming (Open Elective - 15CS664)
Functions are meant for code-reusability. That is, a set of instructions written as a function
need not be repeated. Instead, they can be called multiple times whenever required.
Consider the enhanced version of previous program as below –
def myfun():
print("Inside myfun()")
Execution
starts here(1)
print("Example of function")
(6)
repeat()
(2)
print("Example over")
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 30
Notes for Python Application Programming (Open Elective - 15CS664)
the calling function. Consider an example of a function which takes a single argument as
below –
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 31
Notes for Python Application Programming (Open Elective - 15CS664)
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)
The sample output would be –
Enter a number:3
Enter another number:4
Sum of two numbers: 7
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.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 32
Notes for Python Application Programming (Open Elective - 15CS664)
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 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 –
>>> print("18","2","2018",sep='-')
18-2-2018
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="RNSIT"
>>> address="Channasandra"
>>> print(college, address, sep='@')
RNSIT@Channasandra
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
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 33
Notes for Python Application Programming (Open Elective - 15CS664)
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”)
In fact, when you just type print and open a parentheses in any Python IDE, the intelliSense
(the context-aware code completion feature of a programming language which helps the
programmer with certain suggestions using a pale-yellow box) of print() will show the
existence of sep and end arguments as below –
The above figure clearly indicates that the sep and end have the default values space and
new-line respectively.
(NOTE: You can see two more arguments file and flush here. The default value sys.stdout
of the argument file indicates that print() will send the data to standard output, which is
usually keyboard. When you are willing to print the data into a specific file, the file-object
can be given as a value for file argument. The flush argument with True value makes sure
that operations are successfully completed and the values are flushed into the memory
from the buffer. The default value of flush is False, because in most of the cases we need
not check whether the data is really got flushed or not – as it would be happening even
otherwise. While printing the data into a file (that is, when a file is open for write purpose),
we may need to make sure whether the data got flushed or not. Because, someone else in
the network trying to read the same file (trying to open a file for read purpose) when write
operation is under progress may result in file corruption. In such situations, we need to set
flush argument as True. Indeed, this is just a basic vague explanation of flush argument
and it has much more meaning in real.)
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org
This document can be downloaded from www.chetanahegde.in with most recent updates. 34
Notes for Python Application Programming (Open Elective - 15CS664)
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
>>> print("x=%0.4f, y=%0.2f"%(x,y))
x=6.6667, y=1.86 #observe rounding off digits
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@ieee.org