0% found this document useful (0 votes)
3 views236 pages

Introduction To Python - Teena

Uploaded by

ashmithabhi3
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)
3 views236 pages

Introduction To Python - Teena

Uploaded by

ashmithabhi3
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/ 236

Introduction to Python

Programming

Dr Teena Sharma
2

WHAT IS PYTHON?

Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.

• Python was conceptualized by Guido Van Rossum in the late 1980s


.
• Rossum published the first version of Python code (0.9.0) in February
1991 at the CWI (Centrum Wiskunde & Informatica) in the Netherlands ,
Amsterdam.

• Rossum chose the name "Python", since he was a big fan of Monty
Python's Flying Circus.
3

WHY PYTHON IS PREFFERED?

Python is a
• high-level language
• Interpreted language
• Interactive language
• object-oriented scripting language.
• Python is designed to be highly readable.
• It uses English keywords frequently whereas the other languages use
punctuations.
• It has fewer syntactical constructions than other languages.

Uses: Python is used as AI-assisted coding tools, Natural language


processing (NLP), Game development, and Cloud services
4

ADVANTAGES AND DISADVANTAGES

• Clearly defined syntax


• Slow in speed

• Own IDLE (Integrated Development and


• Weak in mobile computing
Learning Environment)
IDLE is a Tool for writing, testing and
debugging python code • Requires more testing time

• Most appropriate for


mathematical problem solving
5

PYTHON VERSIONS

Release dates for the major and minor versions:


• Python 3.0 - December 3, 2008 • Python 3.8.6 - September 8, 2020
• Python 3.1 - June 27, 2009 • Python 3.9 - September 24, 2020
• Python 3.2 - February 20, 2011 • Python 3.9.1 - October 5, 2020
• Python 3.3 - September 29, 2012 •.
• Python 3.4 - March 16, 2014 •.
• Python 3.5 - September 13, 2015 •.
• Python 3.6 – December 23, 2016 • Python 3.10.6 - August 2, 2022
• Python 3.7 – June 27, 2018 • Python 3.12.6 – September 2024
• Python 3.8 – October 14, 2019
6

PYTHON FEATURES
7

PYTHON FLOW OF RUNNING


8

PYTHON RUNTIME STRUCTURE


9

MODE OF EXECUTION
Interactive Mode Programming (Direct Mode): To run a python code interactively, we
use the command prompt in Windows, terminal in Linux and macOS, or Jupyter
Notebook, etc.

Script mode: We first write a Python program inside a file (like a script) in the script
mode, and then we execute the file after saving it in our system. So, Script mode in
Python is where we first write the Python program inside a script file and execute it
after that.
10

MODE OF EXECUTION

Step1: write a program in a file and save it as ".py" file


11

MODE OF EXECUTION

Step2: import the file in another jupyter notebook through a command


"import file_name"
12

TOKENS IN PYTHON

A smallest individual Unit in a program is called Tokens or Lexical units.

Python has following Tokens:


• Keywords
• Identifiers(Name)
• Literals
• Operators
• Punctuators
13

TOKENS IN PYTHON

1. Keywords: These are the pre-defined words with special meaning to the language
compiler or interpreter. These are reserved for some special purposes and must not be
used as a normal identifier.
14

TOKENS IN PYTHON

2. Identifiers: these are the NAMES given to different parts of the program viz variables,
classes, functions, objects, and so on.
The naming rules for python identifiers can be summarized as follows:

• Variable names must only be a non-keyword word with no spaces in between.

• Variable names must be made up of only letters, numbers, and underscore.

• Variable names cannot begin with a number, although they can contain numbers.
15

TOKENS IN PYTHON

3. Literals: these are data items which have a constant or fixed value.

• string Literals: Words or sentence in double quotes ex: "hi", "Hello world" etc
• Numeric Literals: Numerical values
1. Int : decimal or integer values ex: 234, 89
2. Octal : integer that starts with 0o ex: 0o34
3. Hexadecimal: Integer starting with 0x followed by letters or numbers ex: 0x56,
0xAF
4. Floats: 3.78, 89.0

• Boolean : TRUE , FALSE


• Special Literals: None
16

TOKENS IN PYTHON

4. Operators: Operators are tokens that trigger some computation/action when applied to
variables and other objects in an expression.

• The operators can be arithmetic operators (+, -,/,%,I, **),


