Introduction To Python - Teena
Introduction To Python - Teena
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.
• Rossum chose the name "Python", since he was a big fan of Monty
Python's Flying Circus.
3
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.
PYTHON VERSIONS
PYTHON FEATURES
7
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
MODE OF EXECUTION
TOKENS IN PYTHON
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 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
TOKENS IN PYTHON
4. Operators: Operators are tokens that trigger some computation/action when applied to
variables and other objects in an expression.
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
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
• 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
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
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.
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
(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
• 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.
(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
• 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.
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:
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:
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.
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
• 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
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 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.
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
• 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.
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
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.
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.
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:
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:
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:
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
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
Library Functions: These functions are provided by a Python’s package and a user only need to
call it in your program.
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
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.)
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.
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
• We know that the function will only work when it is being Called.
like, CalcSomething(4),
greet("Bob").. etc
Execution Frame
18
FUNCTIONS
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.
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:
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
• 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
• 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:
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
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
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
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.
Multiply argument 'a' with argument 'b' and return the result:
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
Recursion
statement
3
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
(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,
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
Note: The recursion code can always be written in an iterative way as well
LIKE :
13
RECURSIONS
1. Factorial recursively:
14
RECURSIONS
2. GCD recursively:
15
RECURSIONS
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
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.
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?
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.
_ _ 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
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
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
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
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
• 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.
• 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.
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.
(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
• 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
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
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
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.
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
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.
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.
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