Python Complete Notes
Python Complete Notes
Python Complete Notes
Displays and Indentation error as shown below because of the extra space given in the third line
Note: Besides the Three Errors Syntax Errors, Logical Errors and Exception Errors, Python
undergoes Indentation Error which we normally face while we encounter loops.
>>> 3 + 4
7
>>> 1 + 2 + 4 + 10 + 3
20
>>> print(1 + 2 + 4 + 10 + 3)
20
Running Simple and Sample Programs:
Write a python code to display your name
Program:
#To display your name
name=input("enter your name:")
***
Python Keywords
Keywords are the reserved words in Python where the meaning cannot be changed.
Keywords: False, await, else, import, pass, none, break, except, in ,raise, True, class, finally,
is, return, and, continue, for, lambda, try, as, def, from, nonlocal, while, assert, del, global,
not, with, async, elif, if, or and yield.
Python Identifiers
An identifier is a name given to entities(objects) like class, functions, variables, etc. It helps to
differentiate one entity from another.
website = "apple.com"
print(website)
website = "programiz.com"
print(website)
Output:
apple.com
programiz.com
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
x = y = z = "same"
print (x)
print (y)
print (z)
Statement
A statement is an instruction that a Python interpreter can execute. Python statement ends
with the token NEWLINE character. It means each line in a Python script is a statement.
• Print statements,
• Assignment statements,
• Conditional statements,
• Looping statements.
# statement 1
print('Hello')
# statement 2
x = 20
print(x)
Output: Hello
20
l = 10; b = 5
# statement 3
print('Area of rectangle:', l * b)
Multi-Line Statements
Python statement ends with the token NEWLINE character. But we can extend the statement
over multiple lines using line continuation character (\). This is known as an explicit
continuation.
addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
print(addition)
# Output: 280
• Multi-Line Statements
• Python Compound Statements
• Simple Statements
• Expression statements
• The pass statement
• The del statement
***
Input : Any information or data sent to the computer from the user through the keyboard is
called input.
Output: The information produced by the computer to the user is called output. Python
provides us with the two inbuilt functions as input() and output().
Syntax: input(prompt_message);
Note: The python will automatically identify whether the user entered a string, number, or list;
Syntax: print(), normally used to print the output.
i=int(x)
j=int(y)
Example 3: Write a Python Program to read the employee details and print the same
Output:
Is employee married?[True|False]:True
Indentation
Python uses indentation to indicate a block of code.Indentation refers to the spaces at the
beginning of a code line.
Example 1:
if 5 > 2:
Output:
Example 2:
if 5 > 2:
Output:
Example 3:
if 5 > 2:
if 5 > 2:
Output:
Example 4:
if 5 > 2:
Output:
Example 5:
a = 33
b = 200
if b > a:
Output:
b is greater than a
Example 6:
a = 33
b = 200
if b > a:
Output:
The arguments that are given after the name of the program in the command line shell of the
operating system are known as Command Line Arguments.
Python provides various ways of dealing with these types of arguments. The three most
common are:
• Using sys.argv
• Using getopt module
• Using argparse module
Using sys.argv
The sys module provides functions and variables used to manipulate different parts of the
Python runtime environment. This module provides access to some variables used or
maintained by the interpreter and to functions that interact strongly with the interpreter.
Python getopt module is similar to the getopt() function of C. Unlike sys module getopt
module extends the separation of the input string by parameter validation. It allows both
short, and long options including a value assignment. However, this module requires the use
of the sys module to process input data properly. To use getopt module, it is required to
remove the first element from the list of command-line arguments.
Using argparse module is a better option than the above two options as it provides a lot of
options such as positional arguments, default value for arguments, help message, specifying
data type of argument etc.
Note: As a default optional argument, it includes -h, along with its long version –help.
***
The interactive shell attempts to evaluate both expressions and statements. In this case, the
expression 4 evaluates to 4. The shell executes what is commonly called the read, eval, print
loop. This means the interactive shell’s sole activity consists of
1. reading the text entered by the user,
2. attempting to evaluate the user’s input in the context of what the user has entered up that
point, and
3. printing its evaluation of the user’s input.
If the user enters a 4, the shell interprets it as a 4. If the user enters x = 10, a statement has no
overall value itself, the shell prints nothing. If the user then enters x, the shell prints the
evaluation of x, which is 10. If the user next enters y, the shell reports a error because y has
not been defined in a previous interaction. Python uses the + symbol with integers to perform
normal arithmetic addition, so the interactive shell can serve as a handy adding machine:
Python recognizes both single quotes (') and double quotes (") as valid ways to delimit a
string value. The word delimit means to determine the boundaries or limits of something. The
left ' symbol determines the beginning of a string, and the right ' symbol that follows specifies
the end of the string. If a single quote marks the beginning of a string value, a single quote
must delimit the end of the string. Similarly, the double quotes, if used instead, must appear
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
in pairs. You may not mix the two kinds of quotation marks when used to delimit a particular
string, as the following interactive sequence shows:
The interpreter’s output always uses single quotes, but it accepts either single or double
quotes as valid input. Consider the following interaction sequence:
It is important to note that the expressions 4 and '4' are different. One is an integer expression
and the other is a string expression. All expressions in Python have a type. The type of an
expression indicates the kind of expression it is. An expression’s type is sometimes denoted
as its class. At this point we have considered only integers and strings. The built in type
function reveals the type of any Python expression:
Python associates the type name int with integer expressions and str with string expressions.
The built-in int function creates an actual integer object from a string that looks like an
integer, and the str function creates a string object from the digits that make up an integer:
The expression str(4) evaluates to the string value '4', and int('5') evaluates to the integer
value 5. The int function applied to an integer evaluates simply to the value of the integer
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
itself, and similarly str applied to a string results in the same value as the original string. Any
integer has a string representation, but not all strings have an integer equivalent:
In Python, neither wow nor 3.4 represent valid integer expressions. In short, if the contents of
the string (the characters that make it up) look like a valid integer number, you safely can
apply the int function to produce the represented integer.
The plus operator (+) works differently for strings; consider:
The plus operator splices two strings together in a process known as concatenation. Mixing
the two types directly is not allowed:
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Boolean Expressions
Arithmetic expressions evaluate to numeric values; a Boolean expression, sometimes called a
predicate, may have only one of two possible values: false or true. The term Boolean comes
from the name of the British mathematician George Boole. A branch of discrete mathematics
called Boolean algebra is dedicated to the study of the properties and the manipulation of
logical expressions. The simplest Boolean expressions in Python are True and False. In a
Python interactive shell we see:
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
An expression like 10 < 20 is legal but of little use, since 10 < 20 is always true; the
expression True is equivalent, simpler, and less likely to confuse human readers. Since
variables can change their values during a program’s execution, Boolean expressions are
most useful when their truth values depend on the values of one or more variables. The first
input in the shell binds the variable x to the value 10. The other expressions experiment with
the relational operators. Exactly matching their mathematical representations, the following
expressions all are equivalent:
• x < 10
• 10 > x
• !(x >= 10)
• !(10 <= x)
The relational operators are binary operators and are all left associative. They all have a lower
precedence than any of the arithmetic operators; therefore, Python evaluates the expression
x + 2 < y / 10
as if parentheses were placed as so:
(x + 2) < (y / 10)
***
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-5 Python Programming
Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators:
Arithmetic Operators some basic arithmetic operators are +,-,*,/,%,**, and //. You can apply
these operators on numbers as well as variables to perform corresponding operations.
Example:
a=21
b=10
OUTPUT
print("Addition is ",a+b)
print("Subtraction is=",a-b)
print("Multiplication is=",a*b)
print("Modulus is=",a%b)
a=2
b=3
print("Power value is=",a**b)
a=10
b=4
print("Floor Division is=",a//b)
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Comparison (Relational) Operators:
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators. Assume variable a holds 10 and variable b
holds 20, then:
Example:
a=10
b=30
if a<b:
print("b is big") OUTPUT
elif a>b:
print("a is big")
else:
print("both are equal")
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Assignment Operators:
Python Assignment operator is used for assigning the value of right operand to the left
operand.
Example:
a=20
b=10
c=a+b
print(c)
c+=a
print("value of c+=a is:",c)
c-=a
print("value of c-=a is:",c)
c*=a
print("value of c*=a is:",c)
c/=a OUTPUT
print("value of c/=a is:",c)
c%=a
print("value of c%=a is:",c)
c**=a
print("value of c**=a is:",c)
c//=a
print("value of c//=a is:",c)
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Logical operator
Logical operators in Python are used for conditional statements are true or false. Logical
operators in Python are AND, OR and NOT. For logical operators following condition are
applied.
• For AND operator – It returns TRUE if both the operands (right side and left side) are
true.
• For OR operator- It returns TRUE if either of the operand (right side or left side) is
true.
• For NOT operator- returns TRUE if operand is false.
Example:
a = True
b = False OUTPUT
print(('a AND b is',a and b))
print(('a OR b is',a or b))
print(('NOT a is',not a))
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-6 Python Programming
Operators
Bitwise Operators:
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
Example:
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
a=60
b=13
c=a&b
print("a&b=",c) Output:
c=a|b
print("a|b=",c)
c=a^b
print("a^b=",c)
c=~a
print("~a=",c)
c=a<<2
print("a<<2=",c)
c=a>>2
print("a>>2=",c)
Membership Operators:
Membership operators are operators used to validate the membership of a value. It tests for
membership in a sequence, such as strings, lists, or tuples. There are two membership
operators.
• In Operator
• Not in Operator
in operator:
The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it
finds a variable in the specified sequence and false otherwise.
list1=[1,2,3,4,5] OUTPUT:
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
x = 24
y = 20
list = [10, 20, 30, 40, 50 ];
if ( x not in list ):
print("x is NOT present in given list")
else: OUTPUT:
print("x is present in given list")
if ( y in list ):
print("y is present in given list")
else:
print("y is NOT present in given list")
Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity
operators.
• Is Operator
• Not is Operator
‘is’ operator:
It evaluates to true if the variables on either side of the operator point to the same object and
false otherwise.
Example:
x=5
OUTPUT:
if (type(x) is int):
print ("true")
else:
print ("false")
‘isnot’operator –
Evaluates to false if the variables on either side of the operator point to the same object and
true otherwise.
x = 5.2
if (type(x) is not int):
OUTPUT:
print ("true")
else:
print ("false")
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-7 Python Programming
Expressions:
Evaluation of an Expression:
The process of determining the expression’s value is called “evaluation of an expression”.
Example:
a = 10
b = 20
print(a+b)
Output: 30
In general, expressions are evaluated using an assignment statement of the form
variable = expression
here expression gets evaluated first and then value is assigned to variable on the left hand
side of an assignment statement.
Example:
a = 10
b = 20
c = a+b
print(c)
Output:
30
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Mixed Type Expressions:
Expressions may contain mixed integer and floating-point elements.
Example:
x=4
y = 10.2
sum = x + y
print(sum)
Here, x is an integer and
y is a floating-point number and
x + y is a floating-point expression, and
the assignment will make the variable sum bind to a floating-point value.
Output:
14.2
All Python operators have a precedence and associativity. Python has well-defined rules for
specifying the order in which the operators in an expression are evaluated when the
expression has several operators. For example, multiplication and division have a higher
precedence than addition and subtraction.
Precedence –
Precedence / Priority indicate that which operator has to be evaluated first if the given
expression contains more than one operator.
Example:
The expression
10 - 4 * 2 evaluates to 2.
Here, multiplication is performed before addition, since multiplication has highest precedence
over addition.
Example:
10 - 4 * 2
Output:
2
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Example:
a = 10
b = 22
c=3
x=a*b+c
y=a-b*c
print(x)
223
print(y)
-56
Associativity –
If an expression contains different operators but with same precedence, then associativity
helps to determine the order of operations. For example, multiplication and floor division
have the same precedence. Hence, if both of them are present in an expression, the left one is
evaluated first.
There are 2 types of associativity:
a) Left to right
b) Right to left
Left to right associativity:
Here, the operators are having associativity which is from left to right. For example,
arithmetic operators have left to right associativity.
Example:
The expression 2 - 3 - 4 evaluates to -5.
Here, the evaluation is done from left to right since subtraction operator is left associative.
Example:
# Shows left-right associativity
print(5 * 2 // 3)
Output:
3
Right to left associativity:
Here, the operators are having associativity which is from right to left. For example, the
exponent operator i.e., ** has right-to-left associativity in Python.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Example:
# Shows the right-left associativity of **
print(2 ** 3 ** 2)
Output:
512, Since 2**(3**2) = 2**9
The assignment operator is a different kind of operator from the arithmetic operators. The
notions of precedence and associativity do not apply in the context of the assignment
operator. Python support a special kind of assignment statement called chained assignment.
Example:
The statement
w=x=y=z
assigns the value of the rightmost variable (i.e., z) to all the other variables (w, x, and y) to its
left.
The following table shows precedence of different operators in Python:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-8 Python Programming
Conditional Statements:
• Also known as Decision making / Selection statements.
• Decision making is the most important aspect of almost all the programming
languages.
• These statements have the ability to compare values (make decisions) and allows to
run a particular block of code depending on the outcome of the condition i.e., either
TRUE or FALSE.
• Python supports different decision making statements. They are:
a) Simple if,
b) if-else,
c) nested if
d) elif statement
NOTE: Python requires the block to be indented.
Simple if:
Syntax:
The general form/syntax of if statement is
if condition:
statement(s) #if block
Flowchart for if statement is shown in figure:
• Above syntax started with the reserved word if.
• The condition is a Boolean expression that determines
whether or not the body will be executed.
• A colon (:) must follow the condition.
• If the condition is true, then it the block of statement(s) known as “if-block (or) body
of if” gets executed.
• If the condition is false, then control doesn’t enter into if block and executes the
statements followed by if block.
• In Python, the body of if statement is indicated by the indentation.
• The statements within the block must all be indented the same number of spaces from
the left. The body starts with an indentation and the first unintented line marks the
end.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Example:
num = int(input("enter the number: "))
if num%2 == 0:
print("Number is even")
Output:
enter the number: 10
Number is even
If-Else:
Syntax:
The general form/syntax of if-else statement is
if condition:
statement(s) # if block
else:
statement(s) #else block
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
nested if:
When a series of decision are involved, we may have to use more than one if-else statement
in the nested form.
Syntax:
The general form/syntax of nested if is
if condition1:
if condition2:
statement1 # block1
else:
statement2 # block2
else:
if condition3:
statement3 # block3
else:
statement4 # block4
next_statement
Flowchart for nested if is as shown in figure:
Example:
# Example of nested if statement
a=int(input("Enter A: "))
b=int(input("Enter B: "))
c=int(input("Enter C: "))
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
if a>b:
if a>c:
g=a
else:
g=c
else:
if b>c:
g=b
else:
g=c
print("Greater = ",g)
Output
Enter A: 10
Enter B: 20
Enter C: 5
Greater = 20
elif statement:
Syntax:
The general form/syntax of elif is
if condition-1:
Statement-1
elif condition-2:
Statement-2
elif condition-3:
Statement-3
............
elif condition-n:
Statement-n
else:
Default Statement
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Flowchart for elif is as shown in figure:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
ticket_price = 10
else:
ticket_price = 18
print("amount to pay for ticket is",ticket_price,"rupees")
Output:
Enter your age: 4
amount to pay for ticket is 5 rupees
Enter your age: 7
amount to pay for ticket is 10 rupees
Enter your age: 20
amount to pay for ticket is 18 rupees
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-09 Python Programming
Pass Statement:
The pass statement is a null statement. But the difference between pass and comment is that
comment is ignored by the interpreter whereas pass is not ignored.
The pass statement is generally used as a placeholder i.e. when the user does not know
what code to write. So user simply places pass at that line.
Sometimes, pass is used when the user doesn’t want any code to execute. So user can
simply place pass where empty code is not allowed, like in loops, function definitions,
class definitions, or in if statements. So using pass statement user avoids this error.
Synatax:
Pass
Example 3: Pass statement can be used in for loop when user doesn’t know what to
code inside the loop
n = 10
for i in range(n):
# pass can be used as placeholder
# when code is to added later
pass
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
print("b<a")
Iteration Statements:
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many
programming problems. Iteration and conditional execution form the basis for algorithm
construction.
Python supports different iterative/looping statements. They are:
a) while
b) for
while:
Syntax:
The general form/syntax of while is
while expression:
statements #block of statements
Flowchart for while statement is shown in figure:
• The reserved word while begins the while
statement.
• The condition determines whether the body will
be (or will continue to be) executed.
• A colon (:) must follow the condition.
• block is a block of one or more statements to be
executed as long as the condition is true.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
• As a block, all the statements that comprise the block must be indented one level
deeper than the line that begins the while statement.
• The block technically is part of the while statement.
Example:
#printing numbers from 1 to 5 using while
i=1
while i < 6:
print(i)
i = i+1
Output:
1
2
3
4
5
Example:
#factorial of a number in using while
n = int(input("enter a number: "))
f=1
while n>0:
f=f*n
n=n–1
print("factorial is ", f)
Output:
enter a number: 5
factorial is 120
for:
Syntax:
The general form/syntax of for is
for var in sequence:
loop body
for statement flowchart is shown in figure:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
• The for statement iterates over a sequence of
values.
• It can be used to execute a group of statements
repeatedly depending upon the number of
elements in the sequence.
• It can be used to work with sequence like
string, list and tuple.
• Here, the variable takes the value of the item
inside the sequence for each iteration.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
✓ step is the amount to increment or decrement; if the step parameter is omitted, it
defaults to 1 (countsup by ones).
✓ begin, end, and step must all be integer expressions; floating-point expressions and
other types are not allowed.
Example:
for n in range(21, 0, -3):
print(n, end=' ')
Output:
21 18 15 12 9 6 3
Example:
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
Output:
Enter the number 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
nested for:
One loop within another loop is known as “nested loop”. Python allows us to nest any
number of for loops inside a for loop.
When a series of decision are involved, we may have to use more than one if-else statement
in the nested form.
Syntax:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
The general form/syntax of nested for is
for var1 in sequence: #outer loop
for var2 in sequence: #inner loop
block of statements
Example:
n = int(input("Enter the number of rows:"))
for i in range(0,n+1):
for j in range(i):
print(i,end = '')
print()
Output:
Enter the number of rows:5
1
22
333
4444
55555
Loop Control Statements:
Loop control statements change execution from its normal sequence. Python supports
different loop control statements. They are:
✓ break
✓ continue
✓ pass
break:
• Break statement in Python is used to bring the control out of the loop and transfers
execution to the statement immediately following the loop.
Syntax:
break
Flowchart for break is as shown in figure:
Example:
#Sample example for break
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
count = 0
while count <= 100:
print (count)
count += 1
if count >= 3:
break
Output:
0
1
2
Continue:
• 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.
• Unlike break, continue statement continues the loop.
Syntax:
continue
Flowchart for continue is as shown in figure:
Example:
#Sample example for continue
for x in range(10):
if x % 2 == 0:
continue
print (x)
Output:
1
3
5
7
9
Pass statement:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
• Python has a special statement called pass, which means do nothing.
• We may use the pass statement in our code in places where the language requires a
statement to appear but we wish the program to take no action whatsoever.
• pass statement is a no-operation placeholder that is used when the syntax requires a
statement, but have nothing useful to say.
• It is often used to code an empty body for a compound statement.
Example:
#Sample example for pass
x = int(input(“Enter any value”))
if x < 0:
pass # Do nothing
else:
print(x)
Output:
Enter any value:5
5
Enter any value:-5
Explanation:
• .If entered input is negative, then it executes pass statement and does nothing.
Otherwise, it executes print statement and prints the input.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-10 Python Programming
Lists
A list is a sequence of data values called items or elements. An item can be of any type.
➢ The logical structure of a list resembles the structure of a string. Each of the items in a
list is ordered by position.
➢ Like a character in a string, each item in a list has a unique index that specifies its
position.
➢ The index of the first item is 0, and the index of the last item is the length of the list
minus 1.
➢ As sequences, lists and strings share many of the same operators, but they include
different sets of methods.
Literal string values are written as sequences of characters enclosed in quote marks. In
Python, a list literal is written as a sequence of data values separated by commas.
>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
List Traversals:
Example:
length = len(list)
for i in range(length):
print(list[i])
Example:
list = [1, 3, 5, 7, 9]
# Using enumerate()
Example:
for i in list:
print(i)
Example:
# Python3 code to iterate over a list
list = [2, 4, 6, 8, 10]
# Getting length of list
length = len(list)
i=0
# Iterating using while loop
while i < length:
print(list[i])
i += 1
• List Comprehension
• Lambda function
• Python NumPy module
Example 1:
>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]
>>> days
Output:
Example 2:
>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
>>> print(languages)
Output:
Indexing
>>> languages[0]
Output:
[‘English’]
Slicing:
When you want only a part of a Python list, you can use the slicing operator [].
>>> indices=['zero','one','two','three','four','five']
>>> indices[2:4]
Output
[‘two’, ‘three’]
This returns items from index 2 to index 4-1 (i.e., 3)
>>> indices[:4]
Output
[‘zero’, ‘one’, ‘two’, ‘three’]
This returns items from the beginning of the list to index 3.
>>> indices[4:]
Output
[‘four’, ‘five’]
It returns items from index 4 to the end of the list in Python.
>>> indices[:]
Output
[‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’]
This returns the whole list.
>>> indices[:-2]
Output
[‘zero’, ‘one’, ‘two’, ‘three’]
This returns item from the list’s beginning to two items from the end.
>>> indices[1:-2]
Output
[‘one’, ‘two’, ‘three’]
It returns items from the item at index 1 to two items from the end.
>>> indices[-2:-1]
Output
[‘four’]
This returns items from two from the end to one from the end.
>>> indices[-1:-2]
Output
[]
This returns an empty Python list, because the start is ahead of the stop for the traversal.
***
List Methods:
A method is what you can do to it and change it. To call a method on a construct, you use the
dot-operator(.). Python supports some built-in methods to alter a Python list.
a. append()
It adds an item to the end of the list.
>>> a
Output
[2, 1, 3]
>>> a.append(4)
>>> a
Output
[2, 1, 3, 4]
b. insert()
It inserts an item at a specified position.
>>> a.insert(3,5)
>>> a
Output
[2, 1, 3, 5, 4]
This inserted the element 5 at index 3.
c. remove()
It removes the first instance of an item from the Python list.
>>> a=[2,1,3,5,2,4]
>>> a.remove(2)
>>> a
Output
[1, 3, 5, 2, 4]
d. pop()
It removes the element at the specified index, and prints it to the screen.
>>> a.pop(3)
Output
2
>>> a
Output
[1, 3, 5, 4]
e. clear()
It empties the Python list.
>>> a.clear()
>>> a
Output
[]
It now has a False value.
>>> bool(a)
Output
False
f. index()
It returns the first matching index of the item specified.
>>> a=[1,3,5,3,4]
>>> a.index(3)
Output
1
g. count()
It returns the count of the item specified.
>>> a.count(3)
h. sort()
It sorts the list in an ascending order.
>>> a.sort()
>>> a
Output
[1, 3, 3, 4, 5]
i. reverse()
It reverses the order of elements in the Python lists.
>>> a.reverse()
>>> a
Output
[5, 4, 3, 3, 1]
List Comprehension:
Creation of a new list just like you would do in mathematics. To do so, type an expression
followed by a for statement, all inside square brackets. You may assign it to a variable. Let’s
make a list for all even numbers from 1 to 20.
Multi-Dimensional List
A one-dimensional list is a simple list without any sublists. A two-dimensional list is a list that
solely contains many single-dimensional lists. A three-dimensional list solely contains many
two-dimensional lists that solely contains many single-dimensional lists. This concludes that
Multi-dimensional lists are the lists within the lists within the lists within the lists and so on.
Example 1:
>>> grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil']]
>>> grocery_list
Output
[[‘caramel’, ‘P&B’, ‘Jelly’], [‘onions’, ‘potatoes’], [‘flour’, ‘oil’]]
This is a grocery Python list with lists in it, where the lists are according to a category.
Or, you can choose to go deeper.
Example 2:
>>> a=[[[1,2],[3,4],5],[6,7]]
>>> a
>>> a[0][1][1]
Output
4
Example 4:
rows=[]
columns=[]
for i in range(3):
for j in range(3):
columns.append(1)
rows.append(columns)
Example 5:
for i in range(len(rows)):
for j in range(len(columns)):
print(rows[i][j],end="")
print("\n")
Output:
111
111
111
Introduction to Strings
A string is a sequence of characters. Strings most often contain nonnumeric characters:
Python recognizes both single quotes (') and double quotes (") as valid ways to delimit a
string value.
The word delimit means to determine the boundaries or limits of something. The left ' symbol
determines the beginning of a string, and the right ' symbol that follows specifies the end of
the string.
If a single quote marks the beginning of a string value, a single quote must delimit the end of
the string.
Similarly, the double quotes, if used instead, must appear in pairs.
You may not mix the two kinds of quotation marks when used to delimit a particular string,
as the following interactive sequence shows:
The interpreter’s output always uses single quotes, but it accepts either single or double
quotes as valid input.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Consider the following interaction Sequence
Notice that with the missing quotation marks the interpreter does not accept the expression
Fred.
It is important to note that the expressions 4 and '4' are different. One is an integer expression
and the other is a string expression.
All expressions in Python have a type. The type of an expression indicates the kind of
expression it is. An expression’s type is sometimes denoted as its class. At this point we have
considered only integers and strings.
The built in type function reveals the type of any Python expression:
Python associates the type name int with integer expressions and str with string expressions.
The built-in int function creates an actual integer object from a string that looks like an
integer, and the str function creates a string object from the digits that make up an integer:
The expression str(4) evaluates to the string value '4', and int('5') evaluates to the integer
value 5.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
The plus operator (+) works differently for strings; consider:
Programming Exercise:
S="This is GMRIT"
C=len(S.split())
print(C)
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-14 Python Programming
String Formatting
String formatting is the process of infusing things in the string dynamically and presenting the
string.
There are four different ways to perform string formatting:-
1. Formatting with % Operator.
2. Formatting with format() string method.
3. Formatting with string literals, called f-strings.
4. Formatting with String Template Class
You can also inject multiple strings at a time and can also use variables to insert objects in the
string.
Example: Injecting multiple strings using % operator
x = 'looked'
print("Misha %s and %s around"%('walked',x))
Output:
Misha walked and looked around.
‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point values, ‘%b’ for
binary format. For all formats, conversion methods visit the official documentation.
Example:
print('Joe stood up and %s to the crowd.' %'spoke')
print('There are %d dogs.' %4)
Output:
Joe stood up and spoke to the crowd.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
There are 4 dogs.
Float precision with the placeholder method:
Floating-point numbers use the format %a.bf. Here, a would be the minimum number of digits to be
present in the string; these might be padded with white space if the whole number doesn’t have this
many digits. Close to this, bf represents how many digits are to be displayed after the decimal
point.
Example 1: Float point precision using % operator
print('The value of pi is: %5.4f' %(3.141592))
print('Floating point numbers: %1.0f' %(13.144))
Output:
The value of pi is: 3.1416
Floating point numbers: 13
2. Formatting string using format() method
Format() method was introduced with Python3 for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders defined
by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into
the placeholders and concatenate with the string passed as parameters into the format function.
Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)
Example: Formatting string using format() method
print('We all are {}.'.format('equal'))
Output:
We all are equal.
The.format() method has many advantages over the placeholder method:
• We can insert object by using index-based position:
Example
print('{2} {1} {0}'.format('directions','the', 'Read'))
Output:
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
• We can reuse the inserted objects to avoid duplication:
print('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))
Output:
The first second was alright, but the second second was tough.
Float precision with the .format() method:
Syntax: {[index]:[width][.precision][type]}
The type can be used with format codes:
• ‘d’ for integers
• ‘f’ for floating-point numbers
• ‘b’ for binary numbers
• ‘o’ for octal numbers
• ‘x’ for octal hexadecimal numbers
• ‘s’ for string
• ‘e’ for floating-point in an exponent format
Example:
print('The value of pi is: %1.5f' %3.141592)
# vs.
print('The value of pi is: {0:1.5f}'.format(3.141592))
Output:
The value of pi is: 3.14159
The value of pi is: 3.14159
3. Formatted String using F-strings
PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or
more commonly as F-strings (because of the leading f character preceding the string literal). The
idea behind f-strings is to make string interpolation simpler.
To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much
the same way that you would with str.format(). F-strings provide a concise and convenient way to
embed python expressions inside string literals for formatting.
Example: Formatting string with F-Strings
name = 'Ele'
print(f"My name is {name}.")
Output: My name is Ele.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Example: Lambda Expressions using F-strings
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
print(my_string)
Output:
The only way to
learn to program is
by writing code.
Example 3: Using \
my_string = "The only way to \n" \
"learn to program is \n" \
"by writing code."
print(my_string)
Output:
The only way to
learn to program is
by writing code.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-15 Python Programming
String Slicing
Python provides us with a method slice() that creates a ‘slice’ object that contains a set of
‘start’ & ‘stop’ indices and step values. To be specific about the parameters, it is (start, stop,
step).
Slice has two different implementations, i.e. slice have two overload methods, each taking two
different sets of parameters:
Both slice() implementations return an object of the format slice(start, stop, end).
This returned object can now be used to slice string, list, tuple, set, bytes, or range
objects.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
s2-obj: slice(2, 8, None)
s2-res: lcome
s3-obj: slice(1, 20, 2)
s3-res: ecm oGRIsi
Explanation:
Slice() has two implementations, one with a single parameter and another with three
parameters. Implementation with one parameter takes ‘stop’ index as the only and mandatory
parameter whereas Implementation with three parameters takes ‘start’ index, ‘stop’ index, and
OPTIONAL ‘step’ value as well.
In the above example ( check s1, s2 & s3 in the code snippet & output):
• In s1: We first used slice() that takes only one ‘stop’ parameter. In the output, we
received substring as “Welcom” as the ‘start’ index was automatically set to ‘0’ and
‘stop’ was set as 6.
• In s2: After that, we used slice() with a three parameter-method but chose not to
provide an optional ‘step’ parameter. In the output, we received a substring from index
‘2’ until ‘7’, as we provided ‘start’ as ‘2’ & ‘stop’ as ‘8’.
• In s3: We implement slice() with ‘step’ as well. As we provided ‘step’ as 2. In the
output, we received a substring by advancing to every 2nd element starting from index
1 to 20
Hence, now it’s clear that ‘step’ value determines with what value will your iterator (while
forming the substring) advance or increment.
Indexing Syntax
Indexing syntax of a slice is a shorthand or a better substitute of slice() as it’s easier to
understand and execute. It’s one of those operations and syntax that you appreciate as a
developer and subconsciously lookout to apply in your code as it really is a cool operation!
Indexing Syntax:
String [start : stop : step]
So here, instead of creating a slice object first and then implementing it on the string, we
directly use the indexing syntax that performs the same operation.
Example:
s = "Welcome to GMR Institute of Technology"
print("s1", s[:6])
print("s2", s[2 : 7]) # using indexing syntax for slice(start, end, step) without step
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
print("s3", s[1 : 20 : 2]) # using indexing syntax for slice(start, end, step)
Output:
s1 Welcom
s2 lcome
s3 ecm oGRIsi
Note:
• ‘Step’ can never be zero.
• String[ : : ] => start = 0, stop = length of string, step = 1.
• String[2 : : ] => start = 2, stop = length of string, step = 1
• String[ :2: ] => start = 0, stop = 2, step = 1
• String[:6] OR String[1:6] => are valid syntaxes as ‘step’ is an optional parameter for
this operation.
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
# reversing complete string
s1 = s[::-1]
print("s1:", s1)
# reversing complete string by stepping to every 2nd element
s2 = s[::-2]
print("s2:", s2)
# reversing from 10th index until start, 'stop' index here automatically will be till starting of the
string
s3 = s[10::-1]
print("s3:", s3)
# reversing from end until 10th index, 'start' index will automatically be the first element
s4 = s[:10:-1]
print("s4:", s4)
# reversing from 16th index till 10th index
s5 = s[16:10:-1]
print("s5:", s5)
# this will return empty, as we're not reversing here. But NOTE that this 'start' cannot be
greater than ‘stop’ until & unless we're reversing
s6 = s[11:2]
print("s6:", s6)
# reversing from 14th index from the end until 4th index from the end.
s7 = s[-4:-14:-1]
print("s7:", s7)
Output:
s1: ygolonhceT fo etutitsnI RMG ot emocleW
s2: yoohe oeuisIRGo mce
s3: ot emocleW
s4: ygolonhceT fo etutitsnI RMG
s5: nI RMG
s6:
s7: lonhceT fo
Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-16 Python Programming
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Program converting list to tuple: we can convert a list to tuple using tuple() function?
Program: tup.py
list = [1, 2, 3]
tpl = tuple(list)
print(tpl)
output: python tup.py
INTRODUCTION TO DICTIONARIES:
A Dictionary represents a group of elements arranged in the form of key-value pairs. In
dictionary, the first element is considered as ‘key’ and immediate next element is taken as its
‘value’. The key and its value are separated by colon (: ).
All the key-value pairs in a dictionary are inserted in curly braces {}.
It is the mutable data-structure. The dictionary is defined into element Keys and values.
<key> : <value>,
<key> : <value>
In the above dictionary dict, the keys name and age are the string that is an immutable object.
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Example:
Python provides the built-in function dict() method which is also used to create dictionary. The
empty curly braces {} is used to create empty dictionary.
Accessing the Dictionary values: To access the elements of a dictionary we should not use
indexing or slicing. The values in dictionary can be accessed by using keys and keys are unique
in the dictionary.
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
To access the value associated with the key, we need to mention key name inside the square
braces.
Example:
Changing and Adding Dictionary elements: dictionaries are mutable we can change or add
new items using an assignment operator.
If the key is already present, then the existing value will be updated. In case the key is not
7present, a new (key: value) pair is added to the dictionary.
Example:
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Example:
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-17 Python Programming
Dictionary Methods
Dictionary Methods: Various methods are provided to process the elements of a dictionary.
These methods generally retrieve or manipulate the contents of a dictionary.
Method Description
fromkeys(seq[, Returns a new dictionary with keys from seq and value
v]) equal to v (defaults to None).
Returns the value of the key. If the key does not exist,
get(key[,d])
returns d (defaults to None).
Removes the item with the key and returns its value or ‘d’
pop(key[,d]) if key is not found. If d is not provided and the key is not
found, it raises KeyError.
4. get(): The get method return the value of the item with the specific key.
Syntax: dictionary.get(keyname,value)
Example:
6. keys(): the keys() method returns a view object. The view object contains the keys of
the dictionary, as a list. The view object will reflect any changes done to the
dictionary.
Syntax: dictionary.keys()
Example:
7. pop(): The pop() method removes the specific items from the dictionary. The value
of the removed item is the return value of the pop() method.
Syntax: dictionary.pop(keyname, defaultvalue)
Example:
9. setdefault(): The setdefault() method returns the value of the item with the specific
key. If the key does not exist, insert the key, with the specific value.
Syntax: dictionary.setdefault(keyname, value)
Example:
10. update(): The update() method inserts the specified items to the dictionary. The
specified item can be a dictionary, or an iterable object with the key value pairs.
Syntax: dictionary.update(iterable)
Example:
Program: num.py
Input a number 15
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14:
196, 15: 225}
Example 2:
#using set() function
i={1,2,3,4,5}
s=set(i)
print(s)
k=set(range(6))
print(k)
output:
{1,2 3 4,5}
{0,1,2,3,4,5}
Example 3: creating set by using list
#using list
#there are some duplicates in it
s=set(['c','c++','java','c',1,2,5,2,7,5,1,2])
Elements of set:
morning hello Hi True
Example 1:
# Deletion of elements in a Set
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)
output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Set Operations:
Sets can be used to carry out mathematical set operations like union, intersection, difference
and symmetric difference. We can do this with operators or methods.
1. Set Union
2. Set Intersection
3. Set Difference
4. Set Symmetric Difference
1. Set Union: Union of A and B is a set of all elements from both sets. Union is performed
using ‘|’ operator. Same can be accomplished using the union() method.
2. Set Intersection: intersection of A and B is a set of elements that are common in both
the sets. Intersection is performed using ‘&’ operator. Some can be accomplished using
the intersection() method.
Tuple:
• Tuple is exactly same as list except that it is immutable. i.e once tuple object is created,
then any specific changes in that object couldn’t be done. Hence Tuple is read only
version of List.
• If our data is static, then Tuple is used.
• Heterogeneous objects are allowed.
• We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in tuple also.
• Tuple support both +ve and -ve index. +ve index means forward direction (from left to
right) and -ve index means backward direction (from right to left).
• We can represent Tuple elements within Parenthesis and with comma separator
Example:
t=10,20,30,40
print(t)
print(type(t))
Output:
(10,20,30,40)
<class ‘tuple’>
Tuple creation:
t=()
Creation of empty tuple
t=(10,)
t=10, creation of single valued tuple ,parenthesis are optional, should ends with comma
t=10,20,30
t=(10,20,30) creation of multi values tuples & parenthesis are optional
By using tuple() function:
list=[10,20,30]
t=tuple(list)
print(t)
The [:] operator returns the items in the range specified by two index operands separated by
the: symbol.
If the first operand is omitted, the range starts from zero. If the second operand is omitted, the
range goes up to the end of the tuple.
>>>t1=(1,2,3,4,5,6)
>>>t1[1:3]
(2, 3)
>>>t1[3:]
(4, 5, 6)
>>>t1[:3]
(1, 2, 3)
in:
The not in operator returns true if an item does not exist in the given tuple.
>>> t1=(1,2,3,4,5,6)
>>> 4 not in t1
False
>>> 10 not in t1
True
Functions of Tuple:
1. len()
3. index()
Returns index of first occurrence of the given element. If the specified element is not
available then we will get Value Error.
Eg: t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) Value Error: tuple .index(x): x not in tuple
4. sorted()
To sort elements based on default natural sorting order
t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)
Output:
[10, 20, 30, 40]
(40, 10, 30, 20)
6. cmp():
Notes Prepared by : L.Swathi, Assistant Professor, Dept of IT, GMRIT
It compares the elements of both tuples. If both tuples are equal then returns 0 If the first
tuple is less than second tuple then it returns -1 If the first tuple is greater than second
tuple then it returns +1
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2)) # -1
print(cmp(t1,t3)) # 0 6.
print(cmp(t2,t3)) # +1
Note: cmp() function is available only in Python2 but not in Python 3.
Tuple unpacking is the reverse process of tuple packing. We can unpack a tuple and assign its
values to different variables
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
Output: a= 10 b= 20 c= 30 d= 40
***
eval is a built-in- function used in python, eval function parses the expression argument and
evaluates it as a python expression. In simple words, the eval function evaluates the “String” like
a python expression and returns the result as an integer.
Arguments or Parameters
The arguments or parameters of eval function are strings, also optionally global and locals can be
used as an argument inside eval function, but the globals must be represented as a dictionary and
the locals as a mapped object.
Return Value
The return value would be the result of the evaluated expression. Often the return type would be
an integer.
Use Case-1:
An integer is entered as 10+ 10 where expecting a result of 20 (10 + 10) but the input method
returned a string of the same input entered.
Use Case-2:
In the case of eval, it returned the evaluated expression 20 in the form of an integer given the
string as input. 10 + 10 is an expression that returns 20 as a result.
Use Case-3:
x = 10
print(type(x))
--------------------------------------------------------------------
<class 'int'>
expression = eval(evaluate)
print(expression)
print(type(expression))
--------------------------------------------------------------------
485
<class 'int'>
1.abs(x)- The abs() method returns the absolute value of the given number and returns a
magnitude of a complex number.
Syntax: abs (num)
2.all(iterable)- The all() method checks whether all the elements in an iterable are truthy values
or not. It returns true if all elements in the given iterable are nonzero or True. Else, it returns
False.
Syntax: all (iterable)
3.any(iterable)- The any() method returns True if at least one element in the given iterable is the
truthy value or boolean True. It returns False for empty or falsy value (such as 0, False, none).
Syntax: any(iterable)
5.bin(x)- The bin() method converts an integer number to a binary string prefixed with 0b.
Syntax: bin(num)
Parameters: An integer.
6.bytearray()- The bytearray() method returns a bytearray object, which is an array of the given
bytes. The bytearray class is a mutable sequence of integers in the range of 0 to 256.
Syntax: bytearray(source, encoding, errors)
7.Chr()-The chr() method returns the string representing a character whose Unicode code
point is the integer.
Syntax: chr(integer)
8.len()-This function returns the length of the object. It returns total elements in an iterable or
the number of chars in a string.
Syntax: len(object)
print("Total Elements in list: ", len([1,2,3,4,5])) # 5
print("Total Elements in tuple: ",len((1,2,3,4,5))) #5
9.max()-This method returns the largest value from the specified iterable or multiple
arguments.
Syntax: max(iterable, key, default)
print(repr(10)) #'10'
print(repr(10.5)) #'10.5'
Example:
print(round(1)) #1
print(round(1.4)) #1
print(round(1.5)) #2
print(round(1.6)) #2
13.split()-The split() function breaks a string based on set criteria. You can use it to split a string
value from a web form. Or you can even use it to count the number of words in a piece of text.
Example:
class ty:
def __init__(self, number, name):
self.number = number
self.name = name
a = ty(5*8, "Idowu")
b = getattr(a, 'name')
print(b)
Output: Idowu
15.strip()- Python's strip() removes leading characters from a string. It repeatedly removes the
first character from the string, if it matches any of the supplied characters.
Example:
Students can explore More Methods based upon the Need in their Program.
***
Filter
filter()
The filter() function extracts elements from an iterable (list, tuple etc.) for which a function
returns True.
Syntax:
filter(function, iterable)
Arguments:
The filter() function takes two arguments:
function - a function to be run for each item in the iterable
iterable - an iterable like sets, lists, tuples etc.
Return Value:
The filter() function returns an iterator.
Note: You can easily convert iterators to sequences like lists, tuples, strings etc.
Example 1:
This simple example returns values higher than 5 using filter function.
def filterdata(x):
if x>5:
return x
result = filter(filterdata,(1,2,6))
print(list(result))
Output: [6]
Example 2:
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# a function that returns True if letter is vowel
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
return True if letter in vowels else False
Here, the filter() function extracts only the vowel letters from the letters list. Each element of
the letters list is passed to the filter_vowels() function. If filter_vowels() returns True, that
element is extracted otherwise it's filtered out.
Output: [2,4,6]
Here, we have directly passed a lambda function inside filter(). lambda function returns True for
even numbers. Hence, the filter() function returns an iterator containing even numbers only.
Reduce
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer to
write simpler, shorter code, without necessarily needing to bother about intricacies like loops and
branching.
Essentially, these three functions allows to apply a function across a number of iterables, in one fell
swoop. Map and filter come built-in with Python and require no importing. Reduce, however, needs
to be imported as it resides in the functools module.
Reduce():
reduce() isn't a built-in function anymore, and it can be found in the functools module. The reduce()
function applies a provided function to ‘iterables’ and returns a single value, as the name implies.
reduce() works differently than map() and filter().It does not return a new list based on
the function and iterable we've passed. Instead, it returns a single value.
Where func is the function on which each element in the iterable gets cumulatively applied to,
and initial is the optional value that gets placed before the elements of the iterable in the calculation,
and serves as a default when the iterable is empty.
Notes Prepared by: P.Pooja , Assistant Professor, Dept of IT, GMRIT
Note: func requires two arguments, the first of which is the first element in iterable (if initial is not
supplied) and the second element in iterable. If initial is supplied, then it becomes the first argument
to func and the first element in iterable becomes the second element.
reduce() is a bit harder to understand than map() and filter(), so let's look at a step by step example:
• We start with a list [2, 4, 7, 3] and pass the add(x, y) function to reduce() alongside this
list, without an initial value
• reduce() calls add(2, 4), and add() returns 6
• reduce() calls add(6, 7) (result of the previous call to add() and the next element in the
list as parameters), and add() returns 13
• reduce() calls add(13, 3), and add() returns 16
• Since no more elements are left in the sequence, reduce() returns 16
The only difference, if we had given an initial value would have been an additional step,
where reduce() would call add(initial, 2) and use that return value in step 2.
Example 1:
Output: 16
Functions with no name are known as lambda functions. These functions are frequently used as
input to other functions. Let’s try to integrate Lambda functions into the reduce() function.
Output: 187
***
Map
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer to
write simpler, shorter code, without necessarily needing to bother about intricacies like loops and
branching.
Essentially, these three functions allows to apply a function across a number of iterables, in one fell
swoop. Map and filter come built-in with Python and require no importing. Reduce, however, needs
to be imported as it resides in the functools module.
Map():
The map() function is a higher-order function. This function accepts another function and a
sequence of ‘iterables’ as parameters and provides output after applying the function to each iterable
in the sequence.
The map() function iterates through all items in the given iterable and executes the function we
passed as an argument on each of them.
Syntax:
map (func, * iterable(s))
Where func is the function on which each element in iterables would be applied on. Notice the
asterisk (*) on iterables? It means there can be as many iterables as possible, in so far func has that
exact number as required input arguments.
Example:
def starts_with_A(s) :
Return s[0] == “A”
Fruit = [“Apple”, “Banana”, “Orange”, “Mango”, “Grape”]
Map_object = map(starts_with_A, Fruit)
Print(list(map_object))
Example 2:
def function(a):
return a*a
x = map(function, (1,2,3,4)) #x is the map object
Output: {16, 1, 4, 9}
Example 3:
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map(str.upper, my_pets))
print(uppered_pets)
Functions with no name are known as lambda functions. These functions are frequently used as
input to other functions. Let’s try to integrate Lambda functions into the map() function.
Example: tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)
***
Function: A function is a block of code which only runs when it is called. A function can acc
ept parameters as input and returns the output.
Defining a function:
def my_function():
print("Hello ! This is J Section")
Calling a Function:
def my_function():
print("Hello ! This is J Section ")
my_function()
Information can be passed into functions as arguments. Arguments are specified after the fun
ction name, inside the parentheses. N Number of arguments are taken separated with a semi-
colon.
• Default arguments
• Required arguments
• Keyword arguments
• Variable number of arguments
Example:
def my_function(Input):
print(Input + " Says Hello")
my_function("Prasad")
Output:
Note: Function can take N parameters, but when a function is given with N parameters, all th
e N should definitely considered.
my_function("Prasad", "Vadamodula")
Multiple arguments can be added using add a * before the parameter name in the function de
finition.
This way the function will receive a tuple of arguments, and can access the items accordingly
:
Example:
def my_function(*JSection):
print("The youngest child is " + JSection[3])
Keyword Arguments
Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Many keyword arguments that will be passed into the function, add two asterisk: ** before th
e parameter name in the function definition.
def my_function(**JSection):
print("His last name is " + JSection["lname"])
The following example shows how to use a default parameter value. One keyword with One
Value.
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Assign and 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.
Example:
def my_function(food):
for x in food:
print(x)
my_function(fruits)
apple
banana
cherry
Return Values
Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
15
25
45
Function definitions cannot be empty, but if for some reason;wanted a function definition wit
h no content, put in the pass statement to avoid getting an error.
Example:
def myfunction():
pass
Note:
# having an empty function definition like this, would raise an error without the pass stateme
nt
Recursion
Python also accepts function recursion, which means a defined function can call itself. It mea
ns that a function calls itself.
Example:
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
Output:
Explanation:
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). W
e use the k variable as the data, which decrements (-1) every time we recurse. The recursion e
nds when the condition is not greater than 0 (i.e. when it is 0).
***
Power of lambda is better shown when you use them as an anonymous function inside a
nother function.
def myfunc(n):
return lambda a : a * n
Use the same function definition to make a function that always triples the number
Example:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Output: 33
Use the same function definition to make both functions, in the same program
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output:
22
33
The location where a variable is found and also cab be accessed it if required is called the sc
ope of a variable.
Global variables are the ones that are defined and declared outside any function and are not s
pecified to any function. They can be used by any part of the program.
Example:
# This function uses global variable s
def f():
print(s)
# Global scope
s = "I love GMRIT"
f()
Output: I love GMRIT
Example 2:
# This function has a variable with
# name same as s.
def f():
s = "Me too."
print(s)
# Global scope
s = "I love GMRIT"
f()
print(s)
Output:
Me too.
I love GMRIT
# Global Scope
s = "Python is great !"
f()
print(s)
Output:
Python is great!
Look for J Section Python
Look for J Section Python
Example 4:
# Python program to demonstrate
# scope of variable
a=1
# Uses global because there is no local 'a'
def f():
print('Inside f() : ', a)
# Variable 'a' is redefined as a local
def g():
a=2
print('Inside g() : ', a)
# Uses global keyword to modify global 'a'
def h():
global a
a=3
Output:
global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3
Nonlocal keyword
In Python, nonlocal keyword is used in the case of nested functions. This keyword works sim
ilar to the global, but rather than global, this keyword declares a variable to point to the varia
ble of outside enclosing function, in case of nested functions.
outer()
Output:
Value of a using nonlocal is : 10
Value of a without using nonlocal is : 5
***
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Example:
• Save this code in a file named modules.py
def greeting(name):
print("Hello, " + name)
• Import the module named modules, and call the greeting function:
import modules
modules.greeting(“Python”)
Output:
Hello, Python
Variables in Module
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):
Example
Save this code in the file modules.py
person1 = {
"name": "John",
"age": 16,
"country": "India"
}
Import the module named modules, and access the person1 dictionary:
import modules
a = modules.person1["age"]
print(a)
Output:
16
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Example
Create an alias for modules called mx:
import modules as mx
a = mx.person1["age"]
print(a)
Output:
36
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:
import platform
x = platform.system()
print(x)
Output:
Windows
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
'_pypy_sys_version_parser', '_release_filename', '_release_version', '_supported_dists',
'_sys_version', '_sys_version_cache', '_sys_version_parser', '_syscmd_file', '_syscmd_uname',
'_syscmd_ver', '_uname_cache', '_ver_output', '_ver_stages', 'architecture', 'collections', 'dist',
'java_ver', 'libc_ver', 'linux_distribution', 'mac_ver', 'machine', 'node', 'os', 'platform', 'popen',
'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation',
'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'subprocess', 'sys',
'system', 'system_alias', 'uname', 'uname_result', 'version', 'warnings', 'win32_ver']
***
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-27 Python Programming
Import statements from import modules
Python's from statement gives import specific attributes from a module into the current
namespace.
The from...import has the following syntax
from modname import name1[, name2[, ... nameN]]
For example, to import the function fib from the module fibonacc, use the following
statement:
from fibonacc import fib
This statement does not import the entire module fib into the current namespace; it just
introduces the item fib from the module fibonacc into the global symbol table of the
importing module.
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement
from module_name import *
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Example:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
return result
Save the above code as “fibonacc.py”.
Now enter the Python interpreter and import this module with the following command:
import fibonacc
This does not enter the names of the functions defined in fibonacc directly in the current
symbol table; it only enters the module name fibonacc there. Using the module name you can
access the functions:
fibonacc.fib(1000)
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
fibonacc.fib2(100)
Output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
fibonacc.__name__
Output:
' fibonacc '
If you intend to use a function often you can assign it to a local name:
fib = fibonacc.fib
fib(500)
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377
There is even a variant to import all names that a module defines:
from fibonacc import *
fib(500)
fib2(200)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
***
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-27 Python Programming
Math Modules
Python has a built-in module that can be used for mathematical tasks.
The math module has a set of methods and constants.
Math Methods:
Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
math.copysign() Returns a float consisting of the value of the first parameter and the sign of the
second parameter
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
math.dist() Returns the Euclidean distance between two points (p and q), where p and q are
the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns Ex - 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x
and i
math.lgamma() Returns the log gamma value of x
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
math.perm() Returns the number of ways to choose k items from n items with order and
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
math.remainder() Returns the closest value that can make numerator completely divisible by the
denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number
Math Constants
Constant Description
math.e Returns Euler's number (2.7182...)
math.inf Returns a floating-point positive infinity
math.nan Returns a floating-point NaN (Not a Number) value
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)
math.acos() Method
The math.acos() method returns the arc cosine value of a number.
Note: The parameter passed in math.acos() must lie between -1 to 1.
Tip: math.acos(-1) will return the value of PI.
Syntax:
math.acos(x)
Example:
# Import math Library
import math
# Return the arc cosine of numbers
print(math.acos(0.55))
print(math.acos(-0.55))
print(math.acos(0))
print(math.acos(1))
print(math.acos(-1))
Output:
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
0.9884320889261531
2.15316056466364
1.5707963267948966
0.0
3.141592653589793
math.ceil() Method
The math.ceil() method rounds a number UP to the nearest integer, if necessary, and returns
the result.
Tip: To round a number DOWN to the nearest integer, look at the math.floor() method.
Syntax:
math.ceil(x)
Example:
# Import math library
import math
# Round a number upward to its nearest integer
print(math.ceil(1.4))
print(math.ceil(5.3))
print(math.ceil(-5.3))
print(math.ceil(22.6))
print(math.ceil(10.0))
Output:
2
6
-5
23
10
math.fabs() Method
The math.fabs() method returns the absolute value of a number, as a float.
Absolute denotes a non-negative number. This removes the negative sign of the value if it has
any.
Unlike Python abs(), this method always converts the value to a float value.
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Syntax:
math.fabs(x)
Example:
#Import math Library
import math
#Print absolute values from numbers
print(math.fabs(-66.43))
print(math.fabs(-7))
Output:
66.43
7.0
math.factorial() Method
The math.factorial() method returns the factorial of a number.
Note: This method only accepts positive integers.
The factorial of a number is the sum of the multiplication, of all the whole numbers, from our
specified number down to 1. For example, the factorial of 6 would be 6 x 5 x 4 x 3 x 2 x 1 =
720
Syntax:
math.factorial(x)
Example:
#Import math Library
import math
#Return factorial of a number
print(math.factorial(9))
print(math.factorial(6))
print(math.factorial(12))
Output:
362880
720
479001600
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
math.floor() Method
The math.floor() method rounds a number DOWN to the nearest integer, if necessary, and
returns the result.
Tip: To round a number UP to the nearest integer, look at the math.ceil() method.
Syntax:
math.floor(x)
Example:
# Import math library
import math
# Round numbers down to the nearest integer
print(math.floor(0.6))
print(math.floor(1.4))
print(math.floor(5.3))
print(math.floor(-5.3))
print(math.floor(22.6))
print(math.floor(10.0))
Output:
0
1
5
-6
22
10
math.gcd() Method
The math.gcd() method returns the greatest common divisor of the two integers int1 and int2.
GCD is the largest common divisor that divides the numbers without a remainder.
GCD is also known as the highest common factor (HCF).
Tip: gcd(0,0) returns 0.
Syntax:
math.gcd(int1, int2)
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Example:
#Import math Library
import math
#find the the greatest common divisor of the two integers
print (math.gcd(3, 6))
print (math.gcd(6, 12))
print (math.gcd(12, 36))
print (math.gcd(-12, -36))
print (math.gcd(5, 12))
print (math.gcd(10, 0))
print (math.gcd(0, 34))
print (math.gcd(0, 0))
Output:
3
6
12
12
1
10
34
0
math.pow() Method
The math.pow() method returns the value of x raised to power y.
If x is negative and y is not an integer, it returns a ValueError.
This method converts both arguments into a float.
Tip: If we use math.pow(1.0,x) or math.pow(x,0.0), it will always returns 1.0.
Syntax:
math.pow(x, y)
Example:
# Import math Library
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
import math
#Return the value of 9 raised to the power of 3
print(math.pow(9, 3))
Output:
729.0
math.sqrt() Method
The math.sqrt() method returns the square root of a number.
Note: The number must be greater than or equal to 0.
Syntax:
math.sqrt(x)
Example:
# Import math Library
import math
# Return the square root of different numbers
print (math.sqrt(9))
print (math.sqrt(25))
print (math.sqrt(16))
Output:
3.0
5.0
4.0
math.pi Constant
The math.pi constant returns the value of PI: 3.141592653589793.
Note: Mathematically PI is represented by π.
Example:
# Import math Library
import math
# Print the value of pi
print (math.pi)
Output:
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
3.141592653589793
***
Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture notes-29 Python Programming
Itertools
Itertools is one of the most useful modules in Python. Python Itertools is a module that
provides various functions that work on iterators to produce complex iterators. Its functions
make it a breeze to work with lists and arrays.
Python Itertools is a library in Python generally consisting of multiple methods. These are
used in various iterators to compute a fast and code efficient solution in the runtime.
itertools. product() is a part of a python module itertools; a collection of tools used to handle
iterators. Together all these tools form iterator algebra.
Infinite itertools
Python iterators like lists, tuples, and dictionaries are exhaustive. But it is not necessary for
an iterator to exhaust at some point, they can go on forever. Infinite iterators can run a loop
infinitely. These functions more often run using a for loop. There are three infinite iterators:
1) count(start, step): count() may take two values- start and step. This iterator starts
returning values from ‘start’ and goes on infinitely, if steps are provided then those
values are skipped. If you are not given start value by default, it returns a from 0.
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Ex1: for i in itertools.count(2,2):
if i == 10:
break
else:
print(i, end=" ")
Output:
2 4 6 8
3) cycle(input): The cycle() function iterates through the input and prints individual
items in a given order. When it reaches the end of its input, cycle restarts from the
beginning.
Syntax: itertools.cycle(input)
Ex1:
c=0
var = "12345"
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
for i in itertools.cycle(var):
if c == 12:
break
else:
c=c+1
print(i, end=" ")
Output: 1 2 3 4 5 1 2 3 4 5 1 2
***
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Lecture notes-30 Python Programming
Itertools
Combinatoric itertools
The combinatoric iterators provide functions to perform permutations, combinations, and
cartesian products. In Python there are 3 combinatoric iterators:
1) product (input): product() returns the cartesian product of the input iterables. This is
equivalent to a nested for-loop. To compute the product of an iterable with itself, we
use the optional repeat keyword argument to specify the number of repetitions.
Syntax: Itertools.product(input)
Output: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
2) permutations(input, size): This function returns a tuple of all the permutations of the
given iterable. permutations() returns size permutations of elements in the input. It
accepts two parameters: the iterable and group size. If the group size is not specified,
it will form groups of the same length as the iterable itself.
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
Syntax:itertools.combinations_with_replacement(iterable, r)
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Terminating iterators on the shortest input sequence :
These iterators are used to work on finite sequences and produce an output based on the
function used.
1) chain(*iterables): chain() makes an iterator from elements of the first iterable, then
from the second, and so on.
Syntax: itertools.chain(*iterables)
2) compress(data, selectors): This makes an iterator that filters elements, from data, for
which selector values amount to True.
Syntax: Itertools.groupby(iterable,key=None)
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Ex1: from itertools import groupby
for i,j in groupby('AAAAABBCCCCCDDDCCCBBA') :
print(list(j))
Output: [‘A’, ‘A’, ‘A’, ‘A’, ‘A’]
[‘B’, ‘B’]
[‘C’, ‘C’, ‘C’, ‘C’, ‘C’]
[‘D’, ‘D’, ‘D’]
[‘C’, ‘C’, ‘C’]
[‘B’, ‘B’]
[‘A’]
***
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Lecture Notes-31 Python Programming
File
A file is a container that stores data. As files are non-volatile in nature, the data will be stored
permanently in a secondary device like Hard Disk and using python we will handle these files
in our applications.
Binary files: Most of the files that we see in our computer system are called binary files.
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.
Text files: Text files don’t have any specific encoding and it can be opened in normal text
editor itself.
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Syntax: file_object = open(file_name, mode)
Here, file_name is the name of the file or the location of the file that you want to open, and
file_name should have the file extension included as well. Which means in mydocument.txt –
the term mydocument is the name of the file and .txt is the extension of the file. The mode in
the open function syntax will tell Python as what operation you want to do on a file. The
following example gives an idea about creating a file at a specified path
Ex: f = open("f:\mydocument.txt","w")
f.write("python programming")
f.close()
Access modes:
• ‘r’ – Read Mode: Read mode is used only to read data from the file.
• ‘w’ – Write Mode: This mode is used when you want to write data into the file or
modify it. Remember write mode overwrites the data present in the file.
• ‘a’ – Append Mode: Append mode is used to append data to the file. Remember
data will be appended at the end of the file pointer.
• ‘r+’ – Read or Write Mode: This mode is used when we want to write or read the
data from the same file.
• ‘a+’ – Append or Read Mode: This mode is used when we want to read data from
the file or append the data into the same file.
The above-mentioned modes are for opening, reading or writing text files only.
While using binary files, we have to use the same modes with the letter ‘b’ at the end. So that
Python can understand that we are interacting with binary files.
• ‘wb’ – Open a file for write only mode in the binary format.
• ‘rb’ – Open a file for the read-only mode in the binary format.
• ‘ab’ – Open a file for appending only mode in the binary format.
• ‘rb+’ – Open a file for read and write only mode in the binary format.
• ‘ab+’ – Open a file for appending and read-only mode in the binary format.
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Example 1:
fo = open(“C:/Documents/Python/test.txt”, “r+”)
In the above example, we are opening the file named ‘test.txt’ present at the location
‘C:/Documents/Python/’ and we are opening the same file in a read-write mode which gives us
more flexibility.
Reading a File:
In order to read a file in python, we must open the file in read mode. There are three ways
in which we can read the files in python.
• read()
• read(n)
• readline()
• readlines()
Here, n is the number of bytes to be read.
let’s create a sample text file as shown below.
Ex:
f = open("f:\mydocument.txt","w")
f.write("python programming \n" \
"c programming \n" \
"object oriented programming")
f.close()
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
2. read(n)
f = open("f:\mydocument.txt","r")
print(f.read(4))
output: pyth
3. readline()
f = open("f:\mydocument.txt","r")
print(f.readline())
4. readlines()
f = open("f:\mydocument.txt","r")
print(f.readlines())
output:
['python programming \t \n', 'c programming \n', 'object oriented programming']
Writing to a File:
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content present
inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
• write(string)
• writelines(list)
1. write(string):
f = open("f:\mydocument.txt","w")
f.write("python programming")
f.close()
2. writelines(list):
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Closing a File:
After completing our operations on the file, it is highly recommended to close the file. For this
we have to use close() function.
Syntax: f.close()
***
Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Lecture Notes-32 Python Programming
Searching:
• Searching is a technique that helps in finding the position of a given element or value
in a list.
• If we find the element which we are searching, then we will say searching is
successful but we don’t found the element then we will say searching is not
successful.
• Searching is most prevalent task that we do in our daily life. Like searching contacts
list in mobile, student list in register.
Linear Search: This is the simplest searching technique. It sequentially checks each element
of the list for the target searching value until a match is found or until all the elements have
been searched. This searching technique can be performed on both type of list, either the list
is sorted or unsorted.
• It is also known as sequential search.
• In this search technique, we start at the beginning of the list and search for the
searching element by examining each subsequent element until the searching element
is found or the list is exhausted.
• It is one of the simplest searching technique.
• This technique can be applied to both sorted and unsorted list.
Program:
#defining function for linear search
def linear_search(mylist,item):
for i in range(len(mylist)):
if mylist[i]==item:
return i
return -1
#creating empty list and adding elements
mylist=[]
n=int(input('enter number of elements in list'))
for i in range(n):
mylist.append(int(input()))
print("list created is %s"%(mylist))
#result
result = linear_search(mylist,x)
if result==-1:
print("Element not found in the list")
else:
print(f"Element {x} is found at position {result}")
Output 1:
enter number of elements in list6
12
35
62
2
Output 2:
enter number of elements in list5
15
56
26
33
25
list created is [15, 56, 26, 33, 25]
Element in List : [15, 56, 26, 33, 25]
enter searching element :5
Element not found in the list
• If the list has large numbers of data then it is insufficient for searching data.
• It takes more time for searching data.
• If there are 200 elements in the list and you want to search element at the position 199
then you have to search the entire list, that’s consume time.
Binary Search:
• Binary Search is a searching algorithm for finding an element's position in a sorted
array. Binary search algorithms are fast and effective in comparison to linear search
algorithms. The most important thing to note about binary search is that it works only
on sorted lists of elements.
• If the list is not sorted, then the algorithm first sorts the elements using the sorting
algorithm and then runs the binary search function to find the desired output.
• There are two methods by which we can run the binary search algorithm. They are:
1. Iterative method
2. Recursive method
• The steps of the process are general for both the methods; the difference is only found
in the function calling.
Iterative method: A set of statements is repeated multiple times to find an element's index
position in the iterative method. The while loop is used for accomplish this task.
Recursive method: The divide and conquer approach technique is followed by the recursive
method. In this method, a function is called itself again and again until it found an element in
the list.
Example: Searching element using Binary Search
Explanation:
1. In this example we take an sorted list which have 10 elements.
2. 23 is our target element.
3. Set two pointers low and high at the lowest and the highest positions respectively
4. Iteration 1: elements = 2, 5, 8, 12, 16, 23, 38, 56, 72, 91
• Select the middle element. (here 16)
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
• Since 23 is greater than 16, so we divide the array into two halves and
consider the sub-array after element 16.
• Now this subarray with the elements after 16 will be taken into next iteration.
5. Iteration 2: elements= 23,38,56,72,91
• Select the middle element. (now 56)
• Since 23 is smaller than 56, so we divide the array into two halves and
consider the sub-array before element 56.
• Now this subarray with the elements before 56 will be taken into next
iteration.
6. Iteration 3: elements=23,38
7. Select the middle element. (now 23)
8. Since 23 is the middle element. So the iterations will now stop.
9. The above process is depicted in this figure very clearly.
Program: Iterative method
#Function declaration
def binarySearch(lst, x, low, high):
# Repeat until the pointers low and high meet each other
while low <= high:
mid = low + (high - low)//2
if lst[mid] == x:
return mid
elif lst[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Output 1:
enter total element count in list:6
12
45
89
63
79
44
created list is [12, 45, 89, 63, 79, 44]
enter element to search:89
Element is present at index 2
Output 2:
enter total element count in list:5
14
56
2
35
89
created list is [14, 56, 2, 35, 89]
enter element to search:1
Element not found
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
#input element to search
x = int(input('enter element to search:'))
result = binarySearch(lst, x, 0, len(lst)-1)
if result != -1:
print("Element is present at index ",result)
else:
print("Element Not found")
Output 1:
enter total element count in list:6
12
13
6
41
52
63
created list is [12, 13, 6, 41, 52, 63]
enter element to search:41
Element is present at index 3
Output 2:
enter total element count in list:5
12
13
14
15
16
created list is [12, 13, 14, 15, 16]
enter element to search:17
Element not found
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Differences between Linear and Binary Search:
Linear Search Binary Search
Starts searching from the first element Search the position of the searched
and compares each element with a element by finding the middle element
searched element of the array
Do not need the sorted list of element Need the sorted list of elements
Preferred for a small size data set Preferred for a large size data set
Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-34 Python Programming
Sorting:
Sorting is defined as an arrangement of data in a certain order. Sorting techniques are used
to arrange data(mostly numerical) in an ascending or descending order. It is a method used
for the representation of data in a more comprehensible format.
Sorting a large amount of data can take a substantial amount of computing resources if the
methods we use to sort the data are inefficient.
The efficiency of the algorithm is proportional to the number of items it is traversing.
For a small amount of data, a complex sorting method may be more trouble than it is worth.
On the other hand, for larger amounts of data, we want to increase the efficiency and speed
as far as possible.
Some of the real-life examples of sorting are:
• Telephone Directory: It is a book that contains telephone numbers and addresses of
people in alphabetical order.
• Dictionary: It is a huge collection of words along with their meanings in alphabetical
order.
• Contact List: It is a list of contact numbers of people in alphabetical order on a mobile
phone.
A sorting algorithm is used to arrange elements of an array/list in a specific order. For example,
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until
they are not in the intended order.
Just like the movement of air bubbles in the water that rise up to the surface, each element of
the array move to the end in each iteration. Therefore, it is called a bubble sort.
Working of Bubble Sort:
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
Starting from the first index, compare the first and the second elements. If the first element is
greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not in order.
The above process goes on until the last element.
2. Remaining Iteration:
The same process goes on for the remaining iterations. After each iteration, the largest element
among the unsorted elements is placed at the end.
bubbleSort(data)
print('Sorted Array in Ascending Order:',data)
Output1:
enter total number of elements:8
enter each element
12
-2
15
-89
66
-8
456
12
list created : [12, -2, 15, -89, 66, -8, 456, 12]
Sorted Array in Ascending Order: [-89, -8, -2, 12, 12, 15, 66, 456]
Python is an “object-oriented programming language.” This means that almost all the code is
implemented using a special construct called classes. Programmers use classes to keep related
things together. This is done using the keyword “class,” which is a grouping of object-oriented
constructs.
Python Class
• In Python everything is an object. To create objects, the required Model or Plan or Blue
print, which is nothing but a class.
• Ability to write a class to represent properties (attributes) and actions (behavior) of
object.
• Properties can be represented by variables. Actions can be represented by Methods. Class
contains both variables and methods. A real-life example of class
Class: Person
All class definitions start with the class keyword, which is followed by the name of the class and
a colon. Any code that is indented below the class definition is considered part of the class’s
body.
Syntax:
class ClassName:
# Statement-1
.
.
# Statement-N
Create a Class:
class MyClass:
x=5
print(MyClass)
Output: <class '__main__.MyClass'>
Example:
class Dog:
pass
The body of the Dog class consists of a single statement: the pass keyword. Pass is often used as
a placeholder indicating where code will eventually go. It allows you to run this code without
Python throwing an error.
Example:
class member:
estab = 1992
We have created a class with name ‘member’ and we declared some variables here. Now to
access those variables inside ‘member’ we can use class name as follows:
class.club
class.estab
Output:
XYZ Club
1992
self.name = name
self.age = age
The properties that all Dog objects must have are defined in a method called .__init__(). Every
time a new Dog object is created, .__init__() sets the initial state of the object by assigning the
values of the object’s properties. You can give .__init__() any number of parameters, but the first
parameter will always be a variable called self. When a new class instance is created, the
instance is automatically passed to the self parameter in .__init__() so that new attributes can be
defined on the object. The .__init__() method’s signature is indented four spaces. The body of
the method is indented by eight spaces. This indentation is important. It tells Python that
the .__init__() method belongs to the Dog class.
In the body of .__init__(), there are two statements using the self variable:
1. self.name = name creates an attribute called name and assigns to it the value of
the name parameter.
2. self. age = age creates an attribute called age and assigns to it the value of
the age parameter.
Attributes created in .__init__() are called instance attributes. An instance attribute’s value is
specific to a particular instance of the class.
On the other hand, class attributes are attributes that have the same value for all class instances.
You can define a class attribute by assigning a value to a variable name outside of .__init__().
For example, the following Dog class has a class attribute called species with the
value "Canis familiaris":
class Dog:
# Class attribute
species = "Canis familiaris"
Example-2:
class Product:
def __init__(self, name, cost, price):
self.name = name
self.cost = cost
self.price = price
def profit_margin(self):
return self.price - self.cost
Objects:
Objects are an instance of a class. It is an entity that has state and behavior. In a nutshell, it is an
instance of a class that can access the data.
For example - An integer variable belongs to integer class. An object is a real-life entity. An
object is the collection of various data and functions that operate on those data.
An object contains the following properties.
***
Create Object
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Output: 5
Example2:
class Cars:
def __init__(self, m, p):
self.model = m
self.price = p
Audi = Cars("R8", 100000)
print(Audi.model)
print(Audi.price)
Output: R8
100000
Audi = Cars():
Example3:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Output: John
36
Accessing Objects:
Output: 10
25
50
class Person:
def __init__(self, name,hobby):
self.name = name
self.hobby= hobby
def new(self):
print("Heyy my name is " + self.name + ". I Love " + self.hobby)
obj2 = Person("abc","coding")
obj2.new()
Output: Heyy my name is abc. I Love coding
Types of constructors
1. Default constructor
Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT
2. Parameterized constructor
3. Non-Parameterized constructor
The default constructor is a constructor that takes no arguments. It contains only one argument
called self, which is a reference to the instance that is being built.
Example1:
class Employee:
def display(self):
print('Inside Display')
emp = Employee()
emp.display()
Output: Inside Display
Example2:
class Assignments:
check= "not done"
def is_done(self):
print(self.check)
obj = Assignments()
obj.is_done()
Output: not done
Parameterized constructors are constructors that have parameters and a reference to the
instance being created called self. The self reference serves as the first argument.
Example1:
class Triangle:
base = 0
height = 0
area = 0
def __init__(self, b, h):
self.base = b
self.height = h
Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT
def areaOfTriangle(self):
self.area = self.base * self.height * 0.5
print("Area of triangle: " + str(self.area))
obj = Triangle(5, 14)
obj.areaOfTriangle()
Output: Area of triangle: 35.0
Example2:
class Family:
# Constructor - parameterized
members=5
def __init__(self, count):
print("This is parameterized constructor")
self.members = count
def show(self):
print("No. of members are ",self.members)
object = Family(10)
object.show()
Output: This is parameterized constructor
No. of members are 10
***
We can create list of object in Python by appending class instances to list. By this, every index in the
list can point to instance attributes and methods of the class and can access them. If you observe it
closely, a list of objects behaves like an array of structures in C.
Example1:
class Person:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# creating list
list = []
# appending instances to list
list.append( Person('Akash', 2) )
list.append( Person('Dinesh', 40) )
list.append( Person('Deepa', 44) )
for obj in list:
print( obj.name, obj.roll, sep =' ' )
Output: Akash 2
Dinesh 40
Deepa 44
Example2:
class Addition:
def __init__(self, x, y):
self.x = x
self.y = y
def Sum(self):
print( self.x + self.y )
# creating list
list = []
Example:
f=open("abc.txt",'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
Output:
File Name: abc.txt
File Mode: w
IsFile Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True
readlines():- It reads the entire file line by line and updates each line to a list
#Reading a file
f = open(__file__, 'r')
#readline()
text = f.readlines(25)
print(text)
f.close()
write(string):- It writes the contents of string to the file. It has no return value.
# Writing a file
tell():- It returns an integer that tells us the file object’s position from the beginning of the file in
the form of bytes
# Telling the file object position
f = open(__file__, 'r')
lines = f.read(10)
#tell()
print(f.tell())
f.close()
seek(offset, from_where):- Set file pointer position in a file. Offset indicates the number of
bytes to be moved. from_where indicates from where the bytes are to be moved.
# Setting the file object position
f = open(__file__, 'r')
lines = f.read(10)
print(lines)
#seek()
print(f.seek(2,2))
lines = f.read(10)
truncate():- Truncate the file’s size. The size defaults to the current position. The current file
position is not changed.
# Truncates the file
f = open(__file__, 'w')
#truncate()
f.truncate(10)
f.close()
close():- Used to close an open file. A closed file cannot be read or written any more.
# Opening and closing a file
f = open(__file__, 'r')
***
Code Separation: Error Handling can help us segregate the code that is required for error
handling from the main logic. The error related code can be placed inside the “except” block
which is segregating it from the regular code that contains the application logic.
Grouping Error Type and Error Differentiation: It can help us to segregate different kinds
of errors that are encountered during the execution. We can have multiple “except” blocks, each
handling a specific kind of error. In the article below, we will see the implementation of multiple
“except” blocks to handle different types of error.
2. Runtime Errors: Also known as exceptions. While executing the program if something
goes wrong because of end user input or programming logic or memory problems etc then we
will get Runtime Errors.
>>> print(10/0)
ZeroDivisionError: division by zero
print(10/"ten")
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors
Exception:
An Exception is an event , which occurs during the execution of a program, that disrupts the
normal flow of the program’s instructions.
Exception Handling:
Process of responding to the occurrence, during computation, of an exceptional conditions
required special processing-often changing the normal flow of the program execution.
• Whenever a runtime error occurs, it creates an exception.
• Usually, the program stops and Python prints an error message.
Examples:
For example, dividing by zero creates an exception:
>>> print 55/0
ZeroDivisionError: integer division or modulo
So does accessing a nonexistent list item:
>>> a = []
>>> print a[5]
IndexError: list index out of range
Or accessing a key that isn’t in the dictionary:
>>> b = {}
>>> print b[’what’]
KeyError: what
Try and except block : Handling Exceptions
Sometimes we want to execute an operation that could cause an exception, but we don’t want
the program to stop. We can handle the exception using the try and except statements.
• First, the try clause (the statement(s) between the try and except keywords) is
executed.
Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT
• If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
• If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then, if its type matches the exception named after the except keyword,
the except clause is executed, and then execution continues after the try/except block.
• If an exception occurs which does not match the exception named in the except clause,
it is passed on to outer try statements; if no handler is found, it is an unhandled
exception and execution stops with a message as shown above.
Process of Exception Handling:
try:
# Run this code
except:
#Excecute this code when there is an exception
else:
#No exceptions? Run this code
finally:
#Always run this code
Example1 :
try:
print(4/0)
except ZeroDivisionError:
print("Division by zero is undefined")
Output:
Division by zero is undefined
Example 2:
try:
print(12+"string")
except TypeError as e:
print(e)
Output:
unsupported operand type(s) for +: ‘int’ and ‘str’
Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT
Example 3:
try:
print(4/0)
print(12+"string")
except (TypeError, ZeroDivisionError):
print("This an error.")
Output:
This an error.
***
Output :
division by zero
I will always execute
***
Example:
try:
x = 'something'
if x == 'something':
raise Exception
except Exception:
print("x is something")
Output:
x is something
***
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
If we don’t have Anaconda installed, we can alternatively install the libraries using pip by
running the following commands from terminal:
pip install numpy
pip install pandas
Once we have installed these libraries, we are ready to open any Python coding environment (we
recommend Jupyter Notebook). In order to use these libraries, we need to import them using the
following lines of code. We’ll use the abbreviations np and pd, respectively to simplify our
function calls in the future.
import numpy as np
import pandas as pd
Arrays:
An array is a data type used to store multiple values using a single identifier (variable name). An
array contains an ordered collection of data elements where each element is of the same type and
can be referenced by its index (position).
The important characteristics of an array are:
• Each element of the array is of same data type, though the values stored in them may be
different.
• The entire array is stored contiguously in memory. This makes operations on array fast.
• Each element of the array is identified or referred using the name of the Array along with
the index of that element, which is unique for each element.
• The index of an element is an integral value associated with the element, based on the
element’s position in the array.
Difference between List and Array:
ist Array
List can have elements of different data types. All elements of an array are of same data type.
for example , [1,2.0,-3,’hello’,’a@’] for example, an array of floats may be:
[1.2, 5.4, 2.7]
Elements in list are not stored continuously in Array elements are stored in contiguous
memory. memory locations. This makes operations on
arrays faster than lists.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lists do not support element wise operations, Arrays support element wise operations. For
for example, addition, multiplication, etc. example, if A1 is an array, it is possible to say
because elements may not be of same type. A1/3 to divide each element of the array by 3.
Lists can contain objects of different datatype Numpy array takes up less space in memory as
that Python must store the type information for compared to a list because arrays do not
every element along with its element value. require storing the data type of each element
Thus lists take more space in memory and are separately.
less efficient.
List is a part of core Python. Array (ndarray) is a part of NumPy library.
Numpy Arrays:
• NumPy arrays are used to store lists of numerical data, vectors and matrices.
• The NumPy library has a large set of routines (built-in functions) for creating,
manipulating, and transforming NumPy arrays.
• Python language also has an array data structure, but it is not as versatile, efficient and
useful as the NumPy array.
• The NumPy array has contiguous memory allocation i.e., the memory space must be
divided into the fixed sized position and each position is allocated to a single data only.
Creation of NumPy Arrays from List:
There are several ways to create arrays. To create an array and to use its methods, first we need
to import the NumPy library.
#NumPy is loaded as np (we can assign any #name), numpy must be written in lowercase
>>> import numpy as np
The NumPy’s array() function converts a given list into an array.
Example:
#Create an array called array1 from the given list.
array1 = np.array([10,20,30]) #Display the contents of the array
array1 #array([10, 20, 30])
print(array1) # [10 20 30]
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
#incorrect way of declaring array
a = np.array(1,2,3,4)
#correct way of declaring array
a = np.array([1,2,3,4])
Creating a 1-D array:
An array with a single row of elements is called 1-D array. It may contain numbers or strings and
so on.
Example:
array2=np.array([5,-7.4,’a’,7.2])
array2
Output:
array(['5', '-7.4', 'a', '7.2'], dtype='<U32')
Since, there is a string value in the list, all the integer and float values have been promoted to
string, while converting the list to array.
Creating a 2-D array:
A 2-D array can be created by passing nested lists to the array() function.
Example:
array3=np.array([[2.4,3],[4.91,7],[0,-1]])
array3
Output:
array([[ 2.4 , 3. ],
[ 4.91, 7. ],
[ 0. , -1. ]])
Other Ways of creating numpy arrays:
1. We can specify data type (integer, float, etc.) while creating array using dtype as an
argument to array(). This will convert the data automatically to the mentioned type.
Example 1:
import numpy as np
array4 = np.array( [ [1,2], [3,4] ], dtype=float)
array4
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Output:
array([[1., 2.],
[3., 4.]])
Example 2:
import numpy as np
array5 = np.array( [ [1.4567,2.45], [3.09,4.45] ], dtype=int)
array5
Output:
array([[1, 2],
[3, 4]])
2. We can create an array with all elements initialized to 0 using the function zeros(). By
default, the data type of the array created by zeros() is float. The following code will
create an array with 3 rows and 4 columns with each element set to 0:
Example1:
array6 = np.zeros((3,4))
array6
Output:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
3. We can create an array with all elements initialized to 1 using the function ones(). By
default, the data type of the array created by ones() is float. The following code will
create an array with 3 rows and 2 columns:
Example:
array7 = np.ones((3,2))
array7
Output:
array([[1., 1.],
[1., 1.],
[1., 1.]])
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
4. We can create an array with numbers in a given range and sequence using the arange()
function. This function is analogous to the range() function of Python.
Example 1:
array8 = np.arange(6) # an array of 6 elements is created with start value 0 and step size 1
array8
Output:
array([0, 1, 2, 3, 4, 5])
Example 2:
# Creating an array with start value -2, end value 24 and step size 4
array9 = np.arange( -2, 24, 4 )
array9
Output:
array([-2, 2, 6, 10, 14, 18, 22])
Accessing Elements from Numpy Array:
NumPy arrays can be indexed, sliced and iterated over.
a. Indexing:
For 2-D arrays, indexing for both dimensions starts from 0, and each element is referenced
through two indexes i and j, where i represents the row number and j represents the column
number.
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Here, marks[i,j] refers to the element at (i+1)th row and (j+1)th column because the index value
starts at 0. Thus marks[3,1] is the element in 4th row and 2nd column which is 72 (marks of
Prasad in English).
Example:
import numpy as np
marks=np.array([[78,67,56],[76,75,47],[84,59,60],[67,72,54]])
marks
output:
array([[78, 67, 56],
[76, 75, 47],
[84, 59, 60],
[67, 72, 54]])
# accesses the element in the 1st row in the 3rd column
marks[0,2]
#56
marks [0,4]
#index Out of Bound "Index Error".
Index 4 is out of bounds for axis with size 3
b. Slicing:
Sometimes it is necessary to extract a part of an array. This is done through slicing. We can
define which part of the array to be sliced by specifying the start and end index values using
[start:end] along with the array name.
Example 1:
#creating ARRAY
import numpy as np
array8=np.array([-2, 2, 6, 10, 14, 18, 22])
array8
# excludes the value at the end index
array8[3:5]
# reverse the array
array8[ : : -1]
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Output:
array([-2, 2, 6, 10, 14, 18, 22])
array([10,14])
array([22,18,14,10,6,2,-2])
Example 2:
Slicing is done for 2-D arrays. For this, let us create a 2-D array called array9 having 3 rows and
4 columns.
Example:
array9 = np.array([[ -7, 0, 10, 20], [ -5, 1, 40, 200], [ -1, 1, 4, 30]])
# access all the elements in the 3rd column
array9[0:3,2] # specified rows in the range 0:3 because the end value of the range is excluded.
Output:
array([10, 40, 4])
print(array9[0:2,2] ) # array([10, 40]) since specified rows in the range 0:2.
# access elements of 2nd and 3rd row from 1st # and 2nd column
array9[1:3,0:2]
array([[-5, 1], [-1, 1]])
If row indices are not specified, it means all the rows are to be considered. Likewise, if column
indices are not specified, all the columns are to be considered. Thus, the statement to access all
the elements in the 3rd column can also be written as:
array9[:,2]
Output:
array([10, 40, 4])
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes 42 Python Programming
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
[ 70, 104]])
#Exponentiation
array1 ** 3
Output:
array([[ 27, 216],
[ 64, 8]], dtype=int32)
#Division >>> array2 / array1
Output:
array([[3.33333333, 3.33333333],
[3.75 , 6. ]])
#Element wise Remainder of Division #(Modulo)
array2 % array1
Output:
array([[1, 2],
[3, 0]], dtype=int32)
It is important to note that for element-wise operations, size of both arrays must be same. That is,
array1.shape must be equal to array2.shape.
2. Transpose:
Transposing an array turns its rows into columns and columns to rows just like matrices in
mathematics.
#Transpose
import numpy as np
array3 = np.array([[10,-7,0, 20], [-5,1,200,40],[30,1,-1,4]])
array3
Output:
array([[ 10, -7, 0, 20],
[ -5, 1, 200, 40],
[ 30, 1, -1, 4]]) # the original array does not change
array3.transpose() # it transposes the original array
Output:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
array([[ 10, -5, 30],
[ -7, 1, 1],
[ 0, 200, -1],
[ 20, 40, 4]])
3. Sorting:
Sorting is to arrange the elements of an array in an order either ascending or descending. By
default, numpy does sorting in ascending order.
import numpy as np
array4 = np.array([1,0,2,-3,6,8,4,7])
array4.sort()
array4
Output:
array([-3, 0, 1, 2, 4, 6, 7, 8])
array3 = np.array([[10,-7,0, 20], [-5,1,200,40],[30,1,-1,4]])
array3.sort()
array3
Output:
array([[ -7, 0, 10, 20],
[ -5, 1, 40, 200],
[ -1, 1, 4, 30]])
array5 = np.array([[10,-7,0, 20], [-5,1,200,40],[30,1,-1,4]])
#axis =0 means column-wise sorting
array5.sort(axis=0)
array5
Output:
array([[ -5, -7, -1, 4],
[ 10, 1, 0, 20],
[ 30, 1, 200, 40]])
***
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-43 Python Programming
Introduction to Pandas
Pandas is an open-source library that is made mainly for working with relational or labeled
data both easily and intuitively. It provides various data structures and operations for
manipulating numerical data and time series. This library is built on top of the NumPy
library. Pandas is fast and it has high performance & productivity for users.
History: Pandas were initially developed by Wes McKinney in 2008 while he was working
at AQR Capital Management. He convinced the AQR to allow him to open source the
Pandas. Another AQR employee, Chang She, joined as the second major contributor to the
library in 2012. Over time many versions of pandas have been released. The latest version
of the pandas is 1.4.1
Advantages
• Fast and efficient for manipulating and analyzing data.
• Data from different file objects can be loaded.
• Easy handling of missing data (represented as NaN) in floating point as well as non-
floating point data
• Size mutability: columns can be inserted and deleted from DataFrame and higher
dimensional objects
• Data set merging and joining.
• Flexible reshaping and pivoting of data sets
• Provides time-series functionality.
• Powerful group by functionality for performing split-apply-combine operations on
data sets.
Getting Started
The first step of working in pandas is to ensure whether it is installed in the Python folder
or not. If not then we need to install it in our system using pip command. Type cmd
command in the search box and locate the folder using cd command where python-pip
file has been installed. After locating it, type the command:
pip install pandas
After the pandas have been installed into the system, you need to import the library. This
module is generally imported as:
import pandas as pd
Here, pd is referred to as an alias to the Pandas.
Pandas generally provide two data structures for manipulating data, They are:
• Series
• DataFrame
Series: Pandas Series is a one-dimensional labeled array capable of holding data of any
type (integer, string, float, python objects, etc.). The axis labels are collectively called
•
Creating a Series
In the real world, a Pandas Series will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, an Excel file. Pandas Series can be created
from the lists, dictionary, and from a scalar value etc.
import pandas as pd
import numpy as np
# Creating empty series
ser = pd.Series()
print(ser)
# simple array
data = np.array(['g', 'm', 'r', 'i', 't'])
ser = pd.Series(data)
print(ser)
Output:
Series([], dtype: float64)
0 g
1 m
2 r
3 i
4 t
dtype: object
DataFrame
Creating a DataFrame:
In the real world, a Pandas DataFrame will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, an Excel file. Pandas DataFrame can be
created from the lists, dictionary, and from a list of dictionaries, etc.
import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
# list of strings
lst = [['This', 'is', 'GMR', ],['Institute', 'of' ,'Technology']]
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
Output:
Empty DataFrame
Columns: []
Index: []
0 1 2
0 This is GMR
1 Institute of Technology
***
Basic operations that can be applied on a pandas Data Frame are as shown below.
1. Creating a Data Frame.
2. Performing operations on Rows and Columns.
3. Data Selection, addition, deletion.
4. Working with missing data.
5. Renaming the Columns or Indices of a DataFrame.
The Pandas data frame can be created by loading the data from the external, existing
storage like a database, SQL, or CSV files. But the Pandas Data Frame can also be created
import pandas as pd
# Dictionary of key pair values called data
data = {
'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age
0 Ashika 24
1 Tanu 23
2 Ashwin 22
3 Mohit 19
4 Sourabh 10
Selecting a Row: Pandas Data Frame provides a method called “loc” which is used to
retrieve rows from the data frame. Also, rows can also be selected by using the “iloc”
as a function.
import pandas as pd
data = {'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]}
df = pd.DataFrame(data)
# Selecting a row
row = df.loc[1]
print(row)
Output:
Name Tanu
Age 23
Name: 1, dtype: object
3. Data Selection, addition, deletion.
You can treat a DataFrame semantically like a dictionary of like-indexed Series
objects. Getting, setting, and deleting columns works with the same syntax as the
analogous dictionary operations:
import pandas as pd
data = {'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]}
df = pd.DataFrame(data)
# Selecting the data from the column
Columns can be deleted like with a dictionary just use the del operation.
del df[‘Age’]
Data can be added by using the insert function. The insert function is available to insert
at a particular location in the columns:
df.insert(1, ‘name’, df[‘Name’])
print(df)
print(df.fillna(0))
Output:
First name Age
import pandas as pd
data = {‘NAMe’:[‘Ashika’, ‘Tanu’, ‘Ashwin’, ‘Mohit’, ‘Sourabh’],
‘AGe’: [24, 23, 22, 19, 10]}# Calling the pandas data frame
df = pd.DataFrame(data)
newcols = {
‘NAMe’: ‘Name’,
‘AGe’: ‘Age’
}
# Use `rename()` to rename your columns
df.rename(columns=newcols, inplace=True)
print(df)
Output:
***
A) Write a Python program to Create a data frame from dict of numpy array.
import pandas as pd
import numpy as np
Ouutput:
B) Write a Python program to Clean the string data in the given pandas data frame.
import pandas as pd
print(df)
Output:
Date Product Updated_Price Discount
0 10/2/2011 UMbreLla 1250 10
1 11/2/2011 maTress 1450 8
2 12/2/2011 BaDmintoN 1550 15
3 13/2/2011 Shuttle 400 10
Date Product Updated_Price Discount
0 10/2/2011 Umbrella 1250 10
1 11/2/2011 Matress 1450 8
2 12/2/2011 Badminton 1550 15
3 13/2/2011 Shuttle 400 10
print(df)
Output
mynumbers <= 53
0 51 True
1 52 True
2 53 True
3 54 False
4 55 False
print (df)
Output:
mynumbers <= 53
0 51 True
1 52 True
2 53 True
3 54 False
4 55 False
print (df)
Output:
First_name Status
0 Hanah Not Found
1 Ria Found
2 Jay Not Found
3 Bholu Not Found
4 Sachin Not Found
print (df)
Output:
First_name Status
0 Hanah Not Found
1 Ria Found
2 Jay Found
3 Bholu Not Found
4 Sachin Not Found
***