Unit-1 python
Unit-1 python
Nowadays, computational devices like personal computers, laptops, and cell phones are embedded with an
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 tend to 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 solve the required problem, one has to
feed the proper program to it. Hence, one should know how to write a program!!
Many programming languages 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, the complexity involved in implementing the algorithm
in that language, etc.
Operations specified by the program instructions. CPU will perform the given tasks with 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 direct access. Usually, the programs stored in the
secondary storage are brought into the 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 vanish
when the computer is turned off.
Figure 1.1 Computer Hardware Architecture
Secondary Memory: Secondary memory is the permanent storage of the 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. Keyboards,
mouse, monitor, printer, etc. are examples of I/O devices.
Network Connection: Nowadays, most computers are connected to the network and hence they can
communicate with other computers in a network. Retrieving the information from
other computers via the network will be slower compared to accessing the secondary memory. Moreover, the
network is not reliable always due to problems in connection.
The programmer has to use the above resources sensibly to solve the problem.
Usually, a programmer will be communicating with the CPU by telling it „what to do next‟. The usage of
main memory, secondary memory, and 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 a program.
Understanding Programming
A programmer must have the skills to look at the data/information available about a problem, analyze it, and
then 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.
The skill of implementing an idea: A programmer should be like a “storyteller”. That is, he must be capable
of conveying something effectively. He/she must be able to solve the problem by designing a suitable algorithm
and implementing it. And, the program must provide appropriate output as expected.
Thus, the art of programming requires knowledge about the problem‟s requirement and the strength/weakness
of the programming language chosen for the implementation. It is always advisable to choose an appropriate
programming language that can cater to the complexity of the problem to be solved.
The basic constructs of a programming language include a set of characters and keywords that it supports.
The keywords have special meanings in any language and they are intended for doing specific tasks. Python
has a finite set of keywords as given in the Table below.
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 Editors and Installing Python
Before getting into details of the programming language Python, it is better to learn how to install the
software.
Python is freely downloadable from the internet. There are multiple IDEs (Integrated Development
Environments) available for working with Python. Some of them are PyCharm, LiClipse, IDLE, etc.
When you install Python, the IDLE editor will be available automatically. Apart from all these editors, Python
programs can be run on a command prompt also.
One has to install a suitable IDE depending on their need and the Operating System they are using.
Because, there is a separate set of editors (IDE) available for different OS like Windows, UNIX, Ubuntu, Solaris,
Mac, etc. Basic Python can be downloaded from the link: https://www.python.org/downloads/
Python has a 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 that the readers 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 Jupiter notebook.
Conversing with Python
Once Python is installed, one can go ahead with working with Python.
After installing Python (or Anaconda distribution), if you just type „python‟ in the command prompt, you will
get the message as shown in Figure.
Figure: Python initialization in command prompt
The prompt >>> (usually called 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.
.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, the interpreter performs the instructions directly, without requiring them to be pre-
compiled. The interpreter parses (syntactic analysis) the source code and 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.
Consider an example of adding two numbers –
>>> x=10
>>> y=20
>>> z= x+y
>>> print(z)
30
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 is logically related, though they look independent.
NOTE that, Python does 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 a number, string, etc) of the value
being assigned, the type and behavior of the variable name are judged by Python.
Writing a Program
As Python is interpreted language, one can keep typing every line of code one after the other (and
immediately get the output of each line) as shown in the previous section
. But, in a real-time scenario, typing a big program is not a good idea. It is not easy to logically debug such
lines.
Hence, Python programs can be stored in a file with the extension .py and then can be run using the python
command.
Programs written within a file are reusable and can be run whenever we want. Also, they are transferrable
from one machine to another machine via pen drive, CD, etc.
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 time, the program is a generic solution. Hence, the same program may be used to count
the frequency of words in another file.
A person who does not know anything about 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.
The Building Blocks of Programs
There are certain low-level conceptual structures to construct a program in any programming language.
They are called as building-blocks of a program and are listed below –
Input: Every program may take some inputs from outside. The input may be through the keyboard, mouse,
disk file, etc., or even through some sensors like microphone, GPS, etc.
Output: The 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. The 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 a thorough understanding of the above constructs and using them legibly.
What Could Possibly Go Wrong?
One can do mistakes while writing a program. The possible mistakes are categorized below –
Syntax Errors: The statements which do not follow the grammar (or syntax) of the programming language
tend to result in syntax errors. Python is a case-sensitive language. Hence, there is a chance that a beginner may
do some syntactical mistakes while writing a program. The lines involving such mistakes are encountered by
Python when you run the program and the errors are thrown by specifying possible reasons for the error. The
programmer has to correct them and then proceed further.
Logical Errors: Logical error occurs due to a poor understanding of the problem. Syntactically, the program
will be correct. But, it may not give the expected output. For example, you intended to find a%b, but, by mistake,
you have typed a/b. Then it is a logical error.
Semantic Errors: A semantic error may happen due to the wrong use of variables, wrong operations, or the
wrong order. For example, trying to modify un-initialized variables, etc.
NOTE: There is one more type of error – runtime error, usually called exceptions. It may occur due to wrong
input (like trying to divide a number by zero), problems 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 a mechanism for handling various
possible exceptions like Arithmetic Errors, Floating point Error, EOF Error, Memory Error, etc
VARIABLES, EXPRESSIONS & STATEMENTS
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.
Values and Types
A value is one of the basic things a program works with.
Each value in Python has a type. Type 2 is an integer; type 10.5 is a floating point number; “Hello” is a string
etc.
The type of a value can be checked using the type function as shown below –
>>> type("hello")
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(10.5)
<class 'float'>
>>> type("15")
<class 'str'>
In the above four examples, one can make out various types of str, int, and float.
Observe the 4th example – it indicates that whatever is 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 the 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.
>>> 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 the above examples that the value assigned to the variable determines the type of that
variable.
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, the variable name sum is different from SUM, Sum, etc.
Examples:
>>> 3a=5 #starting with a number
Syntax Error: invalid syntax
>>> a$=10 #contains $
Syntax Error: invalid syntax
>>> if=15 #if is a keyword
Syntax Error: invalid syntax
Statements
A statement is a small unit of code that can be executed by the Python interpreter.
Two kinds of statements are: print being an expression statement and an assignment statement
An operator may work on a single operand (unary operator) or two operands (binary operator).
There are several types of operators like arithmetic operators, relational operators, logical operators, etc. in
Python.
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 the 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 the 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
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. The working procedure of these operators is the 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.
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 a 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 has the highest precedence in any expression. The operations within the 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 other operators which are evaluated
from left to right).
For example,
>>> print(2**3) #It is 23 8
>>> print(2**3**2) #It is 512 i.e., 232
Multiplication and Division are the next priority. Out of these two operations, whichever
String Operations
String concatenation can be done using the + 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 the value
of x( a string “32”). Hence the result would be “3245” and its type would be a string.
NOTE: One can use single quotes to enclose a string value, instead of double quotes.
Asking the User for Input
Python uses the built-in function input() to read the data from the keyboard.
When this function is invoked, the user input is expected. The input is read till the user presses enter- key.
For example:
>>> str1=input()
Hello, how are you? #user input
>>> print(“String is “,str1)
String is Hello how are you? #printing str1
When the input() function is used, the cursor 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.
If you need an integer, you need to convert it using the function int(). Observe the following example –
A function chr() is used to convert an integer input into an equivalent ASCII character.
>>> a=int(input("Enter an integer:")) Enter an integer:65
>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ", ch)
The character Equivalent of 65 is A
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.
They are only for the programmer‟s (or any reader‟s) reference.
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 the 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 Python editors have a mechanism to show keywords in a different color. Hence, the
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 the
errors. Some of the examples are given here –
CONDITIONAL EXECUTION
In general, the statements in a program will be executed sequentially.
Boolean Expressions
A Boolean Expression is an expression that results in True or False.
The True and False are special values that belong to class bool.
>>> 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 look the 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 and is not does the identity test. That is, they will compare whether two objects are the
same. Usually, two objects are the same when their memory locations are the 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:
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 the case of or operator, if the first operand is True, the second operand is not evaluated. Because True or’ed
with anything is True.
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 the pass statement as shown below –
>>> if x<0:
pass #do nothing when x is negative
Alternative Execution
A second form of the 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 given below –
As the condition will be either true or false, only one among Statement block-1 and Statement block- 2 will be
get executed. These two alternatives are known as branches.
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
Nested Conditionals
The conditional statements can be nested.
That is, one set of conditional statements can be nested inside the other.
That means we may have more than one branch. This is solved with the help of chained conditionals.
The syntax and flowchart are given below
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.
Example: marks=float(input("Enter marks:")) if marks >= 80:
print("First Class with Distinction") elif marks >= 60 and marks < 80:
print("First Class")
elif marks >= 50 and marks < 60: print("Second Class")
elif marks >= 35 and marks < 50: print("Third Class")
else:
print("Fail")
Sample Output:
Enter marks: 78
First Class
Catching Exceptions using try and except
As discussed there is a chance of runtime error while doing some programs.
Enter b:0
Traceback (most recent call last): 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 the try block.
The try block contains the statements involving suspicious code and the except block contains the possible
remedy (or instructions to the user informing what went wrong and what could be the way to get out of it).
If something goes wrong with the statements inside the try block, the except block will be executed.
a=int(input("Enter a:"))
b=int(input("Enter b:")) try:
c=a/b print(c)
except:
print("Division by zero is not possible")
Output:
Enter a:12 Enter b:0
Division by zero is not possible
Handling an exception using a try is called catching an exception.
In general, catching an exception gives the programmer the to fix the probable problem, try again, or at least
end the program gracefully.
x= 10 y=20
if x<10 and x+y>25: #do something
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 computational time but also leads to a technique known as the guardian
pattern.
Consider the 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 the logical expression itself was
False, and hence by applying short-circuit rule, the remaining part was not executed at all.
Whereas, in the statements x>=2 and (x/y)>2, the first half is True, and the second half results in a 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 False. Hence, the expression (x/y)> 2 is never reached and
possible error is being prevented from happening.
Debugging
One can observe from the previous few examples that when a runtime error occurs, it displays a term
For example –
>>> x=10
>>> y=15
SyntaxError: unexpected indent
The error here is because of the 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 the previous line of code.
FUNCTIONS
Functions are the building blocks of any programming language.
In this section, we will discuss various types of built-in functions, user-defined functions, applications/uses of
functions, etc.
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 the
required task.
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.
max(): This function is used to find the maximum value among the arguments. It can be used for numeric
values or even for strings.
> max(10, 20, 14, 12) #maximum of 4 integers
20
> max("hello world")
10
> min("hello world")
18
There are many other built-in functions available in Python. They are discussed in further Modules, wherever
they are relevant.
Type Conversion Functions
As we have seen earlier (while discussing the input() function), the type of the variable/value can be
converted using functions int(), float(), and str().
Python provides built-in functions that convert values from one type to another
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 scenarios.
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 pseudorandom 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 into 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 –
import random #module random is imported
print(random.random()) #random() function is invoked
0.7430852580883088 #a random number generated
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 the module name and function name. Observe the parentheses while referring to a function
name).
To use these functions, the math module has to be imported into the code.
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
pi: The constant value pi can be used directly whenever we require it.
>>>print (math.pi)
3.141592653589793
log10(): This function is used to find the logarithm of the given argument, to the base 10.
>>> math.log10(2)
0.3010299956639812
log(): This is used to compute the natural logarithm (base e) of a given number.
>>> math.log(2)
0.6931471805599453
sin(): As the name suggests, it is used to find the 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
cos(): Used to find cosine value –
>>>math.cos(45*math.pi/180) 0.7071067811865476
tan(): Function to find the tangent of an angle, given as an argument.
>>> math.tan(45*math.pi/180)
0.9999999999999999
pow(): This function takes two arguments x and y, then finds x to the power of y.
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
Here def is a keyword indicating it as a function definition.
The first line in the function def fname(arg_list)is known as the function header/definition. The remaining
lines constitute a 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.
Hello
Inside the function Example over
The function definition creates an object of type function.
print("Example of function")
myfun() #function call before definition print("Example over")
def myfun(): #function definition is here print("Hello")
print("Inside the function")
The above code would generate an error saying NameError: name 'myfun' is not defined
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 the previous program as below –
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 to the repeat()
function. The statement print(“Inside repeat()”) is executed.
Once again there is a call for the 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 the program is terminated.
The argument is 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 operations on arguments while passing them to a
function. Consider the modified version of the above program –
The output would be –
Example of function with arguments Inside.
test()
Argument is hellohellohello #observe repetition Inside
test()
Argument is 60 #observe multiplication
Over!!
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 multiplied
by 3.
Fruitful Functions and void Functions
A function that performs some task, but does not return any value to the calling function is known as
a void function. The examples of user-defined functions considered till now are void functions.
The function which returns some result to the calling function after performing a task is known as a fruitful
function. The built-in functions like mathematical functions, random number generating functions, etc. that have
been considered earlier are examples of fruitful functions.
One can write a user-defined function to return a value to the calling function as shown in the following
example –
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 a string, instead it is of the type class
'NoneTypeK'. This type of object indicates no value.
Why Functions?
Functions are an essential part of programming because of the following reasons –
Creating a new function allows the programmer 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 in 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 to the original problem.
Well-designed functions are often useful for many programs. The functions written once for a specific purpose
can be reused in any other program.
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 indicate 1-digit space, 2-digit space, etc. on the output screen.
Ex3: One can use the % symbol to have the required number of spaces for a variable. This will be useful in
printing floating-point numbers.
>>> x=19/3
>>> print(x)
6.333333333333333 #observe the number of digits after the 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