Module I
Module I
MODULE I
1
Introduction to Python Programming Module-1
➢ The computer system involves some of the important parts as shown in Figure
What
Next?
Software
Main Secondary
Memory Memory
➢ Central Processing Unit (CPU): It performs basic arithmetic, logical, control and
I/O 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.
➢ 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.
2
Introduction to Python Programming Module-1
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.
3
Introduction to Python Programming Module-1
➢ Variables are the name given for memory locations to store the values in it.
➢ Unlike many other programming languages, a variable in Python need not be declared before
it’s use.
➢ Variables are declared with the assignment operator, “=”.
➢ In Python, variables are created when you assign a value to it.
➢ Python is dynamically typed, meaning that variables can be assigned without declaring their
type, and that their type can change. Values can come from constants, from computation
involving values of other variables, or from the output of a function.
➢ Creating and using Variables in Python
>>> x=5
>>> y="Hello, World!"
>>> x = 3
>>> x
3
Here we define a variable and sets the value equal to 3 and then print the result to the screen.
➢ Later, if you change the value of x and use it again, the new value will be substituted instead:
>>> x = 1000
>>> x
1000
➢ Python also allows chained assignment, which makes it possible to assign the same value to
several variables simultaneously:
>>> a = b = c = 300
>>> print(a, b, c)
300 300 300
The chained assignment above assigns 300 to the variables a, b, and c simultaneously.
➢ A variable can have a short name (like x and y) or a more descriptive name (sum, amount, etc).
➢ Here are some basic rules for Python variables:
➢ A variable name must start with a letter or the underscore character
➢ A variable name cannot start with a number
➢ A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores
➢ Variable names are case-sensitive, e.g., amount, Amount and AMOUNT are three
different variables.
4
Introduction to Python Programming Module-1
➢ One has to install suitable IDE depending on their need and the Operating System they are
using. 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 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.
5
Introduction to Python Programming Module-1
➢ 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
isready 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
asshown –
>>> quit() #Python terminates
6
Introduction to Python Programming Module-1
NOTE: 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
7
Introduction to Python Programming Module-1
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 immediately getting the output of each line) as shown in previous section. But, in real-time scenario,
typing a big program is not a good idea. It is not easy to logically debugsuch lines. Hence, Python
programs can be stored in a file with extension .py and then can be run using python command.
➢ Programs written within a file are obviously reusable and can be run whenever we want. Also,
theyare transferrable from one machine to other machine via pen-drive, CD etc.
What is a Program?
➢ A program is a sequence of instructions intended to do some tasks.
➢ For example, if we need to count the number of occurrences of each word in a text document,
wecan 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
beused 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
countthe 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.
8
Introduction to Python Programming Module-1
NOTE: There is one more type of error – runtime error, usually called as exceptions. It may occur
dueto 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
9
Introduction to Python Programming Module-1
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
10
Introduction to Python Programming Module-1
Statement in Python
➢ A statement is an instruction that a Python interpreter can execute. So, in simple words, we can
say anything written in Python is a statement.
11
Introduction to Python Programming Module-1
➢ Python statement ends with the token NEWLINE character. It means each line in a Python script
is a statement.
➢ For example, a = 10 is an assignment statement. where a is a variable name and 10 is its value.
There are other kinds of statements such as if statement, for statement, while statement, etc., we
will learn them in the following lessons.
➢ There are mainly four types of statements in Python:
o Print statements
o Assignment statements
o Conditional statements
o Looping statements.
Example:
# statement 1
print('Hello')
# statement 2
x = 20
# statement 3
print(x)
➢ As you can see, we have used three statements in our program. Also, we have added
the comments in our code. In Python, we use the hash (#) symbol to start writing a
comment. In Python, comments describe what code is doing so other people can understand
it.
➢ We can add multiple statements on a single line separated by semicolons, as follows:
Multi-Line Statements
Python statement ends with the token NEWLINE character. But we can extend the statement over
multiple lines using line continuation character (\). This is known as an explicit continuation.
12
Introduction to Python Programming Module-1
Example
addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
print(addition)
# Output: 280
Comment in Python
➢ The comments are descriptions that help programmers to understand the functionality of the
program. Thus, comments are necessary while writing code in Python.
➢ In Python, we use the hash (#) symbol to start writing a comment. The comment begins with a
hash sign (#) and whitespace character and continues to the end of the line.
➢ In a team, many programmers work together on a single application. Therefore, if you are
developing new code or modifying the existing application’s code, it is essential to describe the
purpose behind your code using comments.
➢ For example, if you have added new functions or classes in the source code, describe them. It helps
other colleagues understand the purpose of your code and also helps in code review.
➢ Apart from this, In the future, it helps to find and fix the errors, improve the code later on, and
reuse it in many different applications.
➢ Writing comments is considered a good practice and required for code quality.
➢ If a comment is found while executing a script, the Python interpreter completely ignores it and
moves to the next line.
#This is the program to add two numbers
x = 10
y = 20
# adding two numbers
z = x + y
print('Sum:', z)
# Output 30
➢ In python, there is no unique way to write multi-line comments. We can use multi-line strings
(triple quotes) to write multi-line comments. The quotation character can either be ‘ or “. Python
interpreter ignores the string literals that are not assigned to a variable.
13
Introduction to Python Programming Module-1
'''
I am a
multiline comment!
'''
print("Welcome to python programming..")
Variables
➢ A variable is a reserved memory area (memory address) to store value.
For example, we want to store an employee’s salary. In such a case, we can create a variable
and store salary using it.
>>> salary=50000
Using that variable name salary, you can read or modify the salary amount.
➢ In other words, a variable is a value that varies according to the condition or input pass to the
program. Everything in Python is treated as an object so every variable is nothing but an object in
Python.
➢ A variable can be either mutable or immutable.
o If the variable’s value can change, the object is called mutable.
o if the value cannot change, the object is called immutable.
Creating a variable
Python programming language is dynamically typed, so there is no need to declare a
variable before using it or declare the data type of variable like in other programming languages. The
declaration happens automatically when we assign a value to the variable.
Creating a variable and assigning a value
➢ We can assign a value to the variable at that time variable is created. We can use the assignment
operator (=) to assign a value to a variable.
➢ The operand, which is on the left side of the assignment operator, is a variable name. And the
operand, which is the right side of the assignment operator, is the variable’s value.
variable_name = variable_value
Example:
14
Introduction to Python Programming Module-1
In the above example, “John”, 25, 25800.60 are values that are assigned to name, age, and salary
respectively.
Multiple assignments
➢ In Python, there is no restriction to declare a variable before using it in the program. Python allows
us to create a variable as and when required.
15
Introduction to Python Programming Module-1
➢ We can do multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables.
➢ we can assign a single value to multiple variables simultaneously using the assignment operator =.
Now, let’s create an example to assign the single value 10 to all three variables a, b, and c.
a = b = c = 10
print(a) # 10
print(b) # 10
print(c) # 10
Delete a variable
Use the del keyword to delete the variable. Once we delete the variable, it will not be longer
accessible and eligible for the garbage collector.
Example
var1 = 100
print(var1) # 100
#delete var1 and try to access it again
del var1
print(var1)
NameError: name 'var1' is not defined
16
Introduction to Python Programming Module-1
➢ It returns the same address location because both variables share the same value. But if we assign
m to some different value, it points to a different object with a different identity.
Example:
17
Introduction to Python Programming Module-1
m = 500
n = 400
print("Memory address of m:", id(m)) # 1686681059984
print("Memory address of n:", id(n)) # 1686681059824
For m = 500, Python created an integer object with the value 500 and set m as a reference to it.
Similarly, n is assigned to an integer object with the value 400 and sets n as a reference to it. Both
variables have different identities.
Object Reference
➢ In Python, when we assign a value to a variable, we create an object and reference it.
➢ For example, a=10, here, an object with the value 10 is created in memory, and reference a now
points to the memory address where the object is stored.
➢ Suppose we created a=10, b=10, and c=10, the value of the three variables is the same. Instead of
creating three objects, Python creates only one object as 10 with references such as a,b,c.
➢ We can access the memory addresses of these variables using the id() method. a, b refers to the
same address in memory, and c, d, e refers to the same address. See the following example for
more details.
a = 10
b = 10
print(id(a))
print(id(b))
c = 20
d = 20
e = 20
print(id(c))
print(id(d))
print(id(e))
Output:
140722211837248
140722211837248
140722211837568
140722211837568
140722211837568
18
Introduction to Python Programming Module-1
➢ Here, an object in memory initialized with the value 10 and reference added to it, the reference
count increments by ‘1’.
➢ When Python executes the next statement that is b=10, since it is the same value 10, a new object
will not be created because the same object in memory with value 10 available, so it has created
another reference, b. Now, the reference count for value 10 is ‘2’.
➢ Again for c=20, a new object is created with reference ‘c’ since it has a unique value (20).
Similarly, for d, and e new objects will not be created because the object ’20’ already available.
Now, only the reference count will be incremented.
➢ We can check the reference counts of every object by using the getrefcount function of a sys
module. This function takes the object as an input and returns the number of references.
➢ We can pass variable, name, value, function, class as an input to getrefcount() and in return, it
will give a reference count for a given object.
import sys
print(sys.getrefcount(a))
print(sys.getrefcount(c))
In the above picture, a, b pointing to the same memory address location (i.e., 140722211837248), and
c, d, e pointing to the same memory address (i.e., 140722211837568 ). So reference count will be 2
and 3 respectively.
Python Keywords
➢ Python keywords are reserved words that have a special meaning associated with them and
can’t be used for anything but those specific purposes. Each keyword is designed to achieve
specific functionality.
19
Introduction to Python Programming Module-1
import keyword
print(keyword.kwlist)
Output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async',
'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
o help() function: Apart from a keyword module, we can use the help() function to get the list
of keywords.
import keyword
print(keyword.iskeyword('if')) # True
print(keyword.iskeyword('range')) # False
20
Introduction to Python Programming Module-1
21
Introduction to Python Programming Module-1
22
Introduction to Python Programming Module-1
print(x) # (9+8j)
print(y) # (10+4.5j)
print(z) # (11.2+1.2j)
➢ complex() function takes real part and imaginary part as arguments respectively.
➢ While assigning the actual complex number to a variable, we have to mention j next to the
imaginary part to tell Python that this is the imaginary part.
cn = complex(5,6)
23
Introduction to Python Programming Module-1
print(cn)
(5+6j)
➢ We can access the real part and imaginary part separately using dot operator.
o real property of the complex number returns real part.
o imag property of the complex number returns imaginary part.\
Example:
cn = complex(5, 6)
print(‘Given Complex Number:’,cn)
print('Real part is :',cn.real)
print('Imaginary part is :',cn.imag)
Output:
Given Complex Number: (5+6j)
Real part is: 5.0
Imaginary part is: 6.0
# display string
print(platform) # ' Computing'
24
Introduction to Python Programming Module-1
Python Operators
➢ Operators are special symbols that perform specific operations on one or more operands (values)
and then return a result.
➢ For example, you can calculate the sum of two numbers using an addition (+) operator.
➢ The following image shows operator and operands
➢ Python has seven types of operators that we can use to perform different operation and produce a
result.
o Arithmetic operator
o Relational operators
o Logical operators
o Assignment operators
o Bitwise operators
o Membership operators
o Identity operators
Arithmetic operator
➢ The operators which are used to perform arithmetic operations like addition, subtraction, division
etc. They are: +, -, *, /, %, **, //
➢ Division operator / always performs floating-point arithmetic, so it returns a float value.
➢ Floor division (//) can perform both floating-point and integer-
o If values are int type, the result is int type.
o If at least one value is float type, then the result is of float type.
25
Introduction to Python Programming Module-1
# Arithmetic operators
x = 15
y = 4
print('x + y =',x+y) # Output: x + y = 19
Relational Operators
➢ The operators which are used to check for some relation like greater than or less than etc..
between operands are called relational operators. They are: <, >, <=, >=, ==, !=
➢ Relational operators are used to compare the value of operands (expressions) to produce a logical
value. A logical value is either True or False.
26
Introduction to Python Programming Module-1
# Comparison operators
x = 10
y = 12
print('x > y is',x>y) # Output: x > y is False
print('x < y is',x<y) # Output: x < y is True
print('x == y is',x==y) # Output: x == y is False
print('x != y is',x!=y) # Output: x != y is True
print('x >= y is',x>=y) # Output: x >= y is False
print('x <= y is',x<=y) # Output: x <= y is True
Logical Operators
➢ The operators which do some logical operation on the operands and return True or False are
called logical operators. The logical operations can be ‘AND’, ‘OR’ etc.
➢ Logical operators are used to connect two or more relational operations to form a complex
expression called logical expression.
➢ A value obtained by evaluating a logical expression is always logical, i.e. either True or False.
27
Introduction to Python Programming Module-1
# Logical operators
x = True
y = False
print('x and y is',x and y) # Output: x and y is False
print('x or y is',x or y) # Output: x or y is True
print('not x is',not x) # Output: not x is False
Assignment Operators
➢ The operators which are used for assigning values to variables. ‘=’ is the assignment operator.
➢ Assignment operators are used to perform arithmetic operations while assigning a value to a
variable.
28
Introduction to Python Programming Module-1
# Assignment operators
x = 15
x+=5
print('x+=',x) # Output: x += 20
x-=3
print('x–=',x) # Output: x -= 17
x*=2
print('x*=',x) # Output: x *= 34
x/=5
print('x/=',x) # Output: x /= 6.8
x//=2
print('x//=',x) # Output: x//= 3
x**=2
print('x**=',x) # Output: x**= 9
Bitwise operators
➢ Bitwise operators are used to perform operations at binary digit level.
➢ These operators are not commonly used and are used only in special applications where optimized
use of storage is required.
29
Introduction to Python Programming Module-1
Bitwise OR ( | )
Bitwise XOR ( ^ )
Bitwise NOT ( ~ )
30
Introduction to Python Programming Module-1
Membership Operators
➢ The membership operators are useful to test for membership in a sequence such as string, lists,
tuples and dictionaries.
➢ There are two type of Membership operator:-
➢ in
➢ not in
1. in Operators
➢ This operators is used to find an element in the specified sequence.
➢ It returns True if element is found in the specified sequence else it returns False.
Examples:-
st1 = “Welcome to Python Class”
“to” in st1 #output: True
st2 = “Welcome to Python Class”
“come” in st2 #output: True
st3 = “Welcome to Python Class”
“java” in st3 #output: False
2. not in Operators
31
Introduction to Python Programming Module-1
Identity Operators
➢ This operator compares the memory location(address) to two elements or variables or objects.
➢ With these operators, we will be able to know whether the two objects are pointing to the same
location or not.
➢ The memory location of the object can be seen using the id() function.
Example:
a = 25
b = 25
print(id(a))
print(id(b))
Output:
10105856
10105856
➢ There are two identity operators in python,
o is
o is not.
is:
• A is B returns True, if both A and B are pointing to the same address.
• A is B returns False, if both A and B are not pointing to the same address.
is not:
• A is not B returns True, if both A and B are not pointing to the same object.
• A is not B returns False, if both A and B are pointing to the same object.
Example:
a = 25
b = 25
print(a is b) #output: True
print(a is not b) #output: False
32
Introduction to Python Programming Module-1
2 ** Exponent
8 ^ Bitwise XOR
9 | Bitwise OR
14 (Lowest) or Logical OR
Python Operators Precedence
Expressions in Python
➢ A combination of values, variables and operators is known as expression.
Examples:
x=5
y=x+10
z= x-y*3
33
Introduction to Python Programming Module-1
➢ 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
>>> (10 - 4) * 2 +(10+2)
24
➢ What is the output of the following:
i) a = 21
b = 13
c = 40
d = 37
p = (a - b) <= (c + d)
print(p)
Output: True
ii) a, b = 10, 20
print(a == b or a < b and a != b)
Output: True
Output: 116
iv) x = 10
y = 50
res= x ** 2 > 100 and y < 100
print(x, y, res)
Output: 10 50 False
34
Introduction to Python Programming Module-1
35
Introduction to Python Programming Module-1
Output:
type of a: <class 'int'>
type of b: <class 'float'>
SUM= 10.0
type of c: <class 'float'>
PRODUCT= 21.0
type of d: <class 'float'>
b=7
q= float(b)
print(“value of b is :”,b)
print(“value of q is :”,q)
print("The type of 'b' is ",type(b))
print("The type of 'q' is",type(q))
Output:
value of a is : 10.6
value of p is : 10
The type of 'a' is <class 'float'>
The type of 'p' is <class 'int'>
value of b is : 7
value of q is : 7.0
The type of 'b' is <class 'int'>
The type of 'q' is <class 'float'>
36
Introduction to Python Programming Module-1
Output:
value of a is : 10
The type of 'a' is <class 'int'>
value of a is : 10
The type of 'p' is <class 'str'>
value of b is : 8
The type of 'b' is <class 'str'>
value of q is : 8
The type of 'q' is <class 'int'>
value of c is : 7.9
The type of 'c' is <class 'str'>
value of r is : 7.9
The type of 'r' is <class 'float'>
37
Introduction to Python Programming Module-1
>>> int(-5.6)
-5
38
Introduction to Python Programming Module-1
Separating Items
➢ If we want to print multiple items but do not want space to be the separator, we can pass the
separator string as an argument to print() as shown in the examples below. The separator string
can be a single character, or multiple characters or even a null string to indicate that we don't want
any separator between the items.
>>> print("hello","world",sep=',')
hello,world
39
Introduction to Python Programming Module-1
Terminating Items
➢ By default, the print() function prints a newline character (\n) after printing all the items. If we
choose, we can control this too using the keyword argument end as shown in the examples below.
Either we can end up printing any suffix string of our choice, or more practically, remove the
newline so that multiple print() functions end up producing their output on the same line.
>>> print("Python","is","a","dynamic","language",end="\n\t\t
Python\n")
Python is a dynamic language
--Python
>>> print("Hello","world",end="\n\n\n\n")
Hello world
>>> print("2+3=",2+3,end="")
2+3= 5>>>
40
Introduction to Python Programming Module-1
➢ Make use of the placeholders for substituting values. The format() function can receive multiple
arguments which are implicitly numbered from 0. These argument values can be accessed and
substituted in the string wherever placeholders are present. The placeholder can specify which
argument is to be substituted by identifying the argument number as shown in the example below:
>>> print('{0} {1}'.format('Hello','world'))
'Hello world'
>>> print(‘Name:{0} \n Mob_Number:{1}’.format(‘Harsha’,123456))
Name: Harsha
Mob_Number: 123456
41
Introduction to Python Programming Module-1
➢ A function float() is used to convert a valid value enclosed within quotes into float number as
shown below –
>>> f=input("Enter a float value:")
Enter a float value: 3.5
>>> type(f)
<class 'str'> #f is actually a string “3.5”
>>> f=float(f) #converting “3.5” into float value 3.5
>>> type(f)
<class 'float'>
➢ 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 {} is {}".format(a,ch))
Character Equivalent of 65 is A
42
Introduction to Python Programming Module-1
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.
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.
>>> max(10, 20, 14, 12) #maximum of 4 integers
20
>>> max("hello world")
'w' #character having maximum ASCII code
>>> max(3.5, -2.1, 4.8, 15.3, 0.2)
15.3 #maximum of 5 floating point values
43
Introduction to Python Programming Module-1
➢ len(): This function takes a single argument and finds its length. The argument can be a
string, list, tuple etc.
>>> len(“hello how are you?”)
18
➢ abs(): This function is used to return the absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer
and floating-point number. If the argument is a complex number, then, abs() returns its
magnitude.
>>> abs(-25)
25
>>> abs(-45.33)
45.33
➢ divmod(x,y): This method takes two numbers as arguments and returns their quotient and
remainder in a tuple.
>>> divmod(10,3)
(3,1) # A tuple containing the quotient and remainder after
integer division.
44
Introduction to Python Programming Module-1
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
45
Introduction to Python Programming Module-1
>>> 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
➢ pow(): This function takes two arguments x and y, then finds x to the power of y.
>>> math.pow(3,4)
81.0
➢ ceil(x): Return the ceiling of x, the smallest integer greater than or equal to x. It returns
an Integral value.
>>> math.ceil(5.4)
6
>>> math.ceil(-5.4)
-5
➢ floor(x): Return the ceiling of x, the largest integer less than or equal to x. It returns an
Integral value.
>>> math.floor(5.4)
5
>>> math.floor(-5.4)
-6
46
Introduction to Python Programming Module-1
47
Introduction to Python Programming Module-1
Examples:
1. Calculate the difference between a day temperature and a night temperature, as might be seen on
a weather report (a warm weather system moved in overnight).
>>> day_temperature = 3
>>> night_temperature = 10
>>> result=abs(day_temperature - night_temperature)
>>> print(“Temperature difference is “, result)
Temperature difference is 7
In this call on function abs, the argument is day_temperature - night_temperature. Because
day_temperature refers to 3 and night_temperature refers to 10, Python evaluates this expression
to -7. This value is then passed to function abs, which then returns the value 7.
48
Introduction to Python Programming Module-1
Examples:
>>> abs(-7) + abs(3.3)
10.3
>>> pow(abs(-2), round(4.3))
16
Python sees the call on pow and starts by evaluating the arguments from left to right. The first
argument is a call on function abs, so Python executes it. abs(-2) produces 2, so that’s the first value
for the call on pow. Then Python executes round(4.3), which produces 4.
Now that the arguments to the call on function pow have been evaluated, Python finishes calling
pow, sending in 2 and 4 as the argument values. That means that pow(abs(-2), round(4.3)) is
equivalent to pow(2, 4), and 24 is 16.
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
o Here def is a keyword indicating it as a function definition.
o fname is any valid name given to the function
o arg_list is list of arguments taken by a function. These are treated as inputs to the function
from the position of function call. There may be zero or more arguments to a function.
statements are the list of instructions to perform required task. return is a keyword used to
return the output value. This statement is optional
o The first line in the function def fname(arg_list) is known as function header/definition. The
remaining lines constitute function body.
o The function header is terminated by a colon and the function body must be indented.
o To come out of the function, indentation must be terminated.
o Unlike few other programming languages like C, C++ etc, there is no main() function or
49
Introduction to Python Programming Module-1
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.
➢ 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")
50
Introduction to Python Programming Module-1
➢ 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.
51
Introduction to Python Programming Module-1
Example-2
➢ A function that performs some tasks, but do not return any value to the calling function is known
as void function.
def sum(a,b):
s=sum(x,y)
print("Sum of two numbers:",s)
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
sum(x,y)
➢ The function which returns some result to the calling function after performing a task is known as
fruitful function. The built-in functions like mathematical functions, random number generating
functions etc. are the fruitful functions.
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)
52
Introduction to Python Programming Module-1
53