0% found this document useful (0 votes)
24 views53 pages

Module I

The document introduces programming and Python. It discusses why we should learn to program, computer hardware, understanding programming concepts like variables, and basic Python syntax. Programming requires solving problems through logical thinking and choosing the right language. A programmer must understand a problem and implement a suitable algorithm to get the expected output.

Uploaded by

sumanthcm.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views53 pages

Module I

The document introduces programming and Python. It discusses why we should learn to program, computer hardware, understanding programming concepts like variables, and basic Python syntax. Programming requires solving problems through logical thinking and choosing the right language. A programmer must understand a problem and implement a suitable algorithm to get the expected output.

Uploaded by

sumanthcm.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Introduction to Python Programming Module-1

MODULE I

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 tending 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
requiredproblem, 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.

Creativity and Motivation


➢ When a person starts programming, he himself will be both the programmer and the end- user.
Because, he will be learning to solve the problems. But, later, he may become a proficient
programmer. A programmer should have logical thinking ability to solve a given problem.
He/she should be creative in analyzing the given problems,finding the possible solutions,
optimizing the resources available and delivering the best possible results to the end-user.
➢ Motivation behind programming may be a job-requirement and such other prospects. But the
programmer should follow certain ethics in delivering the best possible output to his/her clients.
➢ The responsibilities of a programmer include developing a feasible, user-friendly software with
very less or no hassles.
➢ The user is expected to have only the abstract knowledge about the working of software, but not
the implementation details. Hence, the programmer should strive hard towards developing most
effective software.
Computer Hardware Architecture
➢ To understand the art programming, it is better to know the basic architecture of computer
hardware.

1
Introduction to Python Programming Module-1

➢ The computer system involves some of the important parts as shown in Figure

What
Next?
Software

Input and Output Central


Devices Processing Unit

Main Secondary
Memory Memory

Figure 1.1 Computer Hardware Architecture

➢ 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.

➢ Secondary Memory: The secondary memory is the permanent storage of computer.


Usually, the size of secondary memory will be considerably larger than that of main
memory. Hard disk,USB drive etc., can be considered as secondary memory storage.

➢ I/O Devices: These are the medium of communication between the user and the computer.
Keyboard, mouse, monitor, printer etc. are the examples of I/O devices.

➢ Network Connection: Nowadays, most of the computers are connected to network and
hence they can communicate with other computers in a network. Retrieving the
information from other computers via network will be slower compared to accessing the
secondary memory. Moreover, network is not reliable always due to problem in
connection.

➢ The programmer has to use above resources sensibly to solve the problem.

➢ Usually, a programmer will be communicating with CPU by telling it “What to do next”.


The usage of main memory, secondary memory, I/O devices also can be controlled by the

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.

Words and Sentences


➢ Every programming language has its own constructs to form syntax of the language.
➢ Basic constructs of a programming language include set of characters (Identifiers- variables,
function names, etc.,) and keywords that it supports.
➢ The keywords have special meaning in any language and they are intended for doing specific
task.
➢ Python has a finite set of keywords as given in Table below.
Table: Keywords in Python
and as assert Break class continue
def del elif Else except False
finally for from global if import
In is lambda None nonlocal not
Or pass raise Return True try
while with yield

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

Python Editors and Installing Python


➢ Before getting into details of the programming language Python, it is better to learn how to
installthe software.
➢ Python is freely downloadable from the internet. There are multiple IDEs (Integrated
Development Environment) available for working with Python. Some of them are PyCharm,
Eclipse, IDLE etc.
➢ When you install Python, the IDLE editor will be available automatically. Apart from all
theseeditors, Python program can be run on command prompt also.

➢ 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.

Conversing with Python


➢ Once Python is installed, one can go ahead with working with Python.
➢ Use the IDE of your choice for doing programs in Python.
➢ After installing Python (or Anaconda distribution), if you just type “ python’ in the command

5
Introduction to Python Programming Module-1

prompt, you will get the message as shown in Figure


