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

Python Programming

This document serves as an introduction to Python programming, detailing its features, execution modes, keywords, identifiers, variables, comments, data types, and operators. It explains the differences between mutable and immutable data types, as well as various operators including arithmetic, relational, assignment, and logical operators. The document also provides examples to illustrate key concepts and syntax in Python.

Uploaded by

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

Python Programming

This document serves as an introduction to Python programming, detailing its features, execution modes, keywords, identifiers, variables, comments, data types, and operators. It explains the differences between mutable and immutable data types, as well as various operators including arithmetic, relational, assignment, and logical operators. The document also provides examples to illustrate key concepts and syntax in Python.

Uploaded by

muneebrasheeth
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Topic/Title: INTRODUCTION TO PYTHON

Name of the Paper : Python Programming


Semester : VI
Department : Computer Science
Name of the Faculty : G. Preetha
Designation : Assistant Professor
Introduction to Python

An ordered set of instructions to be executed by a computer to carry out a


specific task is called a program, and the language used to specify this set of
instructions to the computer is called a programming language.
Python uses an interpreter to convert its instructions into machine language, so
that it can be understood by the computer.
An interpreter processes the program statements one by one, first translating and
then executing.
This process is continued until an error is encountered or the whole program is
executed successfully.
In both the cases, program execution will stop. On the contrary, a compiler
translates the entire source code, as a whole, into the object code. After scanning
the whole program, it generates error messages.
Features of Python

Python is a high level language. It is a free and open source language.


It is an interpreted language, as Python programs are executed by an interpreter.
Python programs are easy to understand as they have a clearly defined syntax and
relatively simple structure.
Python is case-sensitive. For example, NUMBER and number are not same in Python.
Python is portable and platform independent, means it can run on various operating
systems and hardware platforms.
Python has a rich library of predefined functions.
Python is also helpful in web development. popular web services and
Many applications are built using Python.
Python uses indentation for blocks and nested blocks.
Working with Python
To write and run (execute) a Python program, we need to have a Python interpreter

installed on our computer or we can use any online Python interpreter.

The interpreter is also called Python shell.

The symbol >>> is the Python prompt, which indicates that the interpreter is ready
to take instructions. We can type commands or statements on this prompt to execute

them using a Python interpreter.


Execution Modes
There are two ways to use the Python interpreter:
a) Interactive mode
b) Script mode
Interactive mode allows execution of individual statement instantaneously. Whereas,
Script mode allows us to write more than one instruction in a file called Python source
code file that can be executed.

(A) Interactive Mode


To work in the interactive mode, we can simply type a Python statement on the >>>
prompt directly. As soon as we press enter, the interpreter executes the statement and
displays the result.
Working in the interactive mode is convenient for testing a single line code for
instant execution.
But in the interactive mode, we cannot save the statements for future use and we
have to retype the statements to run them again.
(B) Script Mode

In the script mode, we can write a Python program in a file, save it and then use the

interpreter to execute it.

Python scripts are saved as files where file name has extension “.py”.

To execute a script, We can open the program directly from IDLE


While working in the script mode, after saving the file, click [Run]->[Run Module] from

the menu.
Python Keywords

Keywords are reserved words.


Each keyword has a specific meaning to the Python interpreter, and we can use a keyword
in our program only for the purpose for which it has been defined.
As Python is case sensitive, keywords must be written exactly as given in the below
Table.
Python keywords:
False
return
None
continue
for
try
True
def
while
del
Identifiers
In programming languages, identifiers are names used to identify a
variable, function, or other entities in a program.
The rules for naming an identifier in Python are as follows:
The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_). This may be followed by any combination of characters
a–z, A–Z, 0–9 or underscore (_). Thus, an identifier cannot start with a digit.
It can be of any length. (However, it is preferred to keep it short and
meaningful).
It should not be a keyword or reserved word
We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
For example, to find the average of marks obtained by a student in three
subjects, we can choose the identifiers as marks1, marks2, marks3 and avg rather
than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3
Variables
A variable in a program is uniquely identified by a name (identifier).
Variable in Python refers to an object — an item or element that is stored in the
memory.
Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or
any combination of alphanumeric characters (CD67).
In Python we can use an assignment statement to create new variables and assign
specific values to them.

Example:
gender = 'M’
message = "Keep Smiling"
price = 987.9
Comments
Comments are used to add a remark or a note in the source code.
Comments are not executed by interpreter.
They are added with the purpose of making the source code easier for humans to
understand. They are used primarily to document the meaning and purpose of source
code and its input and output requirements, so that we can remember later how it
functions and how to use it.
For large and complex software, it may require programmers to work in teams and
sometimes, a program written by one programmer is required to be used or maintained
by another programmer.

In Python, a comment starts with # (hash sign).


Everything following the # till the end of that line is treated as a comment and the
interpreter simply ignores it while executing the statement.
Python Data Types
Data types are the classification or categorization of data items. It represents
the kind of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and variables are
instance (object) of these classes.

Following are the standard or built-in data type of Python:

•Numeric
•Sequence Type
•Boolean
•Set
•Dictionary
.

Numeric

In Python, numeric data type represent the data which has numeric value. Numeric value can be
integer, floating number or even complex numbers. These values are defined as int,
float and complex class in Python.

Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.

Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific notation.

Complex Numbers – Complex number is represented by complex class. It is specified


as (real part) + (imaginary part)j. For example – 2+3j
Sequence
Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows
to store multiple values in an organized and efficient fashion. There are several sequence types in
Python –
•String
•List
•Tuple

String

In Python, Strings are arrays of bytes representing Unicode characters.


A string is a collection of one or more characters put in a single quote, double-quote or
triple quote.
Accessing elements of String

In Python, individual characters of a String can be accessed by using the method of


Indexing. Indexing allows negative address references to access characters from the back of the
String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.
# Python Program to
Access # characters of
String String1 =
"GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\n First character of String is: ")
print(String1[0])
# Printing Last character
print("\n Last character of String is: ")
print(String1[-1])

Output:
Initial String: GeeksForGeeks
First character of String is: G
Last character of String is: s
List

Lists are just like the arrays, declared in other languages which is a ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type.

Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].

Example To create a list


>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
Output: [5, 3.4, 'New Delhi', '20C', 45]
Tuple

Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
This is unlike list, where values are enclosed in brackets [ ].

Once created, we cannot change items in the tuple. Similar to List, items may be of different
data types.

Example
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a’)
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Mutable and Immutable Data
Types
Variables whose values can be changed after they are created and assigned are called
mutable.
Variables whose values cannot be changed after they are created and assigned are called
immutable.
When an attempt is made to update the value of an immutable variable, the old variable is
destroyed and a new variable is created by the same name in memory.
Python data types can be classified into mutable and immutable.

Classification of data types


Immutable Data Mutable Data Type
Type Lists
Integer Dictionary
Float
Boolean
Complex
Strings
Tuples
Operators
An operator is used to perform specific mathematical or logical operation on values.
The values that the operator works on are called operands.
For example, in the expression 10 + num, the value 10, and the variable num
are operands and the + (plus) sign is an operator.
Arithmetic Operators
Python supports arithmetic operators to perform the four basic arithmetic operations as
well as modular division, floor division and exponentiation.
'+' operator can also be used to concatenate two strings on either side of the operator.
>>> str1 = "Hello"
>>> str2 = "India"
>>> str1 + str2
Output:'HelloIndia' ‘
*' operator repeats the item on left side of the operator if first operand is a string and
second operand is an integer value.
>>> str1 = 'India’
>>> str1 * 2
Output: 'IndiaIndia'
Operator Operation Description Example
Adds two numeric >>> num1 = 5
values on either side of >>> num2 = 6
+ Addition the operator >>> num1 + num2
11

Subtracts the operand >>> num1 = 5


on the right from the >>> num2 = 6
- Subtraction operand on the left >>> num1 - num2
-1
Operator Operation Description Example
Multiplies the two >>> num1 = 5
values on both side of >>> num2 = 6
the operator. >>> num1 * num2
30

* Multiplication Repeats the item on left >>> str1 = 'India’


of the operator if first >>> str1 * 2 'IndiaIndia’
operand is a string and
second operand is an
integer value
Divides the operand on >>> num1 = 8
the left by the operand >>> num2 = 4
/ Division on the right and returns >>> num2 / num1
the quotient 0.5
Operator Operation Description Example

Divides the operand on >>> num1 = 13


the left by the operand >>> num2 = 5
% Modulus on the right and returns >>> num1 % num2
the remainder 3

Divides the operand on >>> num1 = 13


the left by the operand on >>> num2 = 4
the right and returns the >>> num1 // num2
// Floor Division quotient by removing the 3
decimal part. It is >>> num2 // num1
sometimes also called 0
integer division.
Performs exponential >>> num1 = 3
(power) calculation on >>> num2 = 4
operands. That is, raise >>> num1 ** num2
** Exponent the operand on the left to 81
the power of the operand
on the right
Relational Operators
Relational operator compares the values of the operands on its either side and determines the
relationship among them.
Assume the Python variables num1 = 10, num2 = 0, num3 = 10, str1 = "Good", str2 =
"Afternoon" for the following examples:
Relational Operators in Python

