Python Programming
Python Programming
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
In the script mode, we can write a Python program in a file, save it and then use the
Python scripts are saved as files where file name has extension “.py”.
the menu.
Python Keywords
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.
•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.
String
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[].
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.
Assignment operator assigns or changes the value of the variable on its left.
>>> num1 = 2
>>> num2 = num1
>>> num2
2
Assigns valuefrom right-side >>> country = 'India’
= >>> country
operand to left side operand
'India'
Operator Description Example
not
9
and
10
Logical operators
11 or
Expressions
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
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
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
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
Explanation
If the age entered by the user is greater than 18, then print that the user is eligible to vote.
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
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
Start
Initialization
Statement
False
Statements
following the loop
Stop
Syntax of the For Loop for in
Output:
2 is an even Number
4 is an even Number
The Range() Function
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.
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
Output:
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.
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
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.
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
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
#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
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.
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,
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
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
The Python string module contains some built-in string constants that can be used for
various purposes.
ascii_lowercase ‘abcdefghijklmnopqrstuvwxyz’
ascii_uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
ascii_letters ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz’
digits ‘0123456789’
hexdigits ‘0123456789abcdefABCDEF’
octdigits ‘01234567’
punctuation !”#$%&'()*+,-./:;<=>?@[\]^_`{|}~
The following script will take any string data from the user and store it in the
variable stringVal.
to True.
After checking all characters of stringVal, if the value of error remains False, then a success
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
[Link] attribute returns the regular expression passed and [Link] attribute
returns the string passed
[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.
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
Output:
List of Items
Peter
Jack
4. Creating a Multi-Dimensional List
Output:
0
3
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]
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.
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
#negative indexes
>>> list1[-6:-2] #elements at index -6,-5,-4,-3 are sliced
Output:
['Green','Blue','Cyan','Magenta']
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 = []
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
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
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.
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
• 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)
• 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)
• 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
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
>>> 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]() 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.
[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.
[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
UNIT V
• These occur when there are syntax errors, runtime errors or logical errors in the
code.
• 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
• 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.
• 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.
= 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
• 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
= 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
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