Figure : Python initialization in command prompt

➢ 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.

Figure: Python IDLE editor


➢ 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 –
>>> print(“Hello World”) #type this and press enter key
Hello World #output displayed
>>> #prompt returns again

➢ 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

Terminology: Interpreter and Compiler


➢ All digital computers can understand only the machine language written in terms of zeros
andones. But, for the programmer, it is difficult to code in machine language.
➢ Hence, we generally use high level programming languages like Java, C++, PHP, Perl, JavaScript
etc.
➢ Python is also one of the high-level programming languages. The programs written in high
level languages are then translated to machine level instruction so as to be executed by CPU.
➢ How this translation behaves depending on the type of translators viz. compilers and interpreters.
➢ 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.
➢ 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
theprevious line will be retained by Python and hence, the further lines can make use of previously
usedvariables.
➢ Thus, each line that we write at the Python prompt are logically related, though they look
independent.

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.

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 listed below –
➢ 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
programmust 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

8
Introduction to Python Programming Module-1

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.

What Could Possibly Go Wrong?


It is obvious that one can do mistakes while writing a program. The possible mistakes are categorized
as below –
➢ Syntax Errors: The statements which are not following the grammar (or syntax) of the
programming language are 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 the 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 poor understanding of the problem. Syntactically,
the program will be correct. But it may not give the expected output. For example, you are
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 wrong use of variables, wrong
operations or in wrong order. For example, trying to modify un-initialized variable etc.

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

Difference between Compiler and Interpreter


Basis Compiler Interpreter
The entire program is analyzed in a In an interpreter, a line-by-line analysis
Analysis
compiler in one go. is performed on the program.
Stores machine code in the disk
Machine Code Machine code is not stored anywhere.
storage.
The execution of the program takes
The execution of the program happens
place after every line is evaluated and
Execution only after the entire program is
hence the error is raised line by line if
compiled.
any.
Compiled program runs faster. Since it Interpreted program runs slower. Since
Run Time consumes less time, it is much faster it consumes more time, it is much
than an interpreter. slower than a compiler.
The compilation gives an output The interpretation does not give any
Generation program that runs independently from output program and is thus evaluated
the source file. on every execution.
The compiler reads the entire program
No rigorous optimization takes place as
Optimization and searches multiple times for a time-
code is evaluated line by line.
saving execution.
All the errors are shown at the end of
Displays the errors from line to line.
Error and error the compilation and the program
The program runs till the error is found
execution cannot be run until the error is
and proceeds further on resolving.
resolved.
The compiler takes in the entire The interpreter takes in lines of code
Input
program for analysis. for analysis.
The compiler gives intermediate code The interpreter does not generate any
Output
forms or object code. intermediate code forms.
Programming C, C++, C#, Java are compiler-based PHP, PERL, Ruby are interpreter-
languages programming languages. based programming languages.

10
Introduction to Python Programming Module-1

The interpreter uses less CPU than the


CPU Utilization CPU utilization is higher in compilers.
compiler.
Error Errors can be localized more easily
Localizing errors is difficult.
Localization than in the compiler.
An error can trigger the reorganization Errors only cause part of the program
Error Effects
of the entire program. to be reorganized.
The interpreter provides more
Flexibility In general, compilers are not flexible.
flexibility.
Error Simultaneously check for both
Syntactic errors are checked only.
Verification syntactic and semantic errors.

VARIABLES, EXPRESSIONS AND STATEMENTS

Values and Types


➢ A value is one of the basic things a program works with.
➢ It may be like 2, 10.5, “Hello” etc.
➢ Each value in Python has a type. Type of 2 is integer, type of 10.5 is floating point number,
“Hello” is string etc.
➢ The type of a value can be checked using type() 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 str, int and float.
➢ Observe the 4th example – it clearly indicates that whatever enclosed within a double quote is
astring.

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:

# two statements in a single


l = 10; b = 5
# statement 3
print('Area of rectangle:', l * b)
# Output Area of rectangle: 50

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:

name = "John" # string assignment


age = 25 # integer assignment
salary = 25800.60 # float assignment
print(name) # John
print(age) # 25
print(salary) # 25800.6

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.

Changing the value of a variable


➢ Many programming languages are statically typed languages where the variable is initially
declared with a specific type, and during its lifetime, it must always have that type.
➢ But in Python, variables are dynamically typed and not subject to the data type restriction. A
variable may be assigned to a value of one type, and then later, we can also re-assigned a value
of a different type.
Example:
var = 10
print(var) # 10
# print its type
print(type(var)) # <class 'int'>

# assign different integer value to var


var = 55
print(var) # 55

# change var to string


var = "Now I'm a string"
print(var) # Now I'm a string
# print its type
print(type(var)) # <class 'str'>

# change var to float


var = 35.69
print(var) # 35.69
# print its type
print(type(var)) # <class 'float'>

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

➢ Assigning multiple values to multiple variables


roll_no, marks, name = 10, 70, "python"
print(roll_no, marks, name) # 10 20 python

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

Python variable are case-sensitive


Python is a case-sensitive language. If we define a variable with names a = 100 and A =200
then, Python differentiates between a and A. These variables are treated as two different variables (or
objects).
Example
a = 100
A = 200
# value of a
print(a) # 100
# Value of A
print(A) # 200
a = a + A
print(a) # 300

16
Introduction to Python Programming Module-1

Rules and naming convention for 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.
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

Object/Variable identity and references


➢ In Python, whenever we create an object, a number is given to it and uniquely identifies it. This
number is nothing but a memory address of a variable’s value. Once the object is created, the
identity of that object never changes.
➢ No two objects will have the same identifier. The Object is for eligible garbage collection when
deleted. Python has a built-in function id() to get the memory address of a variable.
➢ For example, consider a library with many books (memory addresses) and many students (objects).
At the beginning(when we start The Python program), all books are available. When a new student
comes to the library (a new object created), the librarian gives him a book. Every book has a unique
number (identity), and that id number tells us which book is delivered to the student (object)
Example:
n = 300
m = n
print(id(n)) # same memory address
print(id(m)) # same memory address

➢ 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

➢ Python keywords are case-sensitive.


➢ All keywords contain only letters (no special symbols).
➢ Except for three keywords (True, False, None), all keywords have lower case letters.

Get the List of Keywords:


➢ We can use the following two ways to get the list of keywords in Python:
o keyword module: The keyword is the built-in module to get the list of keywords. Also, this
module allows a Python program to determine if a string is a keyword.
Example:

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.

How to Identify Python Keywords


➢ Python keyword module allows a Python program to determine if a string is a keyword or not.

import keyword
print(keyword.iskeyword('if')) # True
print(keyword.iskeyword('range')) # False

iskeyword(s): Returns True if s is a keyword

20
Introduction to Python Programming Module-1

Python Data Types


➢ Data types specify the different sizes and values that can be stored in the variable. For example,
Python stores numbers, strings, and a list of values using different data types.
➢ Python is a dynamically typed language; therefore, we do not need to specify the variable’s type
while declaring it. Whatever value we assign to the variable based on that data type will be
automatically assigned.
➢ For example,
name = 'Computer' # here Python will store the name variable as a str data type.
➢ No matter what value is stored in a variable (object), a variable can be any type like int, float, str,
list, set, tuple, dict, bool, etc.
➢ There are mainly five types of basic/primitive data types available in Python
o Numeric: int, float, and complex
o Sequence: String, list, and tuple
o Boolean: True, False
o Set
o Dictionary (dict)

Data type Description Example

int To store integer values n = 20

float To store decimal values n = 20.75

To store complex numbers (real and imaginary


complex n = 10+20j
part)

21
Introduction to Python Programming Module-1

str To store textual/string data name = 'Jessa'

bool To store boolean values flag = True

list To store a sequence of mutable data l = [3, 'a', 2.5]

tuple To store sequence immutable data t =(2, 'b', 6.4)