Operator Operation Description Example

If the values of two >>> num1 == num2


operands are equal, then False
== Equals to the condition is True, >> str1 == str2
otherwise it is False False

to If values of two >>> num1 != num2


operands are not equal, True
then condition is True, >>> str1 != str2
!= Not equal otherwise it is False True
>>> num1 != num3
Operator Operation Description Example
If the value of the >>> num1 > num2
left-side operand is True
greater than the value >>> str1 > str2
> Greater than of the right-side True
operand, then condition
is True, otherwise it is
False
If the value of the >>> num1 < num3
left-side operand is less False
Less than than the value of the >>> str2 < str1
< right-side operand, then True
condition is True,
otherwise it is False

If the value of the >>> num1 >= num2


Greater than or equal to left-side operand is True
greater than or equal to
Assignment Operators

Assignment operator assigns or changes the value of the variable on its left.

Assignment Operators in Python

Operator Description Example

>>> num1 = 2
>>> num2 = num1
>>> num2
2
Assigns valuefrom right-side >>> country = 'India’
= >>> country
operand to left side operand
'India'
Operator Description Example

It adds the value of right-side >>> num1 = 10


operand to the left-side operand >>> num2 = 2
and assigns the result to the >>> num1 += num2
+= left-side operand Note: x += y is >>> num1 12
same as x = x + y >>> num2
2

It subtracts the value of right-side >>> num1 = 10


operand from the left-side operand >>> num2 = 2
and assigns the result to left-side >>> num1 -= num2
operand Note: x -= y is same as x >>> num1
-= =x-y 8
Logical Operators

There are three logical operators supported by Python.


These operators (and, or, not) are to be written in lower case only.
The logical operator evaluates to either True or False based on the logical operands on either
side.
Every value is logically either True or False.
By default, all values are True except None, False, 0 (zero), empty collections "", (), [], {}, and
few other special values.
So if we say num1 = 10, num2 = -20, then both num1 and num2 are logically True.
Logical operators

Operator Operation Description Example

If both the operands are >>> True and True


True, then condition True
becomes True >>> num1 = 10
and Logical AND >>> num2 = -20
>>>bool(num1 and num2)
True
If any of the two operands >>> True or
are True, then condition True True
or Logical OR becomes True >>> True or False
True

Used to reverse the logical >>> num1 = 10


state of its operand >>> bool(num1)
not Logical NOT True
Precedence of Operators
Evaluation of the expression is based on precedence of operators.
When an expression contains different kinds of operators, precedence determines which
operator should be applied first.
Higher precedence operator is evaluated before the lower precedence operator.
Binary operators are operators with two operands.
The unary operators need only one operand, and they have a higher precedence than the binary
operators.
The minus (-) as well as + (plus) operators can act as both unary and binary operators, but not
is a unary logical operator.
Example:
How will Python evaluate the following expression?
20 - 30 + 40
Solution: The two operators (–) and (+) have equal precedence. Thus, the first operator, i.e.,
subtraction is applied before the second operator, i.e., addition (left to right).
=
= (20
-10 –+ 30)
40 + 40 #Step
#Step 21
= 30 #Step 3
Precedence of all operators in Python

Order of Precedence Operators Description

** Exponentiation (raise to the power)


1

~ ,+, - Complement, unary plus and unary


2 minus
* ,/, %, // Multiply, divide, modulo and floor
3 division
+, - Addition and subtraction
4

<= , < , > , >=, == , != Relational and Comparison operator


5

=, %=, /=, //=, -=, +=, *=, **= Assignment operators


6
Order of Precedence Operators Description

is, is not Identity operator


7

in, not in Membership operators


8

not
9

and
10
Logical operators

11 or
Expressions

An expression is defined as a combination of constants, variables, and operators.


An expression always evaluates to a value.
A value or a standalone variable is also considered as an expression but a standalone operator
is not an expression.
Examples of valid expressions are given below.
(i) 100
(ii) num (iii) num – 20.4
(iv) 3.0 + 3.14
(v) 23/3 -5 * 7(14 -2)
(vi) "Global" + "Citizen"
Input and Output

A program needs to interact with the user’s to get some input data or information from the
end user and process it to give the desired output.
In Python, we have the input() function for taking the user input.
The input() function prompts the user to enter data.
It accepts all user input as string.
The user may enter a number or a string but the input() function treats them as strings only.
The syntax for input() is:
input ([Prompt])
Prompt is the string we may like to display on the screen prior to taking the input, and it is
optional.
When a prompt is specified, first it is displayed on the screen after which the user can enter
data.
The input() takes exactly what is typed from the keyboard, converts it into a string and assigns
it to the variable on left-hand side of the assignment operator (=).
Entering data for the input function is terminated by pressing the enter key.
Example for Input Statement

>>> fname = input("Enter your first name: ")


Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
Explanation
The variable fname will get the string ‘Arnab’, entered by the user.
Similarly, the variable age will get the string ‘19’.
We can typecast or change the datatype of the string data accepted from user to an appropriate
numeric value.
For example, the following statement will convert the accepted string to an integer.
If the user enters any non-numeric value, an error will be generated.
Print Statement

Python uses the print() function to output data to standard output device — the screen.
The function print() evaluates the expression before displaying it on the screen.
The print() outputs a complete line and then moves to the next line for subsequent output.
The syntax for print() is:
print(value [, ..., sep = ' ', end = '\n']) • sep:
The optional parameter sep is a separator between the output values.
We can use a character, integer or a string as a separator.
The default separator is space. • end:
This is also optional and it allows us to specify any string to be appended after the last
value.
The default is a new line.
Example for Print Statement

Statement Output

print("Hello") Hello

print(10*2.5) 25.0

print("I" + "love" + "my" + "country") Ilovemycountry

print("I'm", 16, "years old") I'm 16 years old


Explanation of the example

The third print function in the above example is concatenating strings, and we use + (plus)
between two strings to concatenate them.
The fourth print function also appears to be concatenating strings but uses commas (,)
between strings. Actually, here we are passing multiple arguments, separated by commas to
the print function.
As arguments can be of different types, hence the print function accepts integer (16)
along with strings here.
But in case the print statement has values of different types and ‘+’ is used instead of comma,
it will generate an error.
Conditional And Looping Construct

The order of execution of the statements in a program is known as flow of control.


The flow of control can be implemented using control structures.
Python supports two types of control structures—selection and repetition.

Selection
A decision involves selecting from one of the two or more possible options.
In programming, this concept of decision making or selection is implemented with the help of
if..else statement.
The syntax of if statement is:

if condition:
statement(s)
Example

age = int(input("Enter your age "))


if age >= 18:
print("Eligible to vote")

Explanation
If the age entered by the user is greater than 18, then print that the user is eligible to vote.

If the condition is true, then the indented statement(s) are executed.

The indentation implies that its execution is dependent on the condition.


There is no limit on the number of statements that can appear as a block under the if

statement.
if..else statement

A variant of if statement called if..else statement allows us to write two alternative paths
and the control condition determines which path gets executed.
The syntax for if..else statement is as follows.
if condition:
statement(s)
else:
statement(s)
Example

age = int(input("Enter your age: "))


if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Program to print the positive difference of two numbers.

#Program to print the positive difference of two numbers


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2,"is",diff)

Output:
Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1
elif statement
The syntax for a selection structure using elif is as shown
below.
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Example
Check whether a number is positive, negative, or zero.
number = int(input("Enter a number: ")
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
Repetition

Repetition of a set of statements in a program is made possible using looping constructs.

The ‘For’ Loop

The for statement is used to iterate over a range of values or a sequence.


The for loop is executed for each of the items in the range.
These values can be either numeric, they can be elements of a data type like a string, list, or
tuple. With every iteration of the loop, the control variable checks whether each of the
values in the range have been traversed or not.
When all the items in the range are exhausted, the statements within loop are not executed;
the control is then transferred to the statement immediately following the for loop.
While using for loop, it is known in advance the number of times the loop will execute.
Flow chart of for loop

Start

Initialization
Statement

Test True Body of for


Expression loop

False

Exit for loop

Statements
following the loop

Stop
Syntax of the For Loop for in

for <control-variable> in <sequence/items in range>:


<statements inside body of the loop>

Program to print even numbers in a given sequence using for


loop.
#Print even numbers in the given sequence
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number’)

Output:

2 is an even Number
4 is an even Number
The Range() Function

The range() is a built-in function in Python.


Syntax of range() function is:
range([start], stop[, step])
It is used to create a list containing a sequence of integers from the given start value
upto stop value (excluding stop value), with a difference of the given step value.
In function range(), start, stop and step are parameters.
The start and step parameters are optional.
If start value is not specified, by default the list starts from 0.
If step is also not specified, by default the value increases by 1 in each iteration.
All parameters of range() function must be integers.
The step parameter can be a positive or a negative integer excluding zero.
Example
>>> list(range(10)-)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
The ‘While’ Loop
The while statement executes a block of code repeatedly as long as the control
condition of the loop is true.
The control condition of the while loop is executed before any statement inside the loop
is executed.
After each iteration, the control condition is tested again and the loop continues as long
as the condition remains true.
When this condition becomes false, the statements in the body of loop are not executed
and the control is transferred to the statement immediately following the body of while
loop.
If the condition of the while loop is initially false, the body is not executed even once.
The statements within the body of the while loop must ensure that the condition
eventually becomes false; otherwise the loop will become an infinite loop, leading to a
logical error in the program.
Syntax of while Loop
while test_condition:
body of while
Flow chart of while Loop