• bitwise operators (&, ^),
• shift operators (<<, >>),
• identity operators (is, is not),
• relational operators (>, <, >, <=,=, !~), logical operators (and, or, not),
• assignment operator (-), membership operators (in, not in), and arithmetic-assignment
operators (/=, +=, -=, */, %=-, **=, //-).
17

TOKENS IN PYTHON

5. Punctuators: Punctuators are symbols that are used in programming languages to organize
sentence structures, and indicate the rhythm and emphasis of expressions, statements, and
program structure.
ex: = , (), [], {}, @, ; , : , ", '
18

BAREBONES OF PYTHON PROGRAM


19

VARIABLES AND ASSIGNMENTS

Variables represent labelled storage locations, whose values can be manipulated during program run.
In Python, to create a variable, just assign to its name the value of appropriate type.

For example, to create a variable namely Student to hold student's name and variable age to hold student's
age, you just need to write somewhat similar to what is shown below:

Student = "Jacob"

Age=16
20

DYNAMIC TYPING
In Python, as you have learnt, a variable is defined by assigning to it some value (of a particular type such as
numeric, string etc.). For instance, after the statement:
X=10
We can say that variable is referring to a value of integer type. Later in your program, if you reassign a value of
some other type to variable x, Python will not complain (no error will be raised),
eg:
A variable pointing to a value of a certain type, can be made to point
X =Hello world
to a value/object of different type. This is called Dynamic Typing
print(x)
#Above code will yield the output as:
10
Hello world
21

DYNAMIC TYPING VS STATIC TYPING


• Dynamic typing is different from Static Typing. In Static typing a data type is attached with a variable
when it is defined first, and it is fixed.

• That is, data type of a variable cannot be changed in static typing whereas there is no such restriction in
dynamic typing, which is supported by Python.
Multiple Assignments
1. Assigning same value to multiple variables. You can assign same value to multiple variables in a single
statement, eg:
a = b= c = 10

It will assign value 10 to all three variables a, b, c.


22

MULTIPLE ASSIGNMENTS
2. Assigning multiple values to multiple variables. You can even assign multiple values to multiple variables
in single statement, eg.
x, y, z = 12, 20, 30
It will assign the values in order , ie, first variable is given first value, second variable is given the second
value and so on. That means, above statement will assign value 12 to x, 20 to y and 30 to z.

Note: if you want swap the value of x and y you just have to give it as
x, y = y, x
23

SIMPLE INPUT AND OUTPUT


• To get the input from the user interactively we can use a built-in command called "input()".
name = input(" what is your name? ")
• This function always returns a value of string type.
• python offers two functions int() , float() to convert the values recieved through input() to int()
and float()
<variable> = int(input( "string" )
<variable>
Print() Command: The print() function of Python =a
3.x is float(input(
way to send"string")
output to standard output device,
which is normally a monitor.
print("objects, [ sep=" or <separator-string> end = '\n' or <end-string> ])

"objects means it can be one or multiple comma separated objects to be printed."


24

PRINT COMMAND
Let us consider some simple examples first:
• print ("hello")
• print (17.5)
• print (3.14159 (r*r) # if r has some value assigned to it
• print ("Im", 12+ 5, "years old.")
The print statement has a number of features:

• it auto-converts the items to strings i.e., if you are printing a numeric value, it will automatically convert
it into equivalent string and print it; for numeric expressions, it first evaluates them and then converts
the result to string, before printing.

• it inserts spaces between items automatically because the default value of sep argument (separator
character) is space("").
24

PRINT COMMAND
Consider this code:
Input: print ("My", "name", "is", "Amit.")
output: My name is Amit. #Four different string objects with no space in them are being printed.

• You can change the value of separator character with sep argument of print() as per this: The code:
Input: print ("My", "name", "is", "Amit.", sep="...")
Output: My...name...is...Amit.

• it appends a newline character at the end of the line unless you give your own end argument.
Consider the code given below:
Input:print ("My name is Amit.")
input: print("I am 16 years old")
25

PRINT COMMAND
Consider this code:
Input: print ("My", "name", "is", "Amit.")
output: My name is Amit. #Four different string objects with no space in them are being printed.

• You can change the value of separator character with sep argument of print() as per this: The code:
Input: print ("My", "name", "is", "Amit.", sep="...")
Output: My...name...is...Amit.

• it appends a newline character at the end of the line unless you give your own end argument.

Consider this code:


Input: print ("My name is Amit.") output: My name is Amit
print("I am 16 years old") I am 16 years old
26

PRINT COMMAND

• If you explicitly give an end argument with a print() function then the print() will print the line and end it with
the string specified with the end argument, and not the newline character,
eg. the code

Input: print("My name is Amit. ", end- print("I am 16 years old.")


#A print() function without any value or name or expression prints a blank line.
Output: My name is Amit. $I am 16 years old
01
DATA TYPES
Data types are means to identify type of data and set of valid operations for it.
Python offers following built-in core data types:

(i) Numbers
(ii) String
(iii) List
(iv) Tuple
(v) Dictionary
02
DATA TYPES
(i)Numbers : Python offers following data types to store and process different types of numeric data

(a) Integers : There are two types of integers in Python

• Integers (signed): It is the normal integer representation of whole numbers. It is the signed representation
i.e, It can take positive or negative values
• Booleans: These represent the truth values False and True. The Boolean type is a subtype of plain
integers, and Boolean values False and True behave like the values 0. and 1, respectively.

(b) Floating-Point Numbers

(c) complex Numbers : Python represents complex numbers in the form A+Bj. Complex numbers are a
composite quantity made of two parts; the real part and the imaginary part, both of which are represented
internally as float values (floating point numbers).
03
DATA TYPES

(ii)Strings :
Strings in python are stored as individual characters in contigous locations. with both forward and backward
indexing

We can access the length of a string using len(String).


Its basically like a word or sentence and also can be a number inside inverted cammas :
"Hello" , "I had my dinner" , " my age is 21".
04
DATA TYPES
• One important thing about Python strings is that you cannot change the individual letters of a string by
assignment because strings are immutable and hence item assignment is not supported.

• immutable i.e they are un-changeable. Once a string is created, you cannot change its values.

• Traversing a string : Traversing refers to iterating through the elements of a string, one character at a time.

To traverse through a string, you can write a loop like:


05
DATA TYPES

Operators in strings
• String replication operator: multiplying a string with a number using ("*") Asterisk will replicates the string.
06
DATA TYPES
• Membership operator:
There are two membership operators for strings (in fact, for all sequence types).
These are in and not in.
in - returns True if a character or a substring exists in the given string; False otherwise.

not in - returns True if a character or a substring does not exist in the given string; False otherwise

Both membership operators (when used with strings), require that both operands used with them
are of string type, ie, <string> not in <string>
07
DATA TYPES
• Comparison Operators:
Nothing but the relational operators!!!
08
DATA TYPES
• ASCII VALUE:
In strings in order to get the ASCII value of that particular number, letter or special
symbols can be printed using ord() and Chr(). But both the function is opposite in its use..
09
DATA TYPES
(ii) Lists:

A List in Python represents a group of comma-separated values of any datatype between square brackets eg,
following are some lists:

["a", "e", "i", "o", "u"]


[1, 2, 3, 4, 5]
["apple", 78, 90, "Cherry"]

In list too, the values internally are numbered from 0 (zero) onwards ie., first item of the list is internally
numbered as 0, second item of the list as 1, 3rd item as 2 and so on.

List items are ordered, changeable (mutable), and allow duplicate values.
10
DATA TYPES
11
DATA TYPES

(iii) Tuples:

Tuples are represented as group of comma-separated values of any date type within parentheses, eg, following
are some tuples:

• mytuple = ("apple", "banana", "cherry")


• tuple2 = (1, 5, 7, 9, 3)
• tuple3 = (True, False, False)

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuples are immutable i.e they are un-changeable. Once a tuple is created, you cannot change its values.
12
DATA TYPES
As we know that Tuple cannot be edited, But there's a way!

You can convert the tuple into a list, change the list, and convert the list back into a tuple.

x = ("apple", "banana", "cherry")

y = list(x)
y[1] = "kiwi"

x = tuple(y)

print(x)
13
DATA TYPES
14
DATA TYPES
(iv) Dictionary:
• The dictionary is an unordered set of comma-separated key: value pairs.
• Dictionary items are changeable, and does not allow duplicates
• you cannot refer to an item by using an index.

Characteristics of a Dictionary :Dictionaries like lists are mutable and that is the only similarity they have with
lists. Otherwise, dictionaries are different type of data structures with following characteristics:
• (a) A dictionary is a unordered set of key: value pairs
• (b) Unlike the string ,list and tuple, a dictionary is not a sequence because it is unordered set of elements..
• (c) Dictionaries are indexed by keys and its keys must be of any non-mutable type.
• (d) Each of the keys within a dictionary must be unique

http://www.hellostudy.org Ranjith Kumar


15
DATA TYPES

http://www.hellostudy.org Ranjith Kumar


16
DATA TYPES
(v) sets: A set is a collection which is unordered, unchangeable*, and unindexed.
myset = {"apple", "banana", "cherry"}
• set items are unchangeable, meaning that we cannot change the items after the set has been created.

• Once a set is created, you cannot change its items, but you can remove items and add new items.

• The values True and 1 are considered the same value in sets, and are treated as duplicates:
01
EXPRESSIONS

Expressions in Python are any valid combination of operators, literals, numbers and variables.
In python we have following expressions:

1. Arithmetic Expressions : Involves Numbers like int, float , complex numbers, along
with arithmetic operators.
02
EXPRESSIONS

2. Relational Expressions : consists of variables and literals of any valid type and the
relational operators.
03
EXPRESSIONS

2. Logical Expressions : consists of variables and literals of any valid type and the logical
operators.
04
EXPRESSIONS
Notes:
• The precedence of logical operators is lower than the arithmetic operators, so
constituent arithmetic sub-expression (if any) is evaluated first and then logical
operators are applied, eg.
25/5 * or * 2 * 20 / 10 will be first evaluated as:
5 or 4
• The precedence of logical operators among themselves is not, and, or
(a or (b and (not c)))
• (a)In 'or' evaluation Python only evaluates the second argument if the first one is false
• (b) In 'and' evaluation, Python only evaluates the second argument if the first one is
true.
http://www.hellostudy.org Ranjith Kumar
05
EXPRESSIONS

Exercise: What is the output of this expression?


(5<10) and (10>5) or (3<18) and not 8 <18
06
EXPRESSIONS
EXTRA LEARNING 1.O
Decimal to Binary conversion: we consider a normal int as a decimal input for the conversion
to its Binary number. In this each individual binary number constitutes to a bit .
07
EXTRA LEARNING 1.O

lets take another example:


08
EXTRA LEARNING 1.O

Bitwise operators: In Python, bitwise operators are used to perform bitwise


calculations on integers. The integers are first converted into binary and then
operations are performed on each bit or corresponding pair of bits, hence the name
bitwise operators. The result is then returned in decimal format.
09
EXTRA LEARNING 1.O
10
EXTRA LEARNING 1.O

Bitwise AND : The bitwise AND operator (&) performs logical conjunction on the corresponding
bits of its operands. For each pair of bits occupying the same position in the two numbers, it
returns a one only when both bits are switched on:
11
EXTRA LEARNING 1.O

Bitwise OR : The bitwise AND operator (&) performs logical conjunction on the corresponding
bits of its operands. For each pair of bits occupying the same position in the two numbers, it
returns a one only when both bits are switched on:
12
EXTRA LEARNING 1.O

Bitwise NOT : bitwise NOT operator (~), which expects just one argument, making it the only
unary bitwise operator. It performs logical negation on a given number by flipping all of its bits
13
EXTRA LEARNING 1.O

Homework:
Search up on Bitwise Left shift and Right shift and document it in google docs
14
EXPRESSIONS
Type Casting : Type Casting is the method to convert the Python variable datatype into a
certain data type to perform the required operation by users.

Type Casting in Python:

1. Python Implicit Type Conversion


2. Python Explicit Type Conversion.

Type casting in Python is performed by type() function of appropriate data type, in the
following manner:
<datatype> (expression)
Implicit Type Conversion in Python: Python converts the datatype into another datatype
automatically. Users don’t have to involve in this process.

Output:

Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>
Explicit Type Conversion in Python
In this method, Python needs user involvement to convert the variable data type into the required data type.

Examples of Type Casting in Python

Mainly type casting can be done with these data type functions:
• Int(): Int() function take float or string as an argument and returns int type object.

• float(): Float () function take int or string as an argument and return float type object.

• str(): This function takes float or int as an argument and returns string type object.

Python Convert Int to Float Python Convert Float to Int Python Convert int to String

Output: Output: Output:


15
STATEMENT FLOW CONTROL

A conditional statement is a statement set which is executed, on the basis of result of a


condition. A loop is a statement set which is executed repeatedly, until the end condition is
satisfied.

1. Compound Statements: A compound statement represents a group of statements


executed as a unit.
The compound statements of Python are written in a specific pattern as shown below:
<compound statement header>:
<indented body containing multiple simple and/or compound statements>
16
STATEMENT FLOW CONTROL

• The compound statements are not written in the same column as the control statement
rather they are indented to the right and together they are called a Block.
• The first line of compound statement, i.e., its header contains a colon(:) at the end of the
line.
17
STATEMENT FLOW CONTROL

2. Simple statements: Compound statements are made of simple statements. Any single
executable statement is a simple statement in Python.

3. Empty statements: The simplest statement is the empty statement i.e., a statement which
does nothing. In Python an empty statement is the pass statement.

It takes the following form:


pass

Wherever Python encounters a pass statement. python does nothing and moves to next
statement.
Example of Empty statements

a = 33
b = 200

if b > a:
pass

# having an empty if statement like this, would raise an error without the pass
statement.
18
THE IF CONDITIONALS

The if statements in python come in multiple forms:


Plain if statements, if else conditionals, if elif conditionals, Nested if

1. Plain if statements: An if statement tests a particular condition; if the condition evaluates


to true, a course-of-action is followed i.e. a statement, or set-of-statements is executed.
If the condition is false, it does nothing.
The syntax (general form) of the if statement is as shown below:

if <conditional statements>:
[statements}
19
THE IF CONDITIONALS
20
THE IF CONDITIONALS
21
THE IF CONDITIONALS
2. if - else conditionals:
This form of if statement tests a condition and if the condition evaluates to true, it carries out
statements indented below 'if' and in case condition evaluates to false, it carries out statement
indented below 'else'.
22
THE IF CONDITIONALS
23
THE IF CONDITIONALS

3. if - elif Statement: Sometimes, you want to check a condition when control reaches else,
i.e, condition test in the form of else if. To serve such conditions. Python provides if-elif and
if-elif-else statements.

The general form of these statements is:


if (condition):
# Executes this block if condition is true
elif :
# Executes this block if condition is true
else:
# Executes this block if
http://www.hellostudy.org Ranjith Kumar
24
THE IF CONDITIONALS
25
THE IF CONDITIONALS

4. Nested if statements:
Sometimes you may need to test additional conditions. For such situations, Python also
supports nested-If form of if. A nested if is an if that has another if in its it's body or in elif.
26
THE IF CONDITIONALS
27
THE IF CONDITIONALS
28
THE IF CONDITIONALS

Short hand if: If you have only one statement to execute, you can put it on the same line as
the if statement.
29
STORING CONDITIONALS

Sometimes the conditions being used in code are complex and repetitive. In such cases to
make your program more readable, you can use named conditions ie, you can store
conditions in a name and then use that named conditional in the if statements.

http://www.hellostudy.org Ranjith Kumar


30
LOOPING STATEMENTS

Python provides two kinds of loops: for loop and while loop to represent counting loop and
conditional loop respectively.

1. for loop : The for loop of Python is designed to process the items of any sequence, such
as a list or a string one by one.
The General Form of for loop The general form of for loop is as given below:

for <variable> in <sequence>:


statements_to_repeat
31
LOOPING STATEMENTS

The above-given for loop executes a sequence of statements for each of the elements of
given sequence [1, 2, 3,4, 5].

To keep the count, it uses a control variable (element in above case) in that takes a different
value on each iteration. Firstly value 1, then the next value of sequence, 2, then 3 and in the
end 5.
32
LOOPING STATEMENTS
33
LOOPING STATEMENTS

The range() in for loop: For number based lists, you can specify range() function to
represent a list as in:

for val in range(3, 18):


print(val)

In the above loop, range(3, 18) will first generate a list [3,4,5,..., 16, 17] with which 'for loop'
will work. You need not define loop variable (val above) beforehand in a for loop.
34
LOOPING STATEMENTS

As mentioned, a range() produces an integer number sequence. There are three ways to
define a range:

1. range(start) : #elements from start to stop-1, incrementing by 1


2. range(start,stop) : #elements from start to stop-1, incrementing by 1
3. range(start,stop,step):#elements from start to stop-1, incrementing by step

The start value is always part of the range. The stop value is never part of the range. The
step shows the difference between two consecutive values in the range.
If start value is omitted, it supposed to be 0. If the step is omitted, it is supposed to be 1.
35
LOOPING STATEMENTS
36
LOOPING STATEMENTS

Else
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished.
37
LOOPING STATEMENTS

Q1: Write a program to print the cubes of the numbers in a range of 2 to 10?

Q2: Write a program to print the square root of every alternate number in the range
38
LOOPING STATEMENTS

while loop: is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true (Boolean True or truth value true).
The general form of Python while loop is:

while <logicalExpression>:
loop-body

where the loop-body may contain a single statement or multiple statements or an empty
statement (ie, pass statement). The loop iterates while the logical Expression evaluates to
true. When the expression becomes false, the program control passes to the line after the
loop-body.
39
LOOPING STATEMENTS

How does While loop work?


40
LOOPING STATEMENTS
41
JUMP STATEMENTS

Python offers two jump statements-break and continue-to be used within loops to jump out of
loop-iterations.

1. Break Statement: A break statement terminates the very loop it lies within. Execution
resumes at the statement immediately following the body of the terminated statement.
42
JUMP STATEMENTS
43
JUMP STATEMENTS

Continue statement: when the continue statement is executed in the loop, the code inside
the loop following the continue statement will be skipped for the current iteration and the next
iteration of the loop will begin.
It forces to continue the next iteration.
44
JUMP STATEMENTS
45
NESTED LOOPS

Nested loop: A loop can contain another loop inside its body. But an important thing is that the
inner loop must terminate before thge outer loop.

in nested loop the Break statement will just break the iteration of the for loop where it exists.
01
FUNCTIONS

Intro : A function is a self-contained block of statement to perform a specific task.

Mainly, there are two types of function:

Library Functions: These functions are provided by a Python’s package and a user only need to
call it in your program.

User Defined Functions in Python


As name indicates that a user will define for its own use. User will decide number of arguments
a function will receive and return, what statement a function will contain.
Python uses a “def” keyword to define a function. Function in Python is preceded by def
keyword and is followed by a colon(:).
02
For example, if you want to define a function to add two variables different types of functions
are defined. Based on how many argument they receive and return.
03
FUNCTIONS

So, On the similar lines, programming languages also support functions.


• You can create functions in a program, that can have arguments (values given to it) if
needed
• can perform certain functionality (some set of statements)
• can return a result
For instance, above mentioned mathematical function f(x) can be written in Python like this

def calcSomething (x):


r= 2*x**2
return r
04
FUNCTIONS

where,
• def means a function definition is starting
• identifier following def' is the name of the function, i.e, here the function name is
calcSomething
• the variables/identifiers inside the parentheses are the parameters (values given to
function), ie, here x is the argument to function calcSomething.
• there is a colon at the end of def line, meaning it requires a block.
• the statements indented below the function, (ie, block below def line) define the
functionality (working) of the function. This block is also called body-of-the-function. Here,
there are two statements in the body of function calcSomething
• The return statement returns the computed result.
05
FUNCTIONS

• The non-indented statements that are below the function definition are not part of the
function calcSomething's definition. For instance, consider the example-function given,
06
FUNCTIONS

Function call: To use a function that has been defined earlier, you need to write a function call
statement in Python. A function call statement takes the following form

<function-name>(<value-to-be-passed-to-argument>)
For example, if we want to call the function calcSomething() defined above, our function call
statement will be like
calcSomething(5) #value 5 is being sent as argument

Another function call for the same function, could be like:


a=7
calcSomething(a) #this time variable a is being sent as argument
07
FUNCTIONS

Carefully notice that number of values being passed is same as number of parameters. Also
notice, the last line of the program uses a function call statement. (print() is using the function
call statement.)

Consider one more function definition given below:


08
FUNCTIONS

• Passing literal as argument:

• Passing variable as argument in function call:


09
FUNCTIONS

• Using function call inside another statement:

• Using function call inside expressions:


10
FUNCTIONS

Function types: Python comes preloaded with many function-definitions that you can use as
per your needs. You can even create new functions. Broadly, Python functions can belong to
one of the following three categories:

1. Built-in functions :These are pre-defined functions and are always available for use.
some of them - len(), type( ), int(), input() etc.

2. Functions defined in modules: These functions are pre-defined in particular modules and
can only be used when the corresponding module is imported. For example, if you want to
use pre-defined functions inside a module, say sin(), you need to first import the module math
(that contains definition of sin()) in your program
11
FUNCTIONS

3. User defined functions : These are defined by the programmer. As programmers you can
give your own functions.

Defining a Function:
As you know that we write programs to do certain things. Functions can be thought of as
key-doers within a program. A function once defined can be invoked as many times as needed
by using its name, without having to rewrite its code

In the following lines, we are about to give the general form i.e, syntax of writing function code
in Python. Before we do that, just remember these things In a syntax language
12
FUNCTIONS

1. item(s) inside angle brackets < > has to be provided by the programmer.
2. item(s) inside square brackets [ ] is optional, ie., can be omitted
3. items/words/punctuators outside <> and [] have to be written as specified.

def<function Name> [parameters]


13
FUNCTIONS

Ways to define function:


14
FUNCTIONS

In a Python program,
• generally all function definitions are given at the top followed by statements which are not
part of any functions. These statements are not indented at all.
• These are often called from the top-level statements (the ones with no indentation). The
Python interpreter starts the execution of a program/script from the top-level statements.
• Internally Python gives a special name to function By default, Python names the top-level
statements as "__main__"
• Python stores this name in a built-in variable called __name__
15
FUNCTIONS

Flow of execution of Function statements:


• the flow of execution refers to the order in which statements are executed in the python
during a programm run.

• We know that the function will only work when it is being Called.
like, CalcSomething(4),
greet("Bob").. etc

• So whenever Function call statement is encountered An execution frame will be created


consisting of the order of execution.
16
FUNCTIONS
17
FUNCTIONS

Execution Frame
18
FUNCTIONS

Arguments and Parameters:


A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
Parameters i,e. 'a' and 'b'

Arguments i,e 5 for a


3 for b

Note: Arguments are always supposed to be values and shouldn't contain any
variables eg: add(a+5 , 3)
19
FUNCTIONS

Passing Parameters: Untill now you learnt that a function call must provide all the values as
required by function definition. For instance, if a function header has three parameters named
in its header then the function call should also pass three values Other than this. Python also
provides some other ways of sending and marching arguments and parameters.

Python supports three types of formal arguments/parameters

1. Positional arguments (Required arguments)


2. Default arguments
3. Keyword (or name) arguments
Let us talk about these, one by one.
20
FUNCTIONS

1. Positional or required arguments: Till now you have seen that when you create a function
call statement for a given hunction definition, you need to match the number of arguments
with number of parameters required
For example, if a function definition header is like
def check (a, b, c)
check (2, 5, 7)
• the number of passed values (arguments) has matched with the number of received
values (parameters)
• Also, the values are given (or matched) position wise or order-wise, i.e, the first parameter
receives the value of first argument, second parameter, the value of second argument and
so on.
21
FUNCTIONS

2. Default arguments:
What if we already know the value for a certain parameter, eg., in an interest calculating
function, we know that mostly the rate of interest is 10%, then there should be a provision to
define this value as the default value.
• Python allows us to assign default value(s) to a function's parameter(s) which is useful in
case a matching argument is not passed in the function call statement.
• The default values are specified in the function header of function definition. Following is an
example of function header with default values:

def interest (principal, time, rate=0.10)


Function call

interest(5400, 3)
22
FUNCTIONS

the value 5400 is passed to the parameter principal, the value 2 is passed to the second
parameter time and since the third argument rate is missing its default value 0.10 is used for
rate.
But if a function call provides all three arguments as shown below
interest (6100, 3, 0.15)

then the parameter principal gets value 6100, time gets 3 and the parameter rate gets value
0.15.

That means the default values (values assigned in function header) are considered only if no
value is provided for that parameter in the function call statement.
23
FUNCTIONS

One very important thing you must know about default parameters!!

In a function header, any parameter cannot have default value unless all parameters appearing
on right have their default values

• For instance, in the above mentioned declaration of function interest, the parameter
principal cannot have its default value unless the parameters on its right, time and rate also
have their default values.
• Similarly, the parameter time cannot have its default value unless the parameter on its
right, ie, rate has its default value. There is no such condition for rate as no parameter
appears on its right.
24
FUNCTIONS

def interest (principle, time, rate=8.28): #Legal

def interest (principle, time=2, rate): #illegal

def test (principle=288, time=2, rate): #illegal

de interet (principle, time=2, rate=8.38) #Legal


25
FUNCTIONS
3. Keyword Arguments:
• The default arguments give you flexibility to specify the default value for a parameter so that
can be skipped in the function call, if needed. However, still you cannot change the order of
the arguments in the function call, you have to remember the correct order of the arguments

• To have complete control and flexibility over the values sent as arguments per the
corresponding parameters, Python offers another type of arguments keyword arguments

• Python offers a way of writing function calls where you can write any argument in any order,
provided you name the arguments when calling the function, as shown below
26
FUNCTIONS
nterest (prin = 2000, time =2, rate=0.10)
interest (time = 4, prin=2600, rate=0.09)
interest (time=2, rate= 0.12, prin=2000)

All the above function calls are valid now, even if the order of arguments does not match to the
order of parameters as defined in the function header.

This way of specifying names for the values being passed, in the function call is known as
keyword arguments
27
FUNCTIONS

Multiple arguments in function call:


• Python allows you to combine multiple argument types in a function call. Consider the
following function call statement that is using both positional (required) and keyword
arguments

interest (5000, time=5)

• The first argument value (5000) in above statement is representing a positional argument
as it will be assigned to first parameter on the basis of its position. The second argument
(time=5) is representing keyword argument or named argument. The above function call
also skips an argument (rate) for which a default value is defined in the function header.
28
FUNCTIONS
Rules for combining all three types of arguments:

Python states that in a function call statement


• an argument list must first contain positional (required) arguments followed by any
keyword argument.

• Keyword arguments should be taken from the required arguments preferably

• You cannot specify a value for an argument more than once


• lets take an example:
def interest( prin, cc, time=2, rate =0.09) :
return printime rate
29
FUNCTIONS
30
FUNCTIONS

RETURNING VALUES FROM FUNCTIONS: Functions in Python may or may not return a
value. You already know about it. There can be broadly two types of functions in Python
1. Functions returning some value (non-void functions)
2. Functions not returning any value (void functions)

3. Non Void Functions: The functions that return some computed result in terms of a value,
fall in this category. The computed value is returned using return statement as per syntax

return <value>
31
FUNCTIONS

2. Void function: The functions that perform some action or do some work but do not return
any computed value or final value to the caller are called void functions. A void function may or
may not have a return statement. If a void function has a return statement, then it takes the
following form

return
32
FUNCTIONS

The void functions do not return a value but they return a legal empty value of Python i.e.
None. Every void function returns value None to its caller. So if need arises you can assign
this return value somewhere as per your needs, eg, consider following program code
33
FUNCTIONS

Returning Multiple values: We can use multiple argument


34
FUNCTIONS

Composition:
Composition in general refers to using an expression as part of a larger expression or a
statement
In functions context, we can understand composition as follows:
The arguments of a function call can be any kind of expression
• an arithmetic expression
greater( (45), (3-4))
• a logical expression
test(a or b)
• a function call (function composition)
int(str(52))
35
FUNCTIONS

Global variable and Local variable

A global variable is a variable defined in the 'main' program ("_ _main_ _" section). Such
variables are said to have global scope.

A local variable is a variable defined within a function. Such variables are said to have local
scope.
36
FUNCTIONS

Arbitrary Arguments: *args


If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
37
FUNCTIONS

Arbitrary keyword Arguments: **kwargs


add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly:
38
FUNCTIONS

Combining *args and **kwargs in a function signature:


You can use both *args and **kwargs together in a function definition. In this case, *args will
collect positional arguments, and **kwargs will collect keyword arguments.
39
FUNCTIONS

Passing a List as an argument:


You can send any data types of argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function
40
FUNCTIONS

Lambda Functions:
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one expression.

syntax: lambda arguments : expression


41
FUNCTIONS

Multiply argument 'a' with argument 'b' and return the result:

Summarize argument a, b, and c and return the result:


42
FUNCTIONS

Why use Lambda function?


The power of lambda is better shown when you use them as an anonymous function inside
another function.

Say you have a function definition that takes one argument, and that argument will be multiplied
with an unknown number:
43
FUNCTIONS

Use that function definition to make a function that always doubles the number you send in:

use the same function definition to make a function that always triples the number you send in:
1
RECURSIONS

What do u think when you hear “Recursions”??


2
RECURSIONS

Recursions is also a type of functions!!!!!

Recursion
statement
3
RECURSIONS

How does it work ???


4
RECURSIONS

Another Example:
5
RECURSIONS
IMPORTANT NOTE IN RECURSIONS ::
• The compute function doesn't always recur. That is when its parameter # is 1, the function
simply returns immediately without any recursive invocations
• Any condition where a recursive function does not invoke itself is called a base case.
• But what exactly happens when a recursive function lacks a base case ? To understand this,
we need to get some idea about how a computer handles function invocations.
• In executing a program, the computer creates what is called the function stack.
• The function stack is a stack of frames, each frame corresponding to a function invocation
• When the function at the stack's top returns, the computer removes that function's frame
from the stack's top, and resumes its work on the function now on the frame's top.
6
RECURSIONS

Stack Frame
7
RECURSIONS

• Recursion in Python :
x^n = x*x*x*x........ (Non Recursive)
x^n = x*(x^n-1) (Recursive )
• Writing a Recursive Function.: Before you start working resursive functions, you must know
that every recursive function must have at least two cases:

1. Recursive case: is the more general case of the problem we're trying to solve using recursiv
call to same function.

2. Base case: The Base Case is a small problem that we know how to solve and is the case
that cases the recursion to end. In other words, it is the case whose solution is pre known (eithe
as a value or formula) and used directly
8
RECURSIONS
Power (x, n)= x-Power (x, n-1) : Recursive case

and the base cases would be,

• Power (x, n)=x , when n=1


• Power (x, n)=1 , when n=0
• and Other cases (when n<0) we are ignoring this now for simplicity sake.
9
RECURSIONS
9
RECURSIONS

If there is no base case, or if the base case is never executed,


an infinite recursion occurs. An Infinite Recursion is when a recursive function calls itself
endlessly. Infinite recursion can happen in one of the following cases.

(1) Base Case Not Defined. When the recursive function has no BASE CASE defined, infinite
recursion will occur

(2) Base Case Not reached. Sometimes you have written a base case but the condition to
execute it, is never satisfied, hence the infinite recursion occur.

,
10
RECURSIONS

For example, the code of above program will face infinite recursion if you enter a negative
value for power. In that case, the condition for base case,
i.e,

if b == 0: (would never be true for negative value of b)

Hence this statement will never be satisfied and hence infinite recursion will occur.
To avoid infinite recursion, your code should take care of recursion values accurately.
11
RECURSIONS

The Code can be modified as follows:


12
RECURSIONS

Note: The recursion code can always be written in an iterative way as well
LIKE :
13
RECURSIONS

Some Recursive codes

1. Factorial recursively:
14
RECURSIONS

2. GCD recursively:
15
RECURSIONS

3. Fibonacci series recursively:


16
RECURSIONS
RECURSIONS VS ITERATION:
17
RECURSIONS
18
REVISION

Congratulations !! We finished more than half of our syllabus!

S0, lets see how you can do this:


1. Write a Python program that calculates the sum of all even numbers from 1 to given
positive integer n. Implement this program using a for loop. For example, if the input is n =
10, the program should calculate and print the sum of even numbers from 1 to 10, which is
2 + 4 + 6 + 8 + 10 = 30.

2. Write a Python program that asks the user to enter an integer and then prints the
multiplication table for that integer from 1 to 10. use functions concept with loops to get the
desired output.
19
EXTRA LEARNING PART -3

Opening an image in python IDEs

1. Opening an image in python requires a package named as “opencv” and “matplotlib” which
needs to installed.
In command prompt type “pip install opencv” and “pip install matplotlib”
20
EXTRA LEARNING PART -3
21
EXTRA LEARNING PART -3
22
EXTRA LEARNING PART -3
01
CLASSES AND OBJECTS

In Python, a class is a user-defined data type that contains both the data itself and the methods
that may be used to manipulate it. In a sense, classes serve as a template or like a blueprint to
create objects. They provide the characteristics and operations that the objects will employ.

Suppose a class is a prototype of a building. A building contains all the details about the floor,
rooms, doors, windows, etc. we can make as many buildings as we want, based on these
details. Hence, the building can be seen as a class, and we can create as many objects of this
class.

http://www.hellostudy.org Ranjith Kumar


02
CLASSES AND OBJECTS

Let's understand this by an example: let’s say you wanted to track the number of dogs that
may have different attributes like breed and age. If a list is used, the first element could be the
dog’s breed while the second element could represent its age. Let’s suppose there are 100
different dogs, then how would you know which element is supposed to be which? What if you
wanted to add other properties to these dogs? This lacks organization and it’s the exact need
for classes.

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the
class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug
who’s seven years old. You can have many dogs to create many different instances, but without
the class as a guide, you would be lost, not knowing what information is required.
03
CLASSES AND OBJECTS
How to create a class?

How to create an object?


04
CLASSES AND OBJECTS

Blueprint of a class
05
CLASSES AND OBJECTS

instances of a class
06
CLASSES AND OBJECTS

Example code:
07
CLASSES AND OBJECTS

The self parameter: The self-parameter refers to the current instance of the class and
accesses the class variables. We can use any user defined name instead of self.
but using self is good for the other programmers to understand.

http://www.hellostudy.org Ranjith Kumar


08
CLASSES AND OBJECTS

_ _ init _ _ Method: In order to make an instance of a class in Python, a specific function


called __init__ is called. Although it is used to set the object's attributes, it is often referred
to as a constructor.
09
CLASSES AND OBJECTS

_ _ str _ _ Method: is used to define how a class object should be represented as a string.
It is often used to give an object a human-readable textual representation.
10
CLASSES AND OBJECTS
Class and Instance Variables:
• Instance Variables are for data, unique to each instance and
• class variables are for attributes and methods shared by all instances of the class.
• Instance variables are variables whose value is assigned inside a constructor or method
with self
• whereas class variables are variables whose value is assigned in the class.
11
CLASSES AND OBJECTS

The Pass statement :In Python, the pass is a null statement. Therefore, nothing happens
when the pass statement is executed.
• The pass statement is used to have an empty block in a code because the empty code is
not allowed in loops, function definition, class definition. Thus, the pass statement will
results in no operation (NOP).
• Generally, we use it as a placeholder when we do not know what code to write or add
code in a future release. Also it shows error if a blank block exists and thats exactly why
we use pass.
12
CLASSES AND OBJECTS

Modify Object Properties:


Every object has properties associated with them. We can set or modify the object’s
properties after object initialization by calling the property directly using the dot operator.

Deleting the object Property:


13
CLASSES AND OBJECTS

Destructor: A destructor is called when an object is deleted or destroyed. Destructor is used to


perform the clean-up activity before destroying the object, such as closing database
connections or filehandle.
• In Python, destructor is not called manually but completely automatic.
• The special method __del__() is used to define a destructor. For example, when we
execute del object_name destructor gets called automatically and the object gets garbage
collected.
14
CLASSES AND OBJECTS

Inheritance in Classes: The process of inheriting the properties of the parent class into a child
class is called inheritance. The existing class is called a base class or parent class and the
new class is called a subclass or child class or derived class.

• The main purpose of inheritance is the reusability of code because we can use the existing
class to create a new class instead of creating it from scratch.

• For example, In the real world, Car is a sub-class of a Vehicle class. We can create a Car
by inheriting the properties of a Vehicle such as Wheels, Colors, Fuel tank, engine, and
add extra properties in Car as required.
15
CLASSES AND OBJECTS
16
CLASSES AND OBJECTS
Types of Inheritance::
17
CLASSES AND OBJECTS
Types of Inheritance::
18
CLASSES AND OBJECTS
Polymorphism: The word polymorphism means having many forms.
• In simple words, polymorphism allows us to perform the same action in many different
ways.
• For example, Jessa acts as an employee when she is at the office. However, when she is at
home, she acts like a wife. Also, she represents herself differently in different places.
Therefore, the same person takes different forms as per the situation. This is an example of
a built in Polymorphism:
19
CLASSES AND OBJECTS
Polymorphism:
There are 2 types of Polymorphism:
20
CLASSES AND OBJECTS

Method Overloading: The process of calling the same method with different parameters is
known as method overloading. Python does not support method overloading. Python considers
only the latest defined method even if you overload the method. Python will raise a TypeError if
you overload the method.:
21
CLASSES AND OBJECTS
22
CLASSES AND OBJECTS

To overcome the above problem, we can use different ways to achieve the method
overloading. In Python, to overload the class method, we need to write the method’s logic
so that different code executes inside the function depending on the parameter passes.
23
CLASSES AND OBJECTS
24
CLASSES AND OBJECTS

Method Overriding: method overriding polymorphism allows us to defines methods in the


child class that have the same name as the methods in the parent class. This process of
re-implementing the inherited method in the child class is known as Method Overriding.

This Show {B} overrides the


show {A}
1
EXCEPTION HANDLING
2
EXCEPTION HANDLING

What are Errors!??


- Errors are the problems in a program due to which the program will stop the execution
In Python, there are three main 3 types of errors:

1. Syntax errors: also known as parsing errors, occur when you write code that doesn't
follow the correct syntax of the Python language. These errors prevent your code from
being executed and are usually caught by the Python interpreter before your program
runs. They often involve issues like missing parentheses, invalid indentation, or
improper use of keywords.
3
EXCEPTION HANDLING

2. Run time errors (Not defined): Runtime errors, also known as exceptions, occur during
the execution of your program. These errors are raised when something unexpected
happens while the program is running, such as division by zero, trying to access an item in
a list that doesn't exist, or attempting to use a variable that hasn't been defined.
4
EXCEPTION HANDLING

3. logical errors : Logical errors, also known as semantic errors, occur when your code is
syntactically correct and runs without errors, but it doesn't produce the expected or desired
output. These errors can be challenging to identify because they don't result in error
messages. They typically stem from incorrect algorithms, incorrect understanding of the
problem, or flawed logic in your code.
5
EXCEPTION HANDLING

Different types of exceptions or errors in python!

These are just a few examples of the many


types of exceptions that can occur in
Python
6
EXCEPTION HANDLING
Difference between Syntax Error and Exceptions
Syntax Error:
• As the name suggests this error is caused by the wrong syntax in the code. It leads to
the termination of the program.
• Syntax errors must be fixed by the programmer before the code can be executed. They
cannot be handled at runtime.

Exceptions:
• Exceptions are raised when the program is syntactically correct, but the code results in
an error. This error does not stop the execution of the program; however, it changes the
normal flow of the program.
• Exceptions can be handled using try-except blocks
7
EXCEPTION HANDLING

But, How do we fix such errors??


8
EXCEPTION HANDLING

By using a method called Exception Handling


9
EXCEPTION HANDLING

Try and Except Statement : Try and except statements are used to catch and handle
exceptions in Python. Statements that can raise exceptions are kept inside the try clause
and the statements that handle the exception are written inside except clause.
10
EXCEPTION HANDLING
11
EXCEPTION HANDLING

Multiple except block: :


12
EXCEPTION HANDLING

Try with Else Clause:


In Python, you can also use the else clause on the try-except block which must be present
after all the except clauses. The code enters the else block only if the try clause does not
raise an exception.
:
13
EXCEPTION HANDLING
Finally Keyword in Python:
Python provides a keyword finally, which is always executed after the try and except blocks.
The final block always executes after the normal termination of the try block or after the try
block terminates due to some exception.
14
EXCEPTION HANDLING
Raising exceptions for a predefined condition :
• When we want to code for the limitation of certain conditions then we can raise an
exception. The raise statement allows the programmer to force a specific exception to
occur.
• The sole argument in raise indicates the exception to be raised. This must be either an
exception instance or an exception class (a class that derives from Exception).
15
EXCEPTION HANDLING
16
EXCEPTION HANDLING
Advantages of Exception Handling:
• Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or
input.
• Simplified error handling: Exception handling allows you to separate error handling
code from the main program logic, making it easier to read and maintain your code.
• Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.
• Easier debugging: When an exception is raised, the Python interpreter prints a
traceback that shows the exact location where the exception occurred, making it
easier to debug your code.
17
EXCEPTION HANDLING
Disadvantages of Exception Handling:
• Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to
catch and handle the exception.

• Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex
error handling logic.

• Possible security risks: Improperly handled exceptions can potentially reveal


sensitive information or create security vulnerabilities in your code, so it’s important
to handle exceptions carefully and avoid exposing too much information about your
17
EXCEPTION HANDLING
Disadvantages of Exception Handling:
• Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to
catch and handle the exception.

• Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex
error handling logic.

• Possible security risks: Improperly handled exceptions can potentially reveal


sensitive information or create security vulnerabilities in your code, so it’s important
to handle exceptions carefully and avoid exposing too much information about your
1
PYTHON LIBRARIES

Why do we use libraries: You must have read and enjoyed a lot of books-story books,
novels, course-books, reference books etc. And, if you recall, all these book types have
one thing in common. Confused? Don't be all these book types are further divided into
chapters. Can you tell, why is this done? Yeah, you are right. Putting all the pages of
one book or novel together, with no chapters, will make the book boring, and difficult to
comprehend. So, dividing a bigger unit into smaller manageable units is a good
strategy.

Similarly, in programming, if we create smaller handleable units, these are called


modules. A library refers to a collection of modules that together cater to specific type of
needs or applications eg, NumPy library of Python caters to scientific computing needs.
2
PYTHON LIBRARIES
WHAT IS A LIBRARY?
a library is a collection of modules (and packages) that together cater to a specific type of
applications or requirements. A library can have multiple modules. Some commonly used
Python libraries are as listed below:

(1) Python standard library: This library is distributed with Python that contains modules for
various types of functionalities. Some commonly used modules of Python standard library are

• math module, which provides mathematical functions to support different types of


calculations.

• cmath module, which provides mathematical functions for complex numbers random
module, which provides functions for generating pseudo-random numbers
3
PYTHON LIBRARIES
• statistics module, which provides mathematical statistics functions.

• Urilib module, which provides URL handling functions so that you can access websites from
within your program

(2) Numpy library. This library provides some advance math functionalities along with tools to
create and manipulate numeric arrays

(3) SciPy library. This is another useful library that offers algorithmic and mathematical tools for
scientific calculations.

(4) tkinter library. This library provides traditional Python user interface toolkit and helps you to
create useriniendly GUI interface for different types of applications.
4
PYTHON LIBRARIES

(v) Malplotlib library. This library offers many functions and tools to produce quality output in
variety of formats such as plots, charts, graphs etc

WHAT IS MODULE?
The act of partitioning a program into individual components (known as modules) is called
modularity. A module is a separate unit in itself. The justification for partitioning a program is that

• it reduces its complexity to some degree and


• it creates a number of well-defined, documented boundaries within the program.

Another useful feature of having modules, is that its contents can be reused in other without
having to rewrite or recreate them. programs,
5
PYTHON LIBRARIES

A Python module can contain much more than just functions. A Python module is a normal
Python file (.py file) containing one or more of the following objects related to a particular task:
• docstrings
• Variables and consonants
• Objects and classes
• Statements and functions
So, we can say that the module XYZ means it is tile “ XYZ.py”
6
PYTHON LIBRARIES
7
PYTHON LIBRARIES

Lets take an example:

Package Module
8
PYTHON LIBRARIES
How to access Module?
As mentioned before, in Python if you want to use the definitions inside a module, then you need
to first import the module in your program. Python provides import statement to import modules
in a program. The import statement can be used in two forms

(1) to import entire module :

(2) to import selected objects:


from a module
9
PYTHON LIBRARIES
10
PYTHON LIBRARIES
importing an entire module and many modules:
The import statement can be used to import entire module and even for importing selected
items. To import entire module, the import statement can be used as per following syntax:

For example, to import a module, say time, you'll write :

To import two modules namely decimals and fractions, you'll write:


11
PYTHON LIBRARIES
Another way!!!
12
PYTHON LIBRARIES
To Import Multiple Objects:
If you want to import multiple objects from the module like this so that you don't have to
prefix the module's name, you can write the comma separated list of objects after keyword
import. For instance, to import just two functions sqrt() and pow() from math module, you'll
write :

To Import All Objects of a Module:


If you want to import all the items from the module like this so that you don't have to prefix
the module's name, you can write :
13
PYTHON LIBRARIES
To Import Multiple Objects:
If you want to import multiple objects from the module like this so that you don't have to
prefix the module's name, you can write the comma separated list of objects after keyword
import. For instance, to import just two functions sqrt() and pow() from math module, you'll
write :

To Import All Objects of a Module:


If you want to import all the items from the module like this so that you don't have to prefix
the module's name, you can write :
14
PYTHON LIBRARIES

PYTHON STANDARD LIBRARIES: Python's standard library is very extensive that offers
many built-in functions that you can use without having to import any library. Python's
standard library is by default available, so you don't need to import it separately.

1. Math module
2. Random module - Python has a module namely ‘random’ that provides random-number
generators. A random number in simple words means - a number generated by chance,
i.e., randomly.

To use random number generators in your Python program, you first need to import
module random using an import command.
15
PYTHON LIBRARIES

Two most common random number generator functions in random module are:
• random() - it returns a random floating point number N in the range [0.0, 1.0), i.e., 0.0≤ N
<1.0. Notice that the number generated with random() will always be less than 1.0. (only
lower range-limit is inclusive). Remember, it generates a floating point number.

• randint(a,b) - it returns a random integer N in the range (a, b), i.e., a≤ N ≤b


(both range-limits are inclusive). Remember, it generates an integer. Let us consider
some examples. In the following lines we are giving some sample codes along with their
output.
16
PYTHON LIBRARIES
17
PYTHON LIBRARIES

3. urilib module: Python offers you module urllib using which you can send http requests and
receive the result from within your Python program. To use urllib in your program to get details
about a website. The urllib module is a collection of sub-modules like request, error, parse etc.

(i) urllib.request.urlopen (<URL>) - opens a website or network object denoted by URL for
reading and returns a file-like object

(ii) <urlopen's returnval>.read() - returns the html or the source code of given url opened via
urlopen()
18
PYTHON LIBRARIES

(iii) <urlopen' return val>.getcode() - returns HTTP status code where 200 means 'all okay'.
301, 302 mean some kind of redirection happened.

(iv) <urlopen's return val>.headers - Stores metadata about the opened URL

(v) <urlopen's return val>.info() -returns same information as stored by headers

(vi) <copy>.geturl() - returns the url string


19
PYTHON LIBRARIES

Following program will use all above functions and urllib, but before that lets use webbrowser
module, using which you can open a URL in a window/tab.

http://www.hellostudy.org Ranjith Kumar


20
PYTHON LIBRARIES

This above code will then open the webpage

http://www.hellostudy.org Ranjith Kumar


21
PYTHON LIBRARIES

This above code will then open the webpage

http://www.hellostudy.org Ranjith Kumar


22
PYTHON LIBRARIES

Packages: As you know that Python packages are basically collections of modules under
common namespace. This common namespace is created via a directory that contains all
related modules. But here you should know one thing that NOT ALL folders having multiple
‘.py’ files (i.e., modules) are packages. In order for a folder containing Python files to be
recognized as a package, an __init__.py file (even if empty) must be part of the folder.

http://www.hellostudy.org Ranjith Kumar


23
PYTHON LIBRARIES

Library: A library can have one or more packages and subpackages.

http://www.hellostudy.org Ranjith Kumar


24
PYTHON LIBRARIES

Let us now create a library and packages in pycharm:

http://www.hellostudy.org Ranjith Kumar


25
PYTHON
The Module Path: When a module LIBRARIES
named spam is imported, the interpreter first searches
for a built-in module with that name. These module names are listed in
sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list
of directories given by the variable sys.path. sys.path is initialized from these locations:
• The directory containing the input script (or the current directory when no file is
specified).
• PYTHONPATH (a list of directory names, with the same syntax as the shell variable
PATH).
• The installation-dependent default (by convention including a site-packages directory,
handled by the site module).
26
PYTHON LIBRARIES

in windows shell type


Environment Variables
27
PYTHON LIBRARIES

This is PYTHONPATH
28
FILE HANDLING

Most computer programs work with files. This is because files help in storing information
permanently. Word processors create document files; Database programs create files of
information; Compilers read source files and generate executable files. So, we see, it is the
files that are mostly worked with, inside programs.

A file in itself is a bunch of bytes stored on some storage device like hard-disk, thumb-drive
etc. Every programming language offers some provision to use and create files through
programs. Python is no exception and in this chapter, you shall be learning to work with data
files through Python programs
29
FILE HANDLING

Data Files: The data files are the files that store data pertaining to a specific application, for
later use. The data files can be stored in two ways:
• Text files
• Binary files

Text Files: A text file stores information in ASCII or Unicode characters (the one which is default
for your programming platform). In text files, each line of text is terminated, (delimited) with a
special character known as EOL (End of Line) character. In text files, some internal translations
take place when this EOL character is read or written. In Python, by default, this EOL character
is the newline character ('\n') or carriage-return, newline combination ('\r\n').
30
FILE HANDLING
Binary Files: A binary file is just a file that contains information in the same format in which the
information is held in memory, i.e., the file content that is returned to you is raw (with no
translation or no specific encoding). In binary file, there is no delimiter for a line. Also no
translations occur in binary files. As a result, binary files are faster and easier for a program to
read and write than are text files. As long as the file doesn't need to be read by people or
need to be ported to a different type of system, binary files are the best way to store program
information.

Opening Files andClosing Files: In order to work with a file from within a Python program, you
need to open it in a specific mode as per the file manipulation task you want to perform. The
most basic file manipulation tasks include adding, modifying or deleting data in a file, which in
http://www.hellostudy.org
turn include any one or combination of the following operations: Ranjith Kumar
31
FILE HANDLING

• reading data from files


• appending data to files
• writing data to files
Open() and close() function:
32
FILE HANDLING
32
FILE HANDLING
33

You might also like