dict To store key: value pair d = {1:'J', 2:'E'}

set To store unorder and unindexed values s = {1, 3, 5}

frozenset To store immutable version of the set f_set=frozenset({5,7})

range To generate a sequence of number numbers = range(10)

bytes To store bytes values b=bytes([5,10,15,11])

Int data type


➢ Python uses the int data type to represent whole integer values.
➢ For example, we can use the int data type to store the roll number of a student.
➢ The Integer type in Python is represented using a int class.
➢ You can store positive and negative integer numbers of any length such as 235, -758, 235689741.
➢ We can create an integer variable using the two ways
1. Directly assigning an integer value to a variable
2. Using a int() class.

# store int value


roll_no = 33
# display roll no
print("Roll number is:", roll_no)
# output 33
print(type(roll_no))
# output class 'int'
# store integer using int() class
id = int(25)
print(id) # 25
print(type(id)) # class 'int'

22
Introduction to Python Programming Module-1

Float data type


➢ To represent floating-point values or decimal values, we can use the float data type.
➢ For example, if we want to store the salary, we can use the float type.
➢ The float type in Python is represented using a float class.
➢ We can create a float variable using the two ways
1. Directly assigning a float value to a variable
2. Using a float() class.

# Store a floating-point value


salary = 8000.456
print("Salary is :", salary) # 8000.456
print(type(salary)) # class 'float'

# store a floating-point value using float() class


num = float(54.75)
print(num) # 54.75
print(type(num)) # class 'float'

Complex data type


➢ A complex number is a number with a real and an imaginary component represented as a+bj
where a and b contain integers or floating-point values.
➢ The complex type is generally used in scientific applications and electrical engineering
applications. If we want to declare a complex value, then we can use the a+bj form.

x = 9 + 8j # both value are int type


y = 10 + 4.5j # one int and one float
z = 11.2 + 1.2j # both value are float type
print(type(x)) # class 'complex'>

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

Str data type


➢ In Python, A string is a sequence of characters enclosed within a single quote or double quote.
➢ These characters could be anything like letters, numbers, or special symbols enclosed within
double quotation marks.
➢ For example, "Computing" is a string.
➢ The string type in Python is represented using a str class.
➢ The string is immutable, i.e., it cannot be changed once defined. You need to create a copy of it if
you want to modify it. This non-changeable behavior is called immutability.

platform = " Computing"


print(type(platform)) # <class 'str'>

# display string
print(platform) # ' Computing'

# accessing 3rd character of a string


print(platform[3]) # p

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

Python program to demonstrate arithmetic operators.

# Arithmetic operators
x = 15
y = 4
print('x + y =',x+y) # Output: x + y = 19

print('x - y =',x-y) # Output: x - y = 11

print('x * y =',x*y) # Output: x * y = 60

print('x / y =',x/y) # Output: x / y = 3.75

print('x // y =',x//y) # Output: x // y = 3

print('x ** y =',x**y) # Output: x ** y = 50625

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

Python program to demonstrate relational operators.

# 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

Python program to demonstrate logical operators

# 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.

Python program to demonstrate assignment operators

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.

Bitwise AND (&)

29
Introduction to Python Programming Module-1

Bitwise OR ( | )

Bitwise XOR ( ^ )

Bitwise NOT ( ~ )

Bitwise Left Shift ( << )

30
Introduction to Python Programming Module-1

Bitwise Right Shift ( >> )

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

➢ This operator works in reverse manner for in operator.


➢ It returns True if element is not found in the specified sequence and if element is found, then
it returns False.
Examples:-
st1 = “Welcome to Python Class”

31
Introduction to Python Programming Module-1

“java” not in st1 #output: True


st2 = “Welcome to Python Class”
“come” not in st2 #output: False
st3 = “Welcome to Python Class”
“to” not in st3 #output: False

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

Python Operators Precedence


In Python, operator precedence and associativity play an essential role in solving the expression.
An expression is the combination of variables and operators that evaluate based on operator
precedence.
The following tables shows operator precedence highest to lowest.
Precedence
Operator Meaning
level
1 (Highest) () Parenthesis

2 ** Exponent

3 +x, -x, ~x Unary plus, Unary Minus, Bitwise


negation
4 *, /, //, % Multiplication, Division, Floor division,
Modulus
5 +, - Addition, Subtraction

6 <<, >> Bitwise shift operator

7 & Bitwise AND

8 ^ Bitwise XOR

9 | Bitwise OR

10 ==, !=, >, >=, <, <= Comparison


is, is not, in, not
11 Identity, Membership
in
12 not Logical NOT

13 and Logical AND

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

iii) print(2**4 + (5 + 5)**(1 + 1))

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