Start

Initialization Statement

Test False
Expression

Statements
following the while
True loop

Body of Loop
Stop
Program to print first 5 natural numbers using while loop.

#Print first 5 natural numbers using while loop


count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Break and Continue Statement

Looping constructs allow programmers to repeat tasks efficiently.


In certain situations, when some particular condition occurs, we may want to exit from a loop
(come out of the loop forever) or skip some statements of the loop before continuing
further in the loop. These requirements can be achieved by using break and continue
statements, respectively.
Python provides these statements as a tool to give more flexibility to the programmer to
control the flow of execution of a program.

Break Statement

The break statement alters the normal flow of execution as it terminates the current loop and
resumes execution of the statement following that loop.
Program to demonstrate use of break
statement.#Program to demonstrate the use of break statement in loop
num = 0
for num in range(10):
num = num + 1
if num == 8:
break
print('Num has value ' + str(num))
print('Encountered break!! Out of loop’)
Output:
Num has value 1
Num has value 2
Num has value 3
Num has value 4
Num has value 5
Num has value 6
Num has value 7
Encountered break!! Out of loop
Continue Statement

When a continue statement is encountered, the control skips the execution of remaining
statements inside the body of the loop for the current iteration and jumps to the beginning of
the loop for the next iteration.

If the loop’s condition is still true, the loop is entered again, else the control is transferred to

the statement immediately following the loop.


Program to demonstrate the use of continue
statement.#Prints values from 0 to 6 except 3
num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value ' + str(num))
print('End of loop’)

Output:

Num has value 1


Num has value 2
Num has value 4
Num has value 5
Num has value 6
End of loop
Nested Loops
A loop may contain another loop inside it.
A loop inside another loop is called a nested loop.

Program to find prime numbers between 2 to 50 using nested for


loops. #Use of nested loops to find the prime numbers between 2
to 50 num = 2
for i in range(2, 50):
j= 2
while ( j <= (i/2)):
if (i % j == 0): #factor found
break #break out of while loop
j += 1
if ( j > i/j) : #no factor found
print ( i, "is a prime number")
print ("Bye Bye!!")
UNIT-III

Strings
Strings
String is a sequence which is made up of one or more UNICODE characters.
Here the character can be a letter, digit, whitespace or any other symbol.
A string can be created by enclosing one or more characters in single, double or triple
quote.

>>> str1 = 'Hello World!’


>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!‘’
str1, str2, str3, str4 are all string variables having the same value 'Hello World!’.
Values stored in str3 and str4 can be extended to multiple lines using triple codes as can
be seen in the following example:
>>> str3 = """Hello World! welcome to the world of Python""“
>>> str4 = '''Hello World! welcome to the world of Python'''
Accessing Characters in a String

Each individual character in a string can be accessed using a technique called indexing.
The index specifies the character to be accessed in the string and is written in square
brackets ([ ]).
The index of the first character (from left) in the string is 0 and the last character is n-1
where n is the length of the string.
If we give index value out of this range then we get an IndexError.
The index must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!’
#gives the first character of str1
>>> str1[0]
'H’
The index can also be an expression including variables and operators but the expression
must evaluate to an integer.
Python allows an index value to be negative also.
Negative indices are used when we want to access the characters of the string from right
to left.
An inbuilt function len() in Python returns the length of the string that is passed as parameter.
For example, the length of string str1 = 'Hello World!' is 12. #gives the length of the string str1
>>> len(str1) 12 #length of the string is assigned to n >>> n = len(str1) >>> print(n) 12 #gives the
last character of the string >>> str1[n-1] '!' #gives the first character of the string >>> str1[-n] 'H'
3. sum(x[,num]): Sum of all the elements in the sequence from left to right. if given parameter, num is
added to the sum. x is a numeric sequence and num is an optional argument. Example:
>>> sum([2,4,7,3])
16
>>> sum([2,4,7,3],3)
19
>>> sum((52,8,4,2))
66

4. len(x): Count of elements in x. x can be a sequence or a dictionary.


Example:
>>> len(“Patience”)
8
>>> len([12,34,98])
3
>>> len((9,45))
2
Module
Other than the built-in functions, the Python standard library also consists of a number of modules.

While a function is a grouping of instructions, a module is a grouping of functions.

When a program grows, function is used to simplify the code and to avoid repetition.

For a complex problem, it may not be feasible to manage the code in one single file.

Then, the program is divided into different parts under different levels, called modules.

Also, suppose we have created some functions in a program and we want to reuse them in another

program.

In that case, we can save those functions under a module and reuse them.

A module is created as a python (.py) file containing a collection of function definitions.


Built-in Modules

Python library has many built-in modules that are really handy to programmers.
Let us explore some commonly used modules and the frequently used functions that are
found in those modules:

•math
•random
•statistics
1. Module name : math

It contains different types of mathematical functions. Most of the functions in this module
return a float value.
Some of the commonly used functions in math module are discussed below.
In order to use the math module we need to import it using the following statement:
import math
[Link](x): ceiling value of x, x may be an integer or floating point
number. Example:
>>> [Link](-9.7)
-9
>>> [Link] (9.7)
10
>>> [Link](9)
9
[Link](x): floor value of x, x may be an integer or floating point number.
Example:
>>> [Link](-4.5)
-5
>>> [Link](4.5)
4
>>> [Link](4)
4
[Link](x): factorial of x, x is a positive
integer. Example:
>>> [Link](5)
120
y
[Link](x,y): x (x raised to the power y). x, y may be an integer or floating point number.
Example:
>>> [Link](3,2)
9.0
>>> [Link](4,2.5)
32.0
[Link](x): square root of x, x may be a positive integer or floating point
number. Example:
>>> [Link](144)
12.0
>>> [Link](.64
0.8
2. Module name : random
This module contains functions that are used for generating random numbers.
Some of the commonly used functions in random module are discussed below.
For using this module, we can import it using the following statement:
import random
[Link](): Random Real Number (float) in the range 0.0 to 1.0.
Example:
>>> [Link]()
0.65333522
random. randint(x,y): Random integer between x and y. x, y are integers such that x <=
y. Example:
>>> [Link](3,7)
4
>>> [Link](-3,5)
1
random. randrange(y): Random integer between 0 and y. y is a positive integer signifying the stop
value.
Example:
>>> [Link](5)
4
3. Module name : statistics
This module provides functions for calculating statistics of numeric (Real-valued) data.
Some of the commonly used functions in statistics module are discussed below.
It can be included in the program by using the following statements:
import statistics
Some of the function available through statistics module:
[Link](x): x is a numeric sequence arithmetic mean
>>> statistics. mean([11,24,32,45,51])
32.6
[Link](x): x is a numeric sequence median (middle value) of x
>>>statistics. median([11,24,32,45,51])
32
[Link](x): x is a sequence mode (the most repeated value)
>>> statistics. mode([11,24,11,45,11]) 11
>>> statistics. mode(("red","blue","red"))
'red'
Unit - 2

Name of the Paper : Python


Semester : VI
Department : Computer Science
Name of the Faculty : [Link]
Designation : Assistant Professor
2. FUNCTIONS
1. Definition:
Functions are the subprograms that perform specific task. Functions are the small
modules.
2. Types of Functions:
There are three types of functions in python:
1. Library Functions (Built in functions)
2. Functions defined in modules
3. User Defined Functions
Build In Function

Types Of Functions Defined


Functions In Modules

User Defined
Functions
2.2 TYPES OF FUNCTIONS
1. Library Functions: These functions are already built in the python library.
2. Functions defined in modules: These functions defined in particular
modules. When you want to use these functions in program, you have to
import the corresponding module of that function.
3. User Defined Functions: The functions those are defined by the user are
called user defined functions.
1. Library Functions in Python: These functions are already built in the
library of python. For example: type( ), len( ), input( ), id( ), range( ) etc.
2. Functions defined in modules:
a. Functions of math module: To work with the functions of math
module, we must import math module in program.
Import Math Module

S. No. Function Description Example

1 sqrt( ) Returns the square root of a number >>>[Link](49)


Output: 7.0
2 ceil( ) Returns the upper integer >>>[Link](81.3)
Output: 82
3 floor( ) Returns the lower integer >>>[Link](81.3)
Output: 81
4 pow( ) Calculate the power of a number >>>[Link](2,3)
Output: 8.0
5 fabs( ) Returns the absolute value of a >>>[Link](-5.6)
number Output: 5.6
6 exp( ) Returns the e raised to the power >>>[Link](3)
i.e. e3 Output:
20.085536923187668
b. Function in random module:
Random module has the following functions:
a. random( ) : returns random value between 0 to 1. It doesn’t include
0 and 1
b. randint(start, stop): returns any integer number from start to stop. It
includes start and stop also.
c. randrange(start, stop) : returns a number between start and stop. It
doesn’t include start and stop value.
Example:
import random
n=[Link](3,7)
*The value of n will be 3 to 7.
c. Functions in datetime module:
It has date function. Which has three parameters named as year, month and
day.
User Defined Functions

The syntax to define a function is:

def function-name ( parameters) :

#statement(s)

Where:
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They
are optional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body. Statements
must have same indentation level.
An optional return statement to return a value from the function.
Example:
def display(name):
print("Hello " + name + " How are you?")
2.3 Function Parameters:
A functions has two types of parameters:
1. Formal Parameter
2. Actual Parameter
3. Formal Parameter:
Formal parameters are written in the function prototype and function header of the definition.
Formal parameters are local variables which are assigned values from the arguments when
the function is called.
Python supports two types of formal parameters:
i. Positional parameters
ii. Default parameters
i. Positional parameter:
These are mandatory arguments. Value must be provided to these parameters and
values should be matched with parameters.
Example:
Let a function defined as given below:
def Test(x,y,z):


Then we can call the function using these possible function calling statements:
p,q,r = 4,5,6
Test(p,q,r) # 3 variables which have values, are passed
Test(4,q,r) # 1 Literal value and 2 variables are passed
Test(4,5,6) # 3 Literal values are passed
So, x,y,z are positional parameters and the values must be provided these parameters.
ii. Default Parameters:
a. The parameters which are assigned with a value in function header while
defining the function, are known as default parameters. This values is
optional for the parameter.
b. If a user explicitly passes the value in function call, then the value which
is passed by the user, will be taken by the default parameter. If no value is
provided, then the default value will be taken by the parameter.
c. Default parameters will be written in the end of the function header,
means positional parameter cannot appear to the right side of default
parameter.
Example:
Let a function defined as given below:
def CalcSI(p, rate, time=5): # time is default parameter here
.
.
.
Then we can call the function using these possible function calling statements:
CalcSI(5000, 4.5) # Valid, the value of time parameter is not
provided, so it will take # default value, which is 5.
CalcSI(5000,4.5, 6) # Valid, Value of time will be 6

Valid/Invalid examples to define the function with default arguments:


CalcSI(p, rate=4.5, time=5): #Valid
CalcSI(p, rate=4.5, time=5): # Valid
CalcSI(p, rate=4.5, time): #Invalid, Positional argument cannot
come after default #parameter
CalcSI(p=5000, rate=4.5, time=5): #Valid
2. Actual Parameter:
When a function is called, the values that are passed in the call are called actual
parameters. At the time of the call each actual parameter is assigned to the
corresponding formal parameter in the function definition.
Example:
def ADD(x, y): #Defining a function and x and y are
formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual
parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Difference between formal parameter and
actual parameter
Formal parameter Actual parameter

Formal parameters are written in the When a function is called, the values that
function prototype and function header of are passed in the call are called actual
the definition. Formal parameters are local parameters. At the time of the call each
variables which are assigned values from actual parameter is assigned to the
the arguments when the function is called. corresponding formal parameter in the
function definition.
Example:
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
2.4 Calling the function:
Once we have defined a function, we can call it from another function, program or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
Output:
Sum = 30.0
How function works?
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
2.5 The return statement:
The return statement is used to exit a function and go back to the place from where it
was called.
There are two types of functions according to return statement:
a. Function returning some value (non-void function)
b. Function not returning any value (void function)
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
Example-2: Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple
print(S)
Output:
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately print(s1, s2, s3)
Output:
7 7 11
b. Function not returning any value (void function) :
The function that performs some operationsbut does not return any value, called
void function.
def message():
print("Hello")
m=message()
print(m)
Output:
Hello
None
2.6 Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence,
they have a local scope.
There are two types of scope for variables:
1. Local Scope
2. Global Scope
3. Local Scope:
Variable used inside the function. It can not be accessed outside the function. In
this scope, The lifetime of variables inside a function is as long as the function
executes. They are destroyed once we return from the function. Hence, a function
does not remember the value of a variable from its previous calls.
2. Global Scope:
Variable can be accessed outside the function. In this scope, Lifetime of a variable is
the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the
function my_func()changed the value of x to 10, it did not affect the value
outside the function.
This is because the variable x inside the function is different (local to the
function) from the one outside. Although they have same names, they are
two different variables with different scope.
On the other hand, variables outside of the function are visible from inside.
They have a global scope.
We can read these values from inside the function but cannot change (write)
them. In order to modify the value of variables outside the function, they
must be declared as global variables using the keyword global.

7. Passing Strings, Lists, Tuples and Dictionaries to functions:


1. Passing Strings to Function:
Example:
def StrPass(S):
for i in S:
print(i,end=‘ ‘)
string=“PythonClassXI”
StrPass(String)
Output:
PythonClassXII
2.7.2 Passing List to function:
Example:
def ListPass(L):
for i in L:
print(i)
List=[‘Physisc’, ’CS’, ’Chemistry’, ’English’, ’Maths’]
ListPass(List)
Output:
Physics
CS
Chemistry
English
Maths
Topic/Title: STRINGS

Name of the Paper : Python Programming


Semester : VI
Department : Computer Science
Name of the Faculty : G. Preetha. P. Malathi
Designation : Assistant Professor
Strings
String is a sequence which is made up of one or more UNICODE characters.
Here the character can be a letter, digit, whitespace or any other symbol.
A string can be created by enclosing one or more characters in single, double or triple
quote.

>>> str1 = 'Hello World!’


>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!‘’
str1, str2, str3, str4 are all string variables having the same value 'Hello World!’.
Values stored in str3 and str4 can be extended to multiple lines using triple codes as can
be seen in the following example:
>>> str3 = """Hello World! welcome to the world of Python""“
>>> str4 = '''Hello World! welcome to the world of Python'''
Accessing Characters in a String

Each individual character in a string can be accessed using a technique called indexing.
The index specifies the character to be accessed in the string and is written in square
brackets ([ ]).
The index of the first character (from left) in the string is 0 and the last character is n-1
where n is the length of the string.
If we give index value out of this range then we get an IndexError.
The index must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!’
#gives the first character of str1
>>> str1[0]
'H’
The index can also be an expression including variables and operators but the expression
must evaluate to an integer.
Python allows an index value to be negative also.
Negative indices are used when we want to access the characters of the string from right
to left.
An inbuilt function len() in Python returns the length of the string that is passed as
parameter.
For example,

#the length of string


str1 = 'Hello World!' is 12.
#gives the length of the string
str1 >>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n) 12
#gives the last character of the string
>>> str1[n-1] '!' #gives the first character of the string
>>> str1[-n]
'H'
String Operations
string is a sequence of characters. Python allows certain operations on string data type,
such as concatenation, repetition, membership and slicing.
Concatenation
To concatenate means to join. Python allows us to join two strings using concatenation
operator plus which is denoted by symbol +

>>> str1 = 'Hello' #First string


>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
Repetition

Python allows us to repeat the given string using repetition operator which is denoted by
symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello' #repeat the value of str1 2 times
>>> str1 * 2 'HelloHello' #repeat the value of str1 5 times
>>> str1 * 5
'HelloHelloHelloHelloHello’
Note: str1 still remains the same after the use of repetition operator

Membership

Python has two membership operators 'in' and 'not in’.


The 'in' operator takes two strings and returns True if the first string appears as a
substring in the second string, otherwise it returns False.
The 'not in' operator also takes two strings and returns True if the first string does not
appear as a substring in the second string, otherwise returns False.
Slicing

In Python, to access some part of a string or substring, we use a method called slicing.
Given a string str1, the slice operation str1[n:m] returns the part of the string str1 starting from
index n (inclusive) and ending at m (exclusive).
In other words, we can say that str1[n:m] returns all the characters starting from str1[n] till
str1[m-1].
The numbers of characters in the substring will always be equal to difference of two indices m
and n, i.e., (m-n).
>>> str1 = 'Hello World!' #gives substring starting from index 1 to 4
>>> str1[1:5]
'ello
Negative indexes can also be used for slicing.
#characters at index -6,-5,-4,-3 and -2 are
#sliced
>>> str1[-6:-1]
Traversing a String
We can access each character of a string or traverse a string using for loop and while
loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!’
>>> for ch in str1:
print(ch,end = ‘’)
Hello World! #output of for loop
In the above code, the loop starts from the first character of the string str1
and automatically ends when the last character is accessed.
(B) String Traversal Using while Loop:
>>> str1 = 'Hello World!’
>>> index = 0
#len():a function to get length of string
>>> while index < len(str1):
print(str1[index],end = ‘’)
index += 1
Hello World! #output of while loop
String Methods and Built-in Functions
Python has several built-in functions that allow us to work with strings.
len():
Returns the length of the given string
>>> str1 = 'Hello World!’
>>> len(str1)
1
title():
Returns the string with first letter of every word in the string in uppercase and rest in
lowercase
>>> str1 = 'hello WORLD!’
>>> [Link]()
'Hello World!’
lower():
Returns the string with all uppercase letters converted to lowercase
>>> str1 = 'hello WORLD!’
>>> [Link]()
'hello world!'
upper():
Returns the string with all lowercase letters converted to uppercase
>>> str1 = 'hello WORLD!’
>>> [Link]()
'HELLO WORLD!’
count(str, start, end):
Returns number of times substring str occurs in the given string. If we do not give start
index and end index then searching starts from index 0 and ends at length of the string
>>> str1 = 'Hello World! Hello Hello’
>>> [Link]('Hello',12,25)
2
find(str,start, end):
Returns the first occurrence of index of substring str occurring in the given string.
>>> str1 = 'Hello World! Hello Hello’
>>> [Link]('Hello',10,20)
13
>>> [Link]('Hello',15,25)
19
index(str, start, end):
Same as find() but raises an exception if the substring is not present in the given string
>>> str1 = 'Hello World! Hello Hello’
>>> [Link]('Hello’)
0

endswith():
Returns True if the given string ends with the supplied substring otherwise returns False
>>> str1 = 'Hello World!’
>>> [Link]('World!’)
True
isalnum():
Returns True if characters of the given string are either alphabets or numeric. If
whitespace or special symbols are part of the given string or the string is empty it returns
False
>>> str1 = 'HelloWorld’
>>> [Link]()
True
islower():
Returns True if the string is non-empty and has all lowercase alphabets, or has at least
one character as lowercase alphabet and rest are non-alphabet characters
>>> str1 = 'hello world!’
>>> [Link]()
True
>>> str1 = 'hello 1234’
>>> [Link]()
True
isupper():
Returns True if the string is non-empty and has all uppercase alphabets, or has at least
one character as uppercase character and rest are non-alphabet characters
>>> str1 = 'HELLO WORLD!’
>>> [Link]()
True
>>> str1 = 'HELLO 1234’
>>> [Link]()
True
lstrip():
Returns the string after removing the spaces only on the left of the string
lstrip() Returns the string after removing the spaces only on the left of the string
>>> str1 = ' Hello World! ‘
>>> [Link]()
'Hello World!
rstrip():
Returns the string after removing the spaces only on the right of the string
>>> str1 = ' Hello World!’
>>> [Link]()
' Hello World!’
strip():
Returns the string after removing the spaces both on the left and the right of the string
>>> str1 = ' Hello World!’
>>> [Link]()
'Hello World!'
String Constants in Python

A constant is used to define a fixed value in a variable that cannot be modified anywhere

in the code following declaration.

The Python string module contains some built-in string constants that can be used for

various purposes.

You can also define a custom string constant in Python.

The string module of python contains nine string constants.


Constant Name Value

ascii_lowercase ‘abcdefghijklmnopqrstuvwxyz’

ascii_uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’

ascii_letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz’

digits ‘0123456789’

hexdigits ‘0123456789abcdefABCDEF’

octdigits ‘01234567’

punctuation !”#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Includes the characters space, tab, linefeed, return, formfeed,


whitespace and vertical tab

printable Includes the values of digits, ascii_letters, punctuation, and whitespace


Example: Use of ascii_lowercase Constant

The following script will take any string data from the user and store it in the

variable stringVal.

The error variable is set initially to False.


If any uppercase letter exists in the stringVal variable, then the error variable will be set

to True.

After checking all characters of stringVal, if the value of error remains False, then a success

message will be printed. Otherwise, an error message will be printed.


import string
stringVal = input("Enter any text: ")
error = False
for character in stringVal:
if character not in string.ascii_lowercase:
error = True

if error == True :
# Print error message
print("All characters are not in lowercase")
else:
# Print success message
print("Text in correct format")
Use of Multiple String Constants
The following script shows use of the [Link] and [Link] constants for
the first input text and the string.ascii_lowercase and [Link] constants for
the second input.
import string
phone = input("Enter your phone number: ")
email = input("Enter your email: ")
error = False
for character in phone:
if character not in ([Link] + [Link]):
error = True
for character in email:
if character not in (string.ascii_lowercase + [Link]):
error = True
if error == True :
print("Phone number or email is invalid")
else:
Regular Expression in Python with Examples
A Regular Expressions (RegEx) is a special sequence of characters that uses a search
pattern to find a string or set of strings.
It can detect the presence or absence of a text by matching with a particular pattern, and
also can split a pattern into one or more sub-patterns.
Python provides a re module that supports the use of regex in Python. Its primary
function is to offer a search, where it takes a regular expression and a string. Here, it
either returns the first match or else none.
Example:
import re
s = 'GeeksforGeeks: A computer science portal for geeks'
match = [Link](r'portal', s)
print('Start Index:', [Link]())
print('End Index:', [Link]())
Output
Start Index: 34
End Index: 40
Meta Characters
To understand the RE analogy, Meta Characters are useful, important, and will be used
in functions of module re. Below is the list of metacharacters.

MetaCharacters Description

Used to drop the special meaning of character following


\ it

[] Represent a character class

^ Matches the beginning

$ Matches the end


\ – Backslash
The backslash (\) makes sure that the character is not treated in a special way.
This can be considered a way of escaping metacharacters.
For example, if you want to search for the dot(.) in the string then you will find that
dot(.) will be treated as a special character as is one of the metacharacters
[] – Square Brackets
Square Brackets ([]) represents a character class consisting of a set of characters
that we wish to match.
For example, the character class [abc] will match any single a, b, or c.
^ – Caret
Caret (^) symbol matches the beginning of the string i.e. checks whether the string
starts with the given character(s) or not.
For example – ^g will check if the string starts with g such as geeks, globe, girl, g,
etc.
^ge will check if the string starts with ge such as geeks, geeksforgeeks, etc.
Getting the string and the regex

[Link] attribute returns the regular expression passed and [Link] attribute
returns the string passed

Getting index of matched object

start() method returns the starting index of the matched substring


end() method returns the ending index of the matched substring
span() method returns a tuple containing the starting and the ending index of the
matched substring
Regular Expressions in Python –(Search, Match and Find All)

[Link]() : This method either returns None (if the pattern doesn’t match), or
a [Link] that contains information about the matching part of the string.

Matching a Pattern with Text


[Link]() : This function attempts to match pattern to whole string. The [Link]
function returns a match object on success, None on failure.
[Link](pattern, string, flags=0)
pattern : Regular expression to be matched.
string : String where pattern is searched
flags : We can specify different flags

using bitwise OR (|).


Finding all occurrences of a pattern
[Link]() : Return all non-overlapping matches of pattern in string, as a list of strings.
The string is scanned left-to-right, and matches are returned in the order found

import re
string = """Hello my Number is 123456789 and
my friend's number is 987654321"""
regex = '\d+'
match = [Link](regex, string)
print(match)

Output :
['123456789', '987654321']
LIST
1. Introduction to List:
The data type list is an ordered sequence which is mutable and made up of one or
more
elements. Unlike a string which consists of only characters, a list can have elements of
different
data types, such as integer, float, string, tuple or even another list. A list is very useful to
group
together elements of mixed data types. Elements of a list are enclosed in square brackets and
are separated by comma. Like string indices, list indices also start from 0.
1. Lists are Mutable
In Python, lists are mutable. It means that the contents of the list can be changed
after it has
been created.
#List list1 of colors
>>> list1 = ['Red','Green','Blue','Orange'] #change/override the fourth element of list1 >>>
list1[3] = 'Black'
>>> list1 #print the modified list list1
Output:
['Red', 'Green', 'Blue', 'Black']
2. Creating Lists
Creating lists in Python can take place by just placing the sequence inside the
square brackets[]. Furthermore, it is important to understand that a list is unlike a
set. This is because a list doesn’t require a built-in function for the creation of a list.
1. Simple Guide to Creating Lists
Below is a simple example to help understand the process of creating list in
python.
Here, the creation of two lists in Python will take place.
(1) List of Names – this list will contain strings whose placing is within
quotes:
Names = [‘Peter’, ‘Bill’, ‘Samuel’, ‘Ronald’, ‘Jack’]
(2) Age list – this list will have the involvement of numbers (i.e.,
integers) without quotes:
Age = [25, 18, 55, 30, 23]
[Link] Blank List:
[Link] Blank List:

List – []
print(“Blank List”)
print(list)
Output:
Blank List
2. Creating List of Number

List = [25, 18, 55, 30, 23]


print(“\n List of Numbers”)
print (List)
Output:
[25, 18, 55, 30, 23]

3. Creating List of String and Accessing

List = [‘Peter’, ‘Bill’, ‘Samuel’, ‘Ronald’, ‘Jack’]


3. Creating List of String and Accessing

List = [‘Peter’, ‘Bill’, ‘Samuel’, ‘Ronald’, ‘Jack’]


print(“\n List of Items”)
print (List[0])
print(List[4])

Output:

List of Items
Peter
Jack
4. Creating a Multi-Dimensional List

List = [[‘Peter', ‘Bill'] , [‘Jack']]


print("\n Multi-Dimensional List: ")
print(List)
Output:
Multi-Dimensional List
[[‘Peter', ‘Bill'] , [‘Jack']]

5. Creating a list with multiple distinct or duplicate elements


A list may contain duplicate values with their distinct positions and hence,
multiple distinct or duplicate values can be passed as a sequence at the time of list
creation.
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\n List with the use of Numbers: ")
print(List)
Output:
List with the use of Numbers
[1, 2, 4, 4, 3, 3, 3, 6, 5]
6. Creating a List with mixed type of values
List = [1, 2, ‘Peter', 4, ‘Bill', 6, ‘Jack']
print("\n List with the use of Mixed Values: ")
print(List)
Output:
[1, 2, ‘Peter', 4, ‘Bill', 6, ‘Jack']
[Link] the size of List
# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers


List2 = [10, 20, 14]
print(len(List2))

Output:
0
3

3.1.3 Initialization of a List


Initialization refers to the assignment of an initial value for a variable or data
Object. Initialization can certainly prove helpful in accessing the elements.
Example:
#initializes a list list1
>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
Example:
#initializes a list list1
>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
Output:
2
3.1.4 Accessing Elements in a List
The elements of a list are accessed in the same way as characters are
accessed in a string.

#initializes a list list1


>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
>>> list1[3] #return fourth element of list1
Output:
2
8

#return error as index is out of range


>>> list1[15]
Output:
IndexError: list index out of range
Output:
IndexError: list index out of range

#an expression resulting in an integer index


>>> list1[1+4]
>>> list1[-1] #return first element from right 12
Output:
12
#length of the list list1 is assigned to n
>>> n = len(list1)
>>> print(n)
Output:
6

#return the last element of the list1


>>> list1[n-1]
Output:
12
#return the first element of list1
>>> list1[-n]
Output:
2

2. List Operations
The data type list allows manipulation of its contents through various operations as shown
below.
1. Concatenation
Python allows us to join two or more lists using concatenation operator depicted
by the symbol +. If we want to merge two lists, then we should use an assignment statement
to assign the merged list to another list. The concatenation operator '+’ requires that the
operands should be of list type only. If we try to concatenate a list with elements of some
other data type, TypeError occurs.

Example :
>>> list1 = [1,3,5,7,9] #list1 is list of first five odd integers
>>> list2 = [2,4,6,8,10] #list2 is list of first five even integers
>>> list1 + list2 #elements of list1 followed by list2
Output:
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
Output:
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

>>> list3 = ['Red','Green','Blue']


>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
Output:
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
Output:
TypeError: can only concatenate list (not "str") to list

3.2.2 Repetition
Python allows us to replicate a list using repetition operator depicted by symbol *.
Example:
>>> list1 = ['Hello'] #elements of list1 repeated 4 times
>>> list1 * 4
Output:
['Hello', 'Hello', 'Hello', 'Hello']
3. Membership
Like strings, the membership operators in checks if the element is present in the list and
returns True, else returns False.
Example:
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
>>> 'Cyan' in list1
Output:
True
False
The not in operator returns True if the element
is not present in the list, else it returns False.
Example:
>>> list1 = ['Red','Green','Blue']
>>> 'Cyan' not in list1
>>> 'Green' not in list1
Output:
True
False
To print elements from beginning to a range use [: Index], to print elements from end-use
[:-Index], to print elements from specific Index till the end use [Index:], to print elements
within a range, use [Start Index:End Index] and to print the whole List with the use of
slicing operation, use [:]. Further, to print the whole List in reverse order, use [::-1].
Fig 1. Print elements of List from rear-end, use Negative Indexes.

Start:End with Indexes to Print Range

Slicing Here Till End

0 1 2 3 4 5 6 7 8 9 10 11 12 13
A B C D E F G H I J K L M
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Slicing Here Till Beginning


Reverse String By Using[::-1]
[: :]
Default Beginning of the Sequence Default End of Sequence
Example:
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
Output:
['Blue', 'Cyan', 'Magenta', 'Yellow']

#list1 is truncated to the end of the list


>>> list1[2:20] #second index is out of range
Output:
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']

>>> list1[7:2] #first index > second index


Output:
[] #results in an empty list

#return sublist from index 0 to 4


>>> list1[:5] #first index missing
Output:
['Red','Green','Blue','Cyan','Magenta']
#slicing with a given step size
>>> list1[0:6:2]
Output:
['Red','Blue','Magenta']

#negative indexes
>>> list1[-6:-2] #elements at index -6,-5,-4,-3 are sliced
Output:
['Green','Blue','Cyan','Magenta']

#both first and last index missing


>>> list1[::2] #step size 2 on entire list
Output:
['Red','Blue','Magenta','Black']

#negative step size


>>> list1[::-1] #whole list in the reverse order
Output:
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']
3.2.5 List Comprehension
It are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc.
A list comprehension consists of brackets containing the expression, which is executed for
each element along with the for loop to iterate over each element.

Syntax:
newList = [ expression(element) for element in oldList if condition ]

Example:
# below list contains square of all odd numbers from range 1 to 10
odd_square = []

for x in range(1, 11):


if x % 2 == 1:
odd_square.append(x**2)

print(odd_square)
Output:
[1, 9, 25, 49, 81]
3.3 List Methods and Built-in Functions
The data type list has several built-in methods that are useful in programming. Some of them
are listed in Table 9.1.
Table 9.1 Built-in functions for list manipulations

Method Description Example


len() Returns the length of the list >>> list1 = [10,20,30,40,50]
passed as the argument >>> len(list1)
Output : 5
list() Creates an empty list if no >>> list1 = list()
argument is passed Creates a list >>> list1
if a sequence is passed as an []
argument >>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
Output: ['a', 'e', 'i', 'o', 'u']
append() Appends a single element passed >>> list1 = [10,20,30,40]
as an argument at the end of the >>> [Link](50)
list >>> list1 [10, 20, 30, 40, 50]
The single element can also be a >>> list1 = [10,20,30,40]
list >>> [Link]([50,60])
>>> list1
Output: [10, 20, 30, 40, [50, 60]]
extend() Appends each element of the list >>> list1 = [10,20,30]
passed as argument to the end of >>> list2 = [40,50]
the given list >>> [Link](list2)
>>> list1
Output :[10, 20, 30, 40, 50]
insert() Inserts an element at a particular >>> list1 = [10,20,30,40,50]
index in the list >>> [Link](2,25)
>>> list1
Output:[10, 20, 25, 30, 40, 50]
count() Returns the number of times a >>> list1 = [10,20,30,10,40,10]
given element appears in the list >>> [Link](10)
Output: 3
index() Returns index of the first >>> list1 = [10,20,30,20,40,10]
occurrence of the element in the >>> [Link](20)
list. If the element is not present, Output: 1
ValueError is generated
remove() Removes the given element from >>> list1 = [10,20,30,40,50,30]
the list. If the element is present >>> [Link](30)
multiple times, only the first >>> list1 [10, 20, 40, 50, 30]
occurrence is removed. If the >>> [Link](90)
element is not present, then Output: ValueError:[Link](x):x not in list
ValueError is generated
pop() Returns the element whose index >>> list1 = [10,20,30,40,50,60]
is passed as parameter to this >>> [Link](3)
function and also removes it from Output: 40
the list. If no parameter is given, >>> list1 [10, 20, 30, 50, 60]
then it returns and removes the >>> list1 = [10,20,30,40,50,60]
last element of the list >>> [Link]()
Output: 60
reverse() Reverses the order of elements in >>>list1 = ['Tiger','Zebra','Lion', 'Cat',
the given list 'Elephant' ,'Dog']
>>> [Link]()
>>> list1
Output:['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger',
'Zebra']
sorted() It takes a list as parameter and >>> list1 = [23,45,11,67,85,56]
creates a new list consisting of >>> list2 = sorted(list1)
the same elements arranged in >>> list1
sorted order Output: [23, 45, 11, 67, 85, 56]
>>> list2
Output: [11, 23, 45, 56, 67, 85]
min() Returns minimum or smallest >>> list1 = [34,12,63,39,92,44]
element of the list >>> min(list1)
Output: 12
max() Returns maximum or largest >>> list1 = [34,12,63,39,92,44]
element of the list >>> max(list1)
Output: 92
sum() Returns sum of the elements of >>> list1 = [34,12,63,39,92,44]
the list >>> sum(list1)
Output: 284
Tuples
Introduction to Tuples:
A tuple is an ordered sequence of elements of different data types, such as integer, float,
string, list or even a tuple. Elements of a tuple are enclosed in parenthesis (round
brackets) and are separated by commas. Like list and string, elements of a tuple can be
accessed using index values, starting from 0.
Example :
#The tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1
Output: (1, 2, 3, 4, 5)

#The tuple of mixed data types


>>> tuple2 =('Economics',87,'Accountancy',89.6)
>>> tuple2
Output: ('Economics', 87, 'Accountancy', 89.6)
#The tuple with list as an element
>>> tuple3 = (10,20,30,[40,50])
>>> tuple3
Output: (10, 20, 30, [40, 50])

#The tuple with tuple as an element


>>> tuple4 = (1,2,3,4,5,(10,20))
>>> tuple4
Output: (1, 2, 3, 4, 5, (10, 20))

Accessing Elements in a Tuple :


Elements of a tuple can be accessed in the same way as a list or string using indexing and
slicing. for example
>>> a = (‘C’ , ‘ O’ , ‘M’ , ‘P’ , ‘U’ , ‘T’ , ‘E’ , ‘R’)
ELEMENTS C O M P U T E R
POSITIVE INDEX
0 1 2 3 4 5 6 7
VALUE
NEGATIVE
-8 -7 -6 -5 -4 -3 -2 -1
INDEX VALUE

Tuples in Python
>>> a[4] # Output is U (fifth element of tuple)
>>> a[-1] # Output is R (last element of tuple or first element from right)
Tuple is Immutable :
Tuple is an immutable data type. It means that the elements of a tuple cannot be
changed after it has been
created. for example :
>>> a = (‘C’ , ‘ O’ , ‘M’ , ‘P’ , ‘U’ , ‘T’ , ‘E’ , ‘R’)
>>> a[2] = ‘S’
ELEMENTS C
POSITIVE INDEX VALUE 0
NEGATIVE INDEX VALUE -8

Tuple Methods and Built-in Functions :

Method
Description Example
Name
This method returns the
>>>t1 =(10, 20, 30, 40, 50, 60, 70, 80)
length of tuple or the
len( ) >>>len(t1)
number of elements in
8
the tuple.
Tuple Methods and Built-in Functions :

Method
Description Example
Name
>>>t1 = tuple()
This function creates an >>>type(t1)
empty tuple or <class ‘tuple’>
tuple( ) creates a tuple if a
sequence is passed >>>t1 = tuple(‘python’) #string
as argument >>>t1
(‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
This function returns
>>>t1=tuple(“tuples in python”)
the frequency
count( ) >>>[Link](‘p’)
of an element in the
2
tuple.
This function returns
the index of the first >>>t1=tuple(“tuples in python”)
index( ) occurrence of the >>>[Link](‘n’)
element in the given 8
tuple.
Method
Description Example
Name
This element takes tuple
as an argument and >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
returns a sorted list. >>>sorted(t1)
sorted( ) This function does not [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
make any change in the
original tuple.
This function returns >>>t1 = (3, 8, 4, 10, 1)
min() minimum or smallest >>>min(t1)
element of the tuple. 1
>>>t1 = (3, 8, 4, 10, 1)
This function returns
>>>max(t1)
max( ) maximum or largest
10
element of the tuple.

This function returns >>>t1 = (3, 8, 4, 10, 1)


sum( ) sum of the elements of >>>sum(t1)
the tuple 26
Topic/Title: Set, Dictionary, File Handling

Name of the Paper : Python Programming


Semester : VI
Department : Computer Science
Name of the Faculty : G. Preetha
Designation : Assistant Professor
Content
• Sets
• Dictionaries
• I/O and File Handling
Set
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Tuple, and Dictionary, all with different qualities
and usage.
• A set is a collection which is unordered, unchangeable and unindexed. but
you can remove items and add new items.
Continued
Example

Output
• A set contains only unique elements but at the time of set creation, multiple
duplicate values can also be passed.
• Order of elements in a set is undefined and is unchangeable. T
• ype of elements in a set need not be the same, various mixed up data type
values can also be passed to the set.
# Creating a Set with a List of Numbers (Having duplicate values)
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])
print("\nSet with the use of Numbers: ")
print(set1)
Output
Set with the use of Numbers: {1, 2, 3, 4, 5, 6}

# Creating a Set with a mixed type of values (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)
Output
Set with the use of Mixed Values {1, 2, 4, 'Geeks', 6, 'For'}
Python program to demonstrate
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
Output
Initial blank Set: set()
# Creating a Set with the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
Output
Set with the use of String: {'e', 'r', 'k', 'o', 'G', 's', 'F'}
# Creating a Set with the use of Constructor
# (Using object to Store String)
String = 'GeeksForGeeks'
set1 = set(String)
print("\nSet with the use of an Object: " )
print(set1)
Output
Set with the use of List: {'Geeks', 'For'}
Adding Elements to a Set

• Using add() method


• Elements can be added to the Set by using built-in add() function. Only
one element at a time can be added to the set by using add() method, loops
are used to add multiple elements at a time with the use of add() method.
• Lists cannot be added to a set as elements because Lists are not hashable
whereas Tuples can be added because tuples are immutable and hence
Hashable.
# Python program to demonstrate Addition of elements in a Set- Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Adding element and tuple to the Set
[Link](8)
[Link](9)
[Link]((6,7))
print("\nSet after Addition of Three elements: ")
print(set1)
# Adding elements to the Set using Iterator
for i in range(1, 6):
[Link](i)
print("\nSet after Addition of elements from 1-5: ")
print(set1)
Initial blank Set:
set()
Set after Addition of Three elements:
{8, 9, (6, 7)}
Set after Addition of elements from 1-5:
{1, 2, 3, (6, 7), 4, 5, 8, 9}
Using update() method

• For addition of two or more elements Update() method is used. The


update() method accepts lists, strings, tuples as well as other sets as its
arguments. In all of these cases, duplicate elements are avoided.
• Program:
# Python program to demonstrate Addition of elements in a Set
# Addition of elements to the Set using Update function
set1 = set([ 4, 5, (6, 7)])
[Link]([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
• Output
Set after Addition of elements using Update: {10, 11, 4, 5, (6, 7)}
Accessing a Set

• Set items cannot be accessed by referring to an index, since sets are


unordered the items has no index. But you can loop through the set items
using a for loop, or ask if a specified value is present in a set, by using the
in keyword.
# Python program to demonstrate Accessing of elements in a set Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using for loop


print("\nElements of set: ")
for i in set1:
print(i, end=" ")

# Checking the element using in keyword


print("Geeks" in set1)
• Output
Initial set: {'Geeks', 'For'}
Elements of set: Geeks For
True
Removing elements from the Set

• Using remove() method or discard() method


– Elements can be removed from the Set by using built-in remove()
function but a KeyError arises if element doesn’t exist in the set.
To remove elements from a set without KeyError, use discard(), if
the element doesn’t exist in the set, it remains unchanged.
Python program to demonstrate 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)

# Removing elements from Set using Remove()


method [Link](5)
[Link](6)
print("\nSet after Removal of two elements:
") print(set1)
# Removing elements from Set using Discard()
method [Link](8)
[Link](9)
print("\nSet after Discarding two elements: ")
print(set1)

# Removing elements from Set using iterator method


for i in range(1, 5):
[Link](i)
print("\nSet after Removing a range of elements:
") print(set1)
Output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Set after Removal of two elements:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
Set after Discarding two elements:
{1, 2, 3, 4, 7, 10, 11, 12}
Set after Removing a range of elements:
{7, 10, 11, 12}
Using pop() method

• Pop() function can also be used to remove and return an element from the set,
but it removes only the last element of the set.
Note – If the set is unordered then there’s no such way to determine which
element is popped by using the pop() function.
# Python program to demonstrate 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)

# Removing element from the Set using the pop() method


[Link]()
print("\nSet after popping an element: ")
print(set1)
Output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Set after popping an element:
{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Using clear() method

• To remove all the elements from the set, clear() function is used.
#Creating a set
set1 = set([1,2,3,4,5])
print("\n Initial set: ")
print(set1)

# Removing all the elements from Set using clear()


method [Link]()
print("\nSet after clearing all the elements: ")
print(set1)
• Output
Initial set:
{1, 2, 3, 4, 5}
Set after clearing all the elements:
set()
Frozen sets
• In Python are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they
are applied. While elements of a set can be modified at any time, elements
of the frozen set remain the same after creation.
• If no parameters are passed, it returns an empty frozenset.
# Python program to demonstrate working of a FrozenSet Creating a
Set String = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r')
Fset1 = frozenset(String)
print("The FrozenSet is: ")
print(Fset1)

# To print Empty Frozen Set No parameter is passed


print("\nEmpty FrozenSet: ")
print(frozenset())
Python 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.
• Let us consider the following two sets for the following operations.
Function Description

add() Adds an element to a set

Removes an element from a set. If the element is not present in the


remove() set, raise a KeyError

clear() Removes all elements form a set

copy() Returns a shallow copy of a set

Removes and returns an arbitrary set element. Raise KeyError if


pop() the set is empty

update() Updates a set with the union of itself and others


union() Returns the union of sets in a new set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from set if it is a member. (Do nothing if the


discard() element is not in set)

intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Returns the symmetric difference of two sets as a new


symmetric_difference() set

Updates a set with the symmetric difference of itself


symmetric_difference_update() and another
Union: Returns a new set with elements from both the sets. >>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
Operator: |
>>> s1|s2
Method: [Link]()
{1, 2, 3, 4, 5, 6, 7, 8}

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> [Link](s2)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> [Link](s1)
{1, 2, 3, 4, 5, 6, 7, 8}
Intersection: Returns a new set containing elements common to both sets. >>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
Operator: &
>>> s1&s2
Method: [Link]()
{4, 5}
>>> s2&s1
{4, 5}

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> [Link](s2)
{4, 5}
>>> [Link](s1)
{4, 5}
Difference: Returns a set containing elements only in the first set, but not in the second set. >>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
Operator: - >>> s1-s2
Method: [Link]()
{1, 2, 3}
Difference: Returns a set containing elements only in the first >>> s2-s1
>>> s1={1,2,3,4,5}
set, but not in the second set.
{8, 6, 7}
>>> s2={4,5,6,7,8}
>>> s1-s2
Operator: -
{1, 2, 3}
Method: [Link]()
>>> s2-s1
{8, 6, 7}
>>> s1={1,2,3,4,5} >>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8} >>> s2={4,5,6,7,8}
>>> [Link](s2) >>> [Link](s2)
{1, 2, 3} {1, 2, 3}
>>> [Link](s1) >>> [Link](s1)
{8, 6, 7} {8, 6, 7}
Symmetric Difference: Returns a set consisting of elements in both sets, excluding >>> s1={1,2,3,4,5}
the common elements. >>> s2={4,5,6,7,8}
>>> s1^s2
Operator: ^
{1, 2, 3, 6, 7, 8}
Method: set.symmetric_difference()
>>> s2^s1
{1, 2, 3, 6, 7, 8}

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>>
s1.symmetric_difference(s2)
{1, 2, 3, 6, 7, 8}
>>>
s2.symmetric_difference(s1)
{1, 2, 3, 6, 7, 8}
Method Description
[Link]() Adds an element to the set. If an element is already exist
in the set, then it does not add that element.

[Link]() Removes all the elements from the set.

[Link]() Returns a shallow copy of the set.

[Link]() Returns the new set with the unique elements that are not
in the another set passed as a parameter.

set.difference_update() Updates the set on which the method is called with the
elements that are common in another set passed as an
argument.
[Link]() Removes a specific element from the set.
[Link]() Returns a new set with the elements that are common in the
given sets.

set.intersection_update() Updates the set on which the instersection_update() method is


called, with common elements among the specified sets.

[Link]() Returns true if the given sets have no common elements. Sets
are disjoint if and only if their intersection is the empty set.

[Link]() Returns true if the set (on which the issubset() is called) contains
every element of the other set passed as an argument.
[Link]() Removes and returns a random element from the set.

[Link]() Removes the specified element from the set. If the specified
element not found, raise an error.
set.symmetric_difference() Returns a new set with the distinct elements found in both the sets.

set.symmetric_difference_u Updates the set on which the instersection_update() method called,


pdate() with the elements that are common among the specified sets.

[Link]() Returns a new set with distinct elements from all the given sets.

[Link]() Updates the set by adding distinct elements from the passed one or
more iterables.
• Input :
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}

• Output :
Union : [0, 1, 2, 3, 4, 5, 6, 8]
Intersection : [2, 4]
Difference : [8, 0, 6]
Symmetric difference : [0, 1, 3, 5, 6, 8]
# sets are define
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};

# union
print("Union :", A | B)

# intersection
print("Intersection :", A & B)

# difference
print("Difference :", A - B)

# symmetric difference
print("Symmetric difference :", A ^ B)
Output:
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
Dictionaries

• The data type dictionary fall under mapping. It is a mapping between a set
of keys and a set of values.
• The key-value pair is called an item. A key is separated from its value by
a colon(:) and consecutive items are separated by commas.
• Items in dictionaries are unordered, so we may not get back the data in the
same order in which we had entered the data initially in the dictionary.
Creating a Dictionary

• To create a dictionary, the items entered are separated by commas and


enclosed in curly braces.
• Each item is a key value pair, separated through colon (:).
• The keys in the dictionary must be unique and should be of any
immutable data type, i.e., number, string or tuple.
• The values can be repeated and can be of any data type.
PYTHON

UNIT V

Name of the Paper : Python Programming


Semester : VI
Department : Computer Science
Name of the Faculty : G. Preetha
Designation : Assistant Professor
Content
• Errors and Exception
• Introduction to Object Oriented concepts in Python
Exception Handling
What is an Exception?
• Sometimes while executing a Python program, the program does not execute at all
or the program executes but generates unexpected output or behaves abnormally.

• These occur when there are syntax errors, runtime errors or logical errors in the
code.

• In Python, exceptions are errors that get triggered automatically.

• These exceptions can be forcefully triggered and handled through program code.
• Errors are the problems in a program due to which the program will stop the
execution. Exceptions are raised when some internal events occur which changes
the normal flow of the program.
Exception in Python

• In Python, exceptions are errors that get triggered automatically. These


exceptions can be forcefully triggered and handled through program
code.
• Error in Python can be of two types. That are:
– Syntax errors and
– Exceptions
Syntax Error

• Syntax errors are detected when we have not followed the rules of the
particular programming language while writing a program.
• These errors are also known as parsing errors. On encountering a syntax
error, the interpreter does not execute the program unless we rectify the
errors, save and rerun the program.

• When a syntax error is encountered while working in shell mode, Python


displays the name of the error and a small description about the error.
• As a result, the Python interpreter reports a syntax error with a brief
explanation and a recommendation for correction.
• Example:
Exceptions

• Exceptions are raised when the program is syntactically correct, but the
code resulted in an error.
• This error does not stop the execution of the program, however, it changes
the normal flow of the program. the programme does not terminate
abnormally, the programmer must handle such an exception.
• Even though a statement or expression is syntactically accurate, it
is possible that an error will occur during execution.
• For example, opening a file that does not exist, dividing by zero, and so
on. Exceptions are errors that may cause the program's usual execution
to be disrupted.
• As a result, a programmer can foresee such erroneous scenarios that
may emerge during the execution of a programme and address them by
providing appropriate code to handle the exception.
Example
Raising an Exception
• Raising an exception involves interrupting the normal flow execution of
program and jumping to that part of the program (exception handler
code) which is written to handle such exceptional situations.

• Programmers can also forcefully raise exceptions in a program using


the raise and assert statements.

• Each time an error is detected in a program, the Python interpreter raises


(throws) an exception. Exception handlers are designed to execute when
a specific exception is raised.
Example
File Edit fheII Debug
Options Window
PylJion 3.10.2 (tags/v3.10.2:a38ebcc, Jan 17 2022, 14:12:15) [MSC ›.1929
64 bit(AMD64)] on win3
Type "belp”,"copyri@t",”credits" or”license()”for more bfoxnatioa.

= RESTAItT:
C:Ysers/prabkAppDatatocaWrogralns4@oifP@on3l0/exampleraise
[Link] Tracebacl(nostrecent call last):
File "C:Ysers/prabii/AppDatatocaRrogans4@odP@on3l0/example
raise [Link]", line 4, in fmodule*
fillsfl llltlfl

ff0l’ Ill fl fl’0f


Handling exceptions

• To prevent the software or program from crashing unexpectedly, the


programmer must handle each and every exception.
• This is accomplished by adding additional code to a programme to
provide appropriate messages or directions to the user when an
exception occurs.

• Exception handling is the term for this procedure.


Need for Exception Handling

• Exception handling plays vital role in all the programming languages.


• Like C++, Java, Ruby, etc. It is useful to handle runtime errors.
• In python each exception is handled by specific exception handlers.
• Exception handlers separate the main logic of the program from the error
program and correction code. So the error will not affect the main logic
of the program.
• The compiler or interpreter keeps track of the exact position where
the error has occurred.
• Exception handling can be done for both user-defined and built-in
exceptions.
Exception Handling process
Catching Exceptions

• The exception should be caught when the error occurs in the execution.
Exception caught in try block and handled in except block.
• Some times programmer thinks as a particular code of line may
cause error. Such kind of codes will be written inside try block.
• Every try block is followed by an except block. While executing the
program, if an exception is encountered, further execution of the code
inside the try block is stopped and the control is transferred to the
except block.
• Syntax
• try:
• [program statements where exceptions might occur]
• except [exception-name]:
• [code for exception handling if the exception-name error is encountered]
Example
i 4 IDLE Shel I3.1 0.2

File Edit Shell Debup Options Window


Help
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win3 “
2
Type "help", "copyright", "credits" or "license(j" for more information.
V
V

= RESTART: C:/Users/prabh/AppData/Local/Programs/Python/Python310/[Link]
Exception handling
Enter the denominator1
20.0
Executed
Outside try except block

= RESTART: C:/Users/prabh/AppData/Local/Programs/Python/Python310/[Link]
Exception handling
Enter the denominator 0
V
V

Denomintor as zero not alloweded


Outside try except block

t
• In some programs we can extend the number of except block as we suspect more
than one type of error.
• Without specifying any error
•" - e £c I S < ee ac °'11c'i: '"' tec'"' —e a
Pytlion 3.10.2 (taas/v3. 10.2:aS8ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win3
2
Type "lielp", "copyriglit", "credits" or "license()" for more inforiiiation.

= RESTART: C:/Users/prabli/AppData/Locnl/Progi‘ams/Pytlioii/Pytlion310/[Link]
Exception handling
Enter the denoniinatorli
Only Integer values can be entered
Outside by except block

RESTART: C:/Users/prabli/AppDnta/Locnl/Pro ‘ams/Pytlioii/Pytlion310/[Link]


Exception liandlñig
Enter the denominator0
Some Error has occui‘ed
Outside try except block

You might also like