Type Conversion or Type Casting


➢ In Python, we can convert one type of variable to another type. This conversion is called type
casting or type conversion.
➢ Python performs the following two types of casting.
o Implicit casting: The Python interpreter automatically performs an implicit Type conversion,
which avoids loss of data.
o Explicit casting: The explicit type conversion is performed by the user using built-in
functions.
▪ int(): convert any type variable to the integer type.
▪ float(): convert any type variable to the float type.
▪ complex(): convert any type variable to the complex type.
▪ bool(): convert any type variable to the bool type.
▪ str(): convert any type variable to the string type.
Implicit Type Conversion
In this, methods, Python converts data type into another data type automatically. In this process, users
don’t have to involve in this process.
# Python program to demonstrate implicit type Casting
# Python automatically converts
a = 7
print(“type of a:”,type(a))
b = 3.0
print(“type of b:”,type(b))

# Python automatically converts c to float as it is a float addition


c = a + b
print(“SUM=”,c)
print(“type of c:”,type(c))

’’’Python automatically converts d to float as it is a float


multiplication’’’
d = a * b
print(“PRODUCT=”,d)
print(“type of d:”,type(d))

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'>

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type into certain data
type in order to the operation required.

#program to demonstrate explicit type conversion


a=10.6
p=int(a)
print(“value of a is :”,a)
print(“value of p is :”,p)
print("The type of 'a' is ",type(a))
print("The type of 'p' is",type(p))

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

#program to demonstrate explicit type conversion


#initializing the value of a
a=10
print("value of a is :",a)
print("The type of 'a' is ",type(a))
p=str(a)
print("value of a is :",p)
print("The type of 'p' is",type(p))

#initializing the value of b


b='8'
print("value of b is :",b)
print("The type of 'b' is ",type(b))
q=int(b)
print("value of q is :",q)
print("The type of 'q' is",type(q))

#initializing the value of c


c='7.9'
print("value of c is :",c)
print("The type of 'c' is ",type(c))
r=float(c)
print("value of r is :",r)
print("The type of 'r' is",type(r))

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

Consider following few examples –


>>> int('20') #integer enclosed within single quotes
20 #converted to integer type

>>> int("20") #integer enclosed within double quotes


20

>>> int("hello") #actual string cannot be converted to int


Traceback (most recent call last): File "<pyshell#23>",
line 1, in <module> int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

>>> int(3.8) #float value being converted to integer


3 #round-off will not happen, fraction is ignored

>>> int(-5.6)
-5

>>> float('3.5') #float enclosed within single quotes


3.5 #converted to float type

>>> float(42) #integer is converted to float


42.0

>>> str(4.5) #float converted to string


'4.5'

>>> str(21) #integer converted to string


'21'

38
Introduction to Python Programming Module-1

Basic Input and Output

Printing Using the print() Function


Printing a Single Item
➢ To print just a single item, we pass that item to the print() function as shown in the examples
below:
>>> print('hello')
hello
>>> print(12)
12
>>> print(2.5)
2.5
>>> print(True)
True
>>> print("2.5")
2.5
>>> print(1.5 * 3)
4.5

Printing Multiple Items


➢ To print multiple items, we pass all the items in sequence separated by commas as shown in the
examples below. Do note that they are automatically separated by spaces.
>>> print("hello","world")
hello world
>>> print("2+3=",2+3)
2+3= 5

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

>>> print("hello","world",sep=" <-> ")


hello <-> world
>>> print("Welcome","to","Python",sep=" <-> ")
Welcome <-> to <-> Python
>>> print("2+3=",2+3,sep="")
2+3=5

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

Formatting Strings Using the format() Function


➢ While we were able to print using the print() function, we were unable to format the output in
any way (apart from adding separator and terminator strings). For more advanced formatting, we
can rely on the format() function of string class, which can format a string and give us a
resultant string that can then be printed.
➢ The format() function searches the string for placeholders. These placeholders are indicated by
braces ({}) and indicate that some value needs to be substituted there (and probably formatted
too). As a special case, if the string has no placeholders in it, the format () function does nothing
with the string and returns it as it is, as shown in the example below:

40
Introduction to Python Programming Module-1

>>> 'Hello world'.format()


'Hello world'

➢ 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

Getting Information from the Keyboard


➢ 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 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:

41
Introduction to Python Programming Module-1

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'>
>>> x=int(input("Enter x:")) #use int()
Enter x:10
>>> type(x) #Now, type of x is int
<class 'int'>

➢ 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

➢ min(): As the name suggests, it is used to find minimum of arguments.


>>> min(10, 20, 14, 12) #minimum of 4 integers
10
>>> min("hello world")
' ' #space has least ASCII code here
>>> min(3.5, -2.1, 4.8, 15.3, 0.2)

43
Introduction to Python Programming Module-1

-2.1 #minimum 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.
>>> 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.

Type Conversion Functions


➢ As we have seen earlier (while discussing input() function), the type of the variable/value can be
converted using functions int(), float(), str().
➢ Python provides built-in functions that convert values from one type to another
➢ Consider following few examples –
>>> int('20') #integer enclosed within single quotes
20 #converted to integer type
>>> int("20") #integer enclosed within double quotes
20
>>> int("hello") #actual string cannot be converted to int
Traceback (most recent call last): File "<pyshell#23>",
line 1, in <module> int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

44
Introduction to Python Programming Module-1

>>> int(3.8) #float value being converted to integer


3 #round-off will not happen, fraction is ignored
>>> int(-5.6)
-5
>>> float('3.5') #float enclosed within single quotes
3.5 #converted to float type
>>> float(42) #integer is converted to float
42.0
>>> str(4.5) #float converted to string
'4.5'
>>> str(21) #integer converted to string
'21'

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

➢ pi: The constant value pi can be used directly whenever we require.


>>> print(math.pi)
3.141592653589793

➢ log10(): This function is used to find logarithm of the given argument, to the base 10.
>>> math.log10(2)
0.3010299956639812

➢ log(): This is used to compute natural logarithm (base e) of a given number.

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

➢ cos(): Used to find cosine value.


>>>math.cos(45*math.pi/180)
0.7071067811865476

➢ tan(): Function to find tangent of an angle, given as 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.
>>> 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

➢ factorial(): This method returns the factorial of a number.


>>> math.factorial(5)
120

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.

The rules for executing a function call:


1. Evaluate each argument one at a time, working from left to right.
2. Pass the resulting values into the function.
3. Execute the function. When the function call finishes, it produces a value.

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

specific location where a user-defined function has to be called.


o The programmer has to invoke (call) the function wherever required. Consider a simple
example of user-defined 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.

➢ The flow of execution of every program is sequential from top to bottom, a function can be invoked
only after defining it. Usage of function name before its definition will generate error. Observe the
following code:

print("Example of function")
myfun() #function call before definition
print("Example over")

def myfun(): #function definition is here


print("Hello")
print("Inside the function")

50
Introduction to Python Programming Module-1

The above code would generate 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 previous program as below –

➢ 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

The output would be –


Example of function with arguments
Inside test()
Argument is hello
Inside test()
Argument is 20
Over!!

➢ 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

You might also like