Python
Python
01 Dated 10/12/2022
STUDY MATERIAL
Syllabus
Module 1
Introduction to python, features, IDLE, python interpreter, Writing and executing python scripts, comments,
identifiers, keywords, variables, data type, operators, operator precedence and associativity, statements, expressions,
user inputs, type function, eval function, print function
Module 2
Boolean expressions, Simple if statement, if-elif-else statement, compound boolean expressions, nesting, multi way
decisions. Loops: The while statement, range functions, the for statement, nested loops, break and continue
statements, infinite loops.
Module 3
Functions, built-in functions, mathematical functions, date time functions, random numbers, writing user defined
functions, composition of functions, parameter and arguments, default parameters, function calls, return statement,
using global variables, recursion.
Module 4
String and string operations, List- creating list, accessing, updating and deleting elements from a list, basic list
operations. Tuple- creating and accessing tuples in python, basic tuple operations. Dictionary, built in methods to
access, update and delete dictionary values. Set and basic operations on a set.
STUDY Materials (Module Wise)
MODULE 1
Introduction to Python
It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code.
Applications of Python
There are so many applications of Python, here are some of the them.
1. Web development – Web framework like Django and Flask are based on
Python. They help you write server side code which helps you manage database,
write backend programming logic etc.
2. Machine learning and AI– There are many machine learning and AI
applications written in Python.
Machine learning is a way to write specific logic so that a machine can learn
and solve a particular problem on its own.
Why Python?
There are many different ways to perform web scraping to obtain data from
websites.
FEATURES OF PYTHON
Python offers a simple, less cluttered syntax approach for developers in coding.
Python – IDLE
These are a class of applications that help you write code more efficiently.
IDLE provides a fully featured text editor to create Python scripts that
includes features like syntax highlighting, auto completion and smart indent.
It also has a debugger with stepping and breakpoints feature.
Python Indentation
Most of the programming languages like C, C++, and Java use
braces { } to define a block of code.
Python, however, uses indentation. Indentation refers to the spaces at the
beginning of a code line.
Python indentation is a way of telling a Python interpreter that the
group of statements belongs to a particular block of code.
A code block starts with indentation. The amount of indentation is up to
you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over
tabs.
Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
Python Comments
Comments can be used to explain Python code. Comments can
Creating a Comment
print("Hello Python")
Num1 = 5
Num2 = 10
Sum = a+b
Output:
We can also use the triple quotes ('''''') for multiline comment. The triple
quotes are also used to string formatting.
The docstring comment is mostly used in the module, function, class or method.
It is a documentation Python string.
"""
This is a comment
written in
"""
print("Hello, World!")
Python Identifier
a valid name.
We should not use special characters ( #, @, $, %, ! ) in identifiers.
Python keywords
Python has a set of keywords that are reserved words that cannot be used as
variable names, function names, or any other identifiers: the keywords have
a specific meaning.
Python keywords are the fundamental building blocks of any Python program.
Python keywords are special reserved words that have specific meanings and
purposes and can’t be used for anything but those specific purposes.
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
And del import return
As elif in try
Assert else is while
Async except lambda with
Await finally nonlocal yield
Break for not
If we use the keywords for any other purpose it will result in syntax error.
Python Variables
A variable is a name [identifier] associated with a value.
A variable is a symbolic name for the memory location used by the computer
program
In python there is no need to declare the type of the variable before sing them.
name=’’Aravind’’
num = 10
distance = 34.6
x = 10
x = ‘Joe’
print(x)
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Type Conversion
You can convert from one type to another with the int(), float(), and
complex() methods:
Example
x=1 # int
y = 2.8 # float
z = 1j # complex
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
There may be times when you want to specify a type on to a variable. This can be done
with casting. Python is an object-orientated language, and as such it uses classes to
define data types, including its primitive types.
x = int(1) # x will be 1 y
= int(2.8) # y will be 2 z
= int("3") # z will be 3
Random Number
Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers:
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
print('Hello')
Boolean Values
You can evaluate any expression in Python, and get one of two answers, True
or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
print(10 > 9) True
print(10 == 9) False
Python Operators
Operators are the symbols used to perform operations on operands [variables and
values].In the example below, we use the + operator to add together two values:
print(10 + 5)
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operator
Arithmetic operators
% Modulus Divides left hand operand by right hand operand and b%a=
returns remainder 0
** Exponent Performs exponential (power) calculation on a**b =10
operators to the
power 20
and
9.0//2.0
= 4.0,
-11//3
= -4,
-11.0//3
= -4.0
a = 10
b=3
print(a//b) # 3
a = -10
b = -3
print(a//b) # 3
a = 10
b = -3
print(a//b) # -4
a = -10
b=3
print(a//b) # -4
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
<> If values of two operands are not equal, then condition (a <> b)
becomes true. is true.
This is
similar to
!=
operator.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b)
value of right operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the value (a <= b)
of right operand, then condition becomes true. is true.
Python Assignment Operators
+= Add It adds right operand to the left operand and assign the c += a
AND result to left operand
is equivalent
to c = c + a
There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then
[ Show Example ]
and [Logical If both the operands are true then condition becomes true. (a and b)
AND]
is true.
not [Logical Used to reverse the logical state of its operand. Not(a
NOT] and b)
is false.
x=5
x=5
x=5
Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same
memory location:
x = ["apple", "banana"]
y=
["apple",
"banana
"] z = x
print(x is z)
print(x is y)
# returns False because x is not the same object as y, even if they
have the same content
print(x == y)
x=
["apple",
"banana
"]
print("ba
nana" in
x)
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list
a = 0011 1100
b = 0000 1101
~a = 1100 0011
MODULE 2
Boolean Expressions
The simplest Boolean expressions are False and True, the Python Boolean literals.
A Boolean variable is also a Boolean expression. An expression comparing
numeric expressions for equality or inequality is also a Boolean expression. These
comparisons are done using relational operators.
The relational operators are binary operators and are all left associative. They all
have a lower precedence than any of the arithmetic operators; therefore, the
expression x + 2 < y / 10
10 < 20 True
10 >= 20 False
e1 e2 e1 and e2 e1 or e2 not e1
False False False False True
False True False True True
True False False True False
True True True True False
Simple if Statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be
any valid logical expression which can be either evaluated to true or false.
if condition :
block
if x < 10:
y=x
if num%2 == 0:
print("Number is even")
The if-else statement
The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.
Synatx :
if condition:
#block of statements
else:
#another block of statements (else-block)
Eg:-
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
The elif
statement
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.The elif
statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
else:
print("In range")
print("Done")
We say that the second if is nested within the first if. We call the first if the outer if and the
second if the inner if. Both conditions of this nested if construct must be met for the In range
message to be printed.
else:
print("Too large")
print("Done")
Conditional Expressions
The general form of the conditional expression is : expression1 if condition
else expression2 where
Eg :- c = d if a != b else e
A conditional expression evaluates to one of two values depending on a Boolean condition.
Python Loops
The flow of the programs written in any programming language is sequential by
default.The looping simplifies the complex problems into the easy ones. It enables us to
alter the flow of the program so that instead of writing the same code again and again, we
can repeat the same code for a finite number of times.
while expression:
statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
i=1
print(i)
i=i+1
Python for loop
The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary. The for loop is also called as a per-tested loop. It is better to use for loop if
the number of iteration is known in advance.
for iterating_var in
sequence:
statement(s)
str =
"Python"
for i in str:
print(i)
range() function
The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is
given below.
Syntax:
1. range(start,stop,step size)
Output: Output:
0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10
The following examples show how range can be used to produce a variety of
sequences:
Python allows us to nest any number of while or for loops inside another loop. The inner
loop is executed n
Syntax :-
for iterating_var1 in sequence: #outer loop
#Other statements
Eg:-
rows = int(input("Enter
the rows")) for i in
range(0,rows+1):
for j in
range(i):
print(i,end =
'')
print() Output:
1
22
333
4444
55555
Break statement
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.If the break statement is inside a nested
loop (loop inside another loop), the break statement will terminate the innermost loop.
continue statement
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue
Continue
Definite Loops :_
We can inspect the code and determine the number of iterations the loop performs. This
kind of loop is known as a definite loop, since we can predict exactly how many times the
loop repeats.
Eg :-
n=1
n=1
stop =
int(input())
while n <=
stop:
print(n)
n =n+ 1
we cannot predict how many times the loop will repeat. The number of iterations depends
on the input provided by the user. However we would be able to determine the number of
iterations the while loop would perform.
Indefinite Loops :-
else:
print(entry) # If not, print it and continue
we cannot predict at any point during the loop’s execution how many
iterations the loop will perform. The value to match (999) is know before and during the
loop, but the variable entry can be anything the user enters.
Infinite Loops
An infinite loop is a loop that executes its block of statements repeatedly until the user
forces the program to quit. Once the program flow enters the loop’s body it cannot
escape.
while True:
# Do something forever. . .
The Boolean literal True is always true, so it is impossible for the loop’s condition to be
false. The only ways to exit the loop is via a break statement, return statement or a sys.exit
call embedded somewhere within its body. Any non-zero value in the while loop indicates
an always-true condition, whereas zero indicates the always- false condition. This type of
approach is useful if we want our program to run continuously in the loop without any
disturbance.
while (1):
Using functions, we can avoid rewriting the same logic/code again and again in a
program. We can call Python functions multiple times and from anywhere in a
program.
The functions can be divided in to two types – Built–in functions and User
defined functions.
1. The functions that are pre-defined in Python language are called built-in
functions.
2. The functions that are defined by the user to perform a particular task are
called User-defined functions.
BUILT-IN FUNCTIONS
Built-in functions - The built-in functions are those functions that are pre-
defined in Python. They are also called library functions. The python interpreter
has several functions that are always ready for use.
x = abs(-7.25) Result:- 7
print(x
) all()
The python all() function accepts an iterable object (such as list, dictionary, etc.).
It returns true if all items in passed iterable are true. Otherwise, it returns False. If
the iterable object is empty, the all() function returns True.
Result:Tru
e x = all(mylist)
print(x)
any()
The any() function returns True if any item in an iterable are true, otherwise it
returns False.
If the iterable object is empty, the any() function will return False.
x = any(mylist)
print(x)
bin()
The python bin() function is used to return the binary representation of a specified
integer. A result always starts with the prefix 0b.
print(x)
bool()
The bool() function returns the boolean value of a specified object. It can be true
or false. x = bool(1)
Result:- True
print(x)
complex()
The complex() function returns a complex number by specifying a real number
and an imaginary number.
print(x)
float()
The float() function converts the specified value into a floating point
help()
Executes the built-in help system. The help() method is used for interactive use.
hex()
Python hex() function is used to generate hex value of an integer argument. It
takes an integer argument and returns an integer converted into a hexadecimal
string.
print(x)
input()
The input() method reads a line from input, converts into a string and returns it.
The input() function allows user input.
int()
Python int() function is used to get an integer value. It returns an expression
converted into an integer number. If the argument is a floating-point, the
conversion truncates the number.
x = int(3.5) Result: 3
print(x)
len()
The len() function returns the number of items in an object.
When the object is a string, the len() function returns the number of characters in
the string.
x = len(mylist)
min()
Python min() function is used to get the smallest element from the collection.
This function returns the smallest element from the collection.
print(x)
max()
The Python max() function returns the largest item in an iterable. It can also be
used to find the largest item between two or more parameters.
print(x)
next()
Python next() function is used to fetch next item from the collection.
mylist = iter(["apple", "banana",
"cherry"]) x = next(mylist)
print(x)
x=
next(mylist
) print(x)
oct()
The oct() function takes an integer number and returns its octal representation.
Python oct() function is used to get an octal value of an integer number. This
method takes an argument and returns an integer converted into an octal string.
x = pow(4, 3) Result: 64
print(x)
print()
The python print() function prints the given object to the screen or other
standard output devices.
The message can be a string, or any other object, the object will be converted
into a string before written to the screen.
print("Hello World")
x=7
print("x =", x)
reversed()
The reversed() function returns the reversed iterator of the given
ralph = reversed(alph)
for x in ralph:
print(x)
round()
The round() function returns a floating point number that is a rounded version
of the specified number, with the specified number of decimals.The default
number of decimals is 0, meaning that the function will return the nearest
integer
x = round(5.76543, 2) Result:
5.77 print(x)
sorted()
The sorted() function sorts the elements of a given iterable in a specific order
(either ascending or descending) and returns the sorted iterable as a list. You
can specify ascending or descending order. Strings are sorted alphabetically,
and numbers are sorted numerically.
a = ("b", "g", "a", "d", "f", "c", "h", "e") Result: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
x=
sorted(a)
print(x)
sum()
x=
sum(a)
print(x)
type()
The python type() returns the type of the specified object if a single argument is
passed to the type() built in function.
x = type(a) y =
type(b) print(x)
print(y)
MATH FUNCTIONS
The math module is used to access mathematical functions in the Python. All
methods of these functions are used for integer or real type objects, not for
complex numbers.
To use this module, we should import that module into our code. Python has a
built-in module that you can use for mathematical tasks. The math module has a
set of methods and constants.
Method Description
Math Constants
Constant Description
math.e Returns Euler's number (2.7182...)
Example Code
Output:
PYTHON: MODULE 3 S.A
RANDOM FUNCTIONS
Python has a built-in module that you can use to make random
Method Description
choices() Returns a list with a random selection from the given sequence
DATETIME FUNCTIONS
The module named datetime can be imported to work with the date as well as
time. Datetime module supplies classes to work with date and time. These
classes provide a number of functions to deal with dates, times and time
intervals. Datetime module comes built into Python, so there is no need to
install it externally.
import datetime
Time Module
There is a popular time module available in Python which provides functions
for working with times. The function time.time returns the current system time
in ticks since 12:00am,
ticks = time.time()
ticks) struct_time
structure
import time
print (time.gmtime(2244556))
ti =
time.gmtime()
print
(time.asctime(ti))
print (time.ctime(sec))
sleep(sec) :- This method is used to hault the program execution for the time
specified in the arguments.
import time
(time.ctime(234556))
time.sleep(100)
print (time.ctime())
Calendar Function
The calendar module supplies calendar-related functions, including functions to
print a text calendar for a given month or year. By default, calendar takes
Monday as the first day of the week and Sunday as the last one.
firstweekday() :- This function returns the first week day number. By default 0
(Monday).
import calendar
(calendar.calendar(2019,2,1,6)
(calendar.firstweekday())
isleap (2020) :- This function checks if year mentioned in argument is
if (calendar.isleap(2008)): print
prcal(year, w, l, c) :- This function also prints the calendar of specific year but
there is no need of “print” operation to execute this.
calendar.prcal(1997, 2,1,6)
month (year, month, w, l) :- This function prints the month of a specific year
mentioned in arguments. It takes 4 arguments, year, month, width of characters
and no. of lines taken by a week.
import calendar
cal =
calendar.month(2020,9,2,1)
print cal
Datetime functions
date : It allows us to manipulate date without interfering time (month, day, year)
time : It allows us to manipulate date without interfering date (hour, minute, second,
microsecond)
tzinfo : An abstract class for dealing with time zones. These types of objects are
immutable. For instance, to account for different time zones and/or daylight
saving times.
timedelta : It is the difference between two date, time or datetime instances;
08:22:39.776866 x= datetime.datetime.now()
print(x)
PYTHON: MODULE 3 S.A
x = datetime.datetime(2020,
5, 17) print(x)
x = datetime.datetime(2018,
6, 1)
print(x.strftime("%B"))
strftime()
The datetime object has a method for formatting date objects into readable
strings. The method is called strftime(), it takes one parameter, format, to
specify the format of the returned string:
import datetime
x=
datetime.datetime.now
() print(x.year)
print(x.strftime("%A")
output
2020
Wednesday
PYTHON: MODULE 3 S.A
date_object =
datetime.date.today()
print(date_object)
datetime.date() - Return date object with same year, month and day.
Functions help to break our program into smaller and modular chunks. As our
program grows larger, functions make it more organized and manageable.
Defining a Function
Here are the simple rules to define a function in Python.
● Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
● Any input parameters or arguments should be placed within these parentheses.
● The first statement of a function can be an optional statement - the
PYTHON: MODULE 3 S.A
def function_name(
parameters ):
“””function_docstring”””
function_block
return (expression)
called.
my_function(“Aravind",
“Varma")
Keyword arguments are the arguments in which the arguments are send with the key =
value syntax. Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters.
child3) return
PYTHON: MODULE 3 S.A
def my_function(country =
country)
return
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Variable length arguments : You may need to process a function for more
arguments than you specified while defining the function. These arguments are
called variable- length arguments and are not named in the function definition If
number of arguments that will be passed into your function is unknown in the
begining, add a * before the parameter name in the function definition. This way
the function will receive a tuple of arguments, and can access the items
accordingly: Arbitrary Arguments are often shortened to *args in Python
documentations.
def my_function(*kids):
FUNCTION CALL
Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt. A function is called
by its name.
def student(name):
To summarize the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.
Immutable Objects: These are of in-built types like int, float, bool, string, tuple.
In simple words, an immutable object can’t be changed after it is created.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Example 2
output
Example 1
# call by value string = "Python" def test(string):
string = "Python
Programming"
print("Inside
Function:", string)
test(string)
Output
Example 2:
Function", list)
mylist =
[10,20,30,40]
add_more(mylist)
RETURN VALUES
To let a function return a value, use the return statement: The return
statement is used at the end of the function and returns the result of the
function. It terminates the function execution and transfers the result where
the function is called. The return statement cannot be used outside of the
function.
def
my_function(x):
return 5 * x
print(my_functio
n(3))
print(my_functio
n(5))
print(my_functio
n(9))
output
15
25
45
SCOPE OF VARIABLES
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access
a particular identifier. There are two basic scopes of variables in Python −
● Global variables
● Local variables
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed
throughout the program body by all functions. Global variables can be used
by everyone, both inside of functions and outside.
The lifetime of a variable is the period throughout which the variable exits in
the memory. The lifetime of variables inside a function is as long as the
function executes.
y = 20
def my_func():
x = 10
print("Value inside
function:",x) return
my_func()
Output
Value inside
function: 10 Value
outside function:
20
The variable defined outside any function is known to have a global scope,
whereas the variable defined inside a function is known to have a local
scope.
To create a global variable inside a function, you can use the global keyword.
global x
x = "fantastic"
myfunc()
print("Python
is " + x)
def
multip
ly(x):
return
x*2
RECURSION
Python also accepts function recursion, which means a defined function can call
termination condition.
Every time a function gets called, Python creates a new function frame,
which contains the function’s local variables and parameters. For a recursive
function, there might be more than one frame on the stack at the same time.
Advantages of recursion
● Easier to write.
● Readable – Code is easier to read and understand.
● Reduce the lines of code – It takes less lines of code to solve a problem using recursion.
Disadvantages of recursion
● If you don’t define the base case then the code would run
indefinitely.
● Debugging is difficult in recursive functions as the function is calling
itself in a loop and it is hard to
understand which call is causing the issue.
● Memory overhead – Call to the recursive function is not memory efficient.
MODULE 4
STRINGS IN PYTHON
Computers do not deal with characters; they deal with numbers (binary data).
Even though characters are visible on the screen, internally it is stored and
manipulated as a combination of 0s and 1s. This conversion of character to a
number is called encoding, and the reverse process of converting numbers to
character is called decoding. ASCII and Unicode are some of the popular
encodings techniques used.
print(my_string) Output
Hello Hello
Even triple quotes can be used in Python but generally used to represent multiline
strings and docstrings.
the world of
Python"""
print(my_string)
However, Python does not have a character data type, a single character is simply a
string with a length of 1.
ACCESSING STRING
Square brackets can be used to access elements of the string. In Python an entire
string can be accessed using its name and individual characters in a string can
be accessed using indexing. (First character has the position zero).
print(str)
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
Here, we must notice that the upper range given in the slice operator is always
exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1]
= 'E', str[2] = 'L' and nothing else.
# Given String
str = "COMPUTER"
MP COM
STRING SPECIAL OPERATORS
Assume string variable a holds 'Hello' and variable b holds 'Python', then –
print(x)
Output : True
Output : True
STRING METHODS
Python has a set of built-in methods that you can be used on strings. All string
methods return new values. They do not change the original string. The string
methods are written in the format:
stringname.capitalize()
Hello python
hello python
stringname.center(length)
Hello
x = txt.count("apple")
stringname.count(value) print(x)
2
encode() Returns an encoded version of the
string. txt = "My name is Ståle"
x = txt.encode()
print(x)
stringname.encode(coding)
stringname.endswith(value)
True
Hello
find() Searches the string for a specified value mystring = "Python"
and returns the position of where it was print(mystring.find("P"))
found. The find() method returns -1 if
the value is not found.
stringname.find(value,start,end)
0
start and end parameters are optional. It
specifies where to start and end the
search.
stringname.index(value,start,stop)
isalnum() Returns True if all characters in the string are mystr = "HelloPython"
alphanumeric(alphabet or numeric). print(mystr.isalnum())
stringname.isalnum()
True
stringname.isalpha()
False
isdecimal() Returns True if all characters in the string are mystr = "HelloPython"
print(mystr.isdecimal())
decimals.
stringname.isdecimal()
False
stringname.isdigit()
True
identifier. c="_user_123"
print(c.isidentifier())
True
stringname.isidentifier()
stringname.islower()
False
stringname.isnumeric()
True
stringname.isprintable()
False
c="133"
print(c.isprintable())
True
stringname.isspace()
x = txt.isupper ()
stringname.isupper()
print(x)
True
join() The join() method takes all items in an myTuple = ("John", "Peter")
print(x)
John#Peter
stringname.join(iterable)
python
x = txt.partition("is")
print(x)
specified string.
stringname.partition(value)
stringname.replace(oldvalue,newvalue)
Bye Python
rfind() Searches string for a specified value and mystr = "Hello Python"
returns the last position of where it was
>>> print(mystr.rfind("o"))
found. The rfind() method returns -1 if
the value is not found.
stringname.rfind(value) 10
rindex() Searches the string for a specified value mystr = "HelloPython"
and returns the last position of where it >>> print(mystr.rindex("o"))
was found.
stringname.rindex(value) 10
string.
string.rjust(length)
stringname.rpartition(value)
stringname.rsplit()
stringname.rstrip()
print(x)
stringname.split(seperator)
stringname.startswith(value)
False
print(mystr.startswith("H"))
True
title() Converts the first character of each word mystr = "HELLO JAVA"
to upper case. print(mystr.title())
stringname.title()
Hello Java
upper() Converts a string into upper case. mystr = "hello Python"
print(mystr.upper())
stringname.upper()
HELLO PYTHON
x = txt.zfill(10)
stringname.zfill()
print(x)
0000000050
ESCAPE CHARACTERS
Backslash Description
notation
\a Bell or alert
\b Backspace
\n Newline
\s Space
\t Tab
\v Vertical tab
\’ Single quotes
One of Python's features is the string format operator %. . String and Unicode
objects have one unique built-in operation: the % operator (modulo). This is
also known as the string formatting or interpolation operator.
Format Conversion
Symbol
%c Character
%o octal integer
PYTHON COLLECTIONS
There are four collection (array) data types in the Python programming language:
The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the
second index is one, and so forth.
LIST
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets. List is a linear data structure, i.e. the elements are
arranged in a linear order. Each element is identified by its index value.
Normally indexing starts from zero and is known as zero indexing.
CREATING A LIST
L2 = [1, 2, 3, 4, 5]
L4 =
[“c”,”cpp”,”java”]
L5 = []
Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not a
string.
l1 = [1,2,3,4,5]
len(l1) 5
print x
ACCESSING LIST ITEMS
List items can be accessed by referring to the index number: Index number is
also termed as subscript. The action of moving through a list visiting each
element exactly once is known as traversal.
print(thislist[2])
Negative Indexing
print(thislist[-1])
Output will be -
JAVA
To print the whole list using slicing use the format – [:]
When specifying a range, the return value will be a new list with the
specified items.
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0. leaving out the start value, the range will
print(thislist[:4]).By leaving out the end value, the range will go on to the end of the
Specify negative indexes if you want to start the search from the end of the list:
Example
"ANDROID"]
print(thislist[-4:-1])
CHANGE ITEM VALUE
thislist[1] =
"CPP"
print(thislist)
In this case the item in the index position 1 (PYTHON) will be changed to “CPP”
Output
for x in
thislist:
print(x)
Output will be
PYTH
ON
JAVA
if "C" in thislist:
print("Yes, 'C' is in the thislist list")
LIST LENGTH
To determine how many items a list has, use the len() function:
append() method
To add an item to the end of the list, use the append() method: The append() adds
element to the end of the list.
thislist.append("CPP")
print(thislist)
Output
insert() method
To add an item at the specified index, use the insert() method. The insert()
method inserts value at the specified position given. insert() has two parameter
values. The position in which the value should be inserted and the value to be
inserted in the list.
list.insert(position,value)
Example
Output
extend() method
The extend() method adds specified list of elements to the end of current list. Or
you can use the extend() method, to add elements from one list to another list
"PHP"] newlist=
["PYTHON", "R"]
thislist.extend(newlist)
print(thislist)
Output
remove() method
The remove method removes the first occurrence of the specified
element. list.remove(element)
Here list is the list name and parameter is the item to be removed from
thislist.remove("PYTHON
") print(thislist)
Output
['C', 'JAVA']
pop() method
list.pop(position)
The pop() method removes the specified index, or the last item, if index is not
specified from the list.
thislist.pop() print(thislist)
Output
'C', 'PYTHON'
del keyword
The del keyword removes the specified index.
Output
'PYTHON', 'JAVA'
del thislist
clear() method
The clear() method empties the list. All elements in the list will be deleted.
thislist = ["C", "PYTHON", "JAVA"]
thislist.clear() print(thislist)
COPY A LIST
You cannot copy a list simply by typing list2 = list1, because list2 will only be a
reference to list1, and changes made in list1 will also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
mylist =
thislist.copy()
print(mylist)
"JAVA"]
REVERSE A LIST
e()
print(fruits)
Output
ELEMENT COUNT
The count() method returns the number of elements with the specified value.
x = lists.count("c")
print(x)
Output 2
Here the method count() counts the number of times the specified value occurs
in the list.
SORTING A LIST
cars.sort() print(cars)
Output
print(list3)
Another way to join two lists is by appending all the items from list2 into list1,
one by one:
list1.append(x)
print(list1)
Example
brackets print(thislist)
A new list name thislist is created here.
1 cmp(list1, list2).
This function returns 1, if first list is “greater” than second list, -1 if first list is
smaller than the second list else it returns 0 if both the lists are equal.
2 len(list)
Examples:
cmp()
stock_price_1 = [50.23]
stock_price_1))
When you run the above code, it produces the following result:
-1
len()
max()
min()
list() method.
CREATING A TUPLE
Example 1:
tup2 = (1, 2, 3, 4, 5 )
nothing − tup1 = ()
To write a tuple containing a single value include a comma, even though there is
Tuple items can be accessed by referring to the index number, inside square
brackets:
print(thistuple[1])
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item,-2
refers to the second last item etc.
print(thistuple[-2])
Range of Indexes
Range of indexes can be accessed by specifying where to start and where to end
the range.
When specifying a range, the return value will be a new tuple with the specified
items.
print(thistuple[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Negative indexes are used to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
print(thistuple[-4:-1])
We can access a range of items in a tuple by using the slicing operator colon :.
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:])
Output
('r', 'o', 'g')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too. The result of the operation will be a new
tuple. In fact, tuples respond to all of the general sequence operations we used
on strings in the prior chapter −
Once a tuple is created, its values cannot be changed. Tuples are unchangeable,
or immutable.
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Output
if "apple" in thistuple:
To determine how many items a tuple has, use the len() method:
print(len(T1)) Output
Once a tuple is created, new items cannot be added to it. Tuples are unchangeable.
REMOVE ITEMS
Tuples are unchangeable, so items cannot be removed from it, but the tuple can be
deleted completely.
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
JOIN TWO TUPLES
tuple2 = (1, 2, 3)
tuple3 = tuple1 +
tuple2 print(tuple3)
METHODS IN TUPLE
count()
x=
thistuple.count(5)
print(x)
Output
The count() method returns the number of times a specified value appears in the
tuple.
index()
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5,1)
x = thistuple.index(8) print(x)
Output
The index() method finds the first occurrence of the specified value.
To reverse the order of elements in the tuple, Python has an inbuilt function
tuple_name.reverse( ), which reverses the order of appearance of elements in the
tuple.
tup = (2,4,6,8)
1 cmp(tuple1, tuple2)
cmp() function
This is used to compare two tuples. It will return 1, 0 or -1, depending upon
whether the two tuples being compared are similar or not.
The cmp() function takes two tuples as arguments, where both of them are
compared. If T1 is the first tuple and T2 is the second tuple, then:
returns -1 Syntax
− cmp(tuple1, tuple2)
max() function
Python tuple method max() returns the elements from the tuple with maximum
value.
max(tuple)
This method returns the elements from the tuple with maximum value.
Example
The following example shows the usage of max() method. tuple1, tuple2 =
: ", max(tuple2)
min() function
Python tuple method min() returns the elements from the tuple with minimum
value.
min(tuple)
● tuple − This is a tuple from which minimum valued element to be
returned.
This method returns the elements from the tuple with minimum
tuple()
tuple(aList)
print (aTuple)
sorted()
The sorted() function returns a sorted list of the specified iterable object.
x=
sorted(a)
print(x)
Output
Output
Dict = {}
An empty dictionary without any items is written with just two curly braces,
like this: {}.
ACCESSING ITEMS
Items in the dictionary can be accessed by referring to its key name, inside square
brackets:
There is also a method called get() that will give the same result:
x = thisdict.get("name") y = thisdict.get(“age”)
CHANGE VALUES
The value of a specific item can be changed by referring to its key name:
Output
for x in thisdict:
print(thisdict[x]
)
Outp
ut
Ford
Must
ang
1964
Loop through both keys and values, by using the items() method:
Output
brand
Ford
model
Mustang
year 1964
Example
DICTIONARY LENGTH
print(len(thisdict
)) len(thisdict)
1964} print(len(thisdict))
Output
ADDING ITEMS
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
Example
thisdict["color"] = "red"
thisdict[“place”]=” India”
print(thisdict)
REMOVING ITEMS
The pop() method removes the item with the specified key name:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.pop("model")
print(thisdict)
Output
thisdict.popite
m()
print(thisdict)
Output
In this case the dictionary item year will be deleted. It is the last inserted item.
The del keyword removes the item with the specified key name:
Output
del thisdict
thisdict.clear() print(thisdict)
COPY A DICTIONARY
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
print(mydict)
mydict =
dict(thisdict)
print(mydict)
NESTED DICTIONARIES
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Create three dictionaries, and then create one dictionary that will contain the other
three dictionaries:
child1 = {
child2 = {
child3 = {
DICTIONARY METHODS
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
SET
A set is a data collection which is unordered and unindexed. In Python, sets are
written with curly brackets. Every set element is unique (no duplicates) and
must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
CREATE A SET:
print(thisset)
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
print(Days)
Note: Sets are unordered, so you cannot be sure in which order the items will
appear.
To make a set without any elements, we use the set() function without any
argument.
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
print(type(a))
Output
<class 'dict'>
<class 'set'>
But set items can be traversed using a for loop. Here in keyword is used to
check if a specified value is present in a set.
Loop through the set, and print the values:
for x in thisset:
print(x)
CHANGE ITEMS
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method. To add more than one item to a
set use the update() method.
Example
thisset.add("JAVA") print(thisset)
Example
thisset.update(["JAVA", "PHP",
"RUBY"]) print(thisset)
{'C', 'PYTHON', 'CPP', 'JAVA', 'PHP', 'RUBY'}
To determine how many items a set has, use the len() method.
Example
x= len(thisset) print(x)
Output 3
Example
thisset.remove("banana") print(thisset)
Output
{'cherry', 'apple'}
Note: If the item to remove does not exist, remove() will raise an error.
Example
Output
{'cherry', 'apple'}
Note: If the item to remove does not exist, discard() will NOT raise an error.
The pop() method is also used to remove an item from set. The sets are
unordered, so the user won’t know which item gets removed.
pop()
Output
apple
{'cherry', 'banana'}
clear()
Example
print(thisset)
subject = set((“C”,”PYTHON”,”MATHS”))
subject = {“c”,”cpp”,”python”}
subject = set([“c”,”cpp”.python”])
The union() method is a set joining method that returns a new set containing all
items from both sets. The update() method is another join method that inserts all
the items from one set into another.( | pipe operator)
Example
The union() method returns a new set with all items from both sets:
Output
set1 = {5, 4, 7}
set2 = {1, 2, 3}
set1.update(set2) print(set1)
{1, 2, 3, 4, 5, 7}
Note: Both union() and update() will exclude any duplicate items.
Set Intersection
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the
intersection() method.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A &
B) Output
{4, 5}
● intersection(B)
{4, 5}
● intersection(A)
{4, 5}
Set Difference
Difference of the set B from set A (A - B) is a set of elements that are only in A
but not in B. Similarly, B - A is a set of elements in B but not in A.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
Output
{1, 2, 3}
difference(B)
{1, 2, 3}
difference(A)
{8, 6, 7}
The difference_update() method removes the items that exist in both sets.
x.difference_update(y)
print(x) Output
{'banana', 'cherry'}
The intersection_update() method removes the items that is not present in both
sets (or in all sets if the comparison is done between more than two sets).
The intersection_update() method is different from the intersection() method,
because the intersection() method returns a new set, without the unwanted
items, and the intersection_update() method removes the unwanted items from
the original set.
x.intersection_update(y)
print(x)
Output
{'apple'}
The isdisjoint() method returns True if none of the items are present in both
sets, otherwise it returns False.
y = {"google", "microsoft",
"facebook"} z = x.isdisjoint(y)
The issubset() method returns True if all items in the set exists in the specified
set, otherwise it returns False.
x = {"a", "b", "c"}
z = x.issubset(y) print(z)
Output True
The issuperset() method returns True if all items in the specified set exists in the
original set, otherwise it returns False. (If x contains all the elements in y).
z = x.issuperset(y) print(z)
Output True
The symmetric_difference() method returns a set that contains all items from
both set, but not the items that are present in both sets.
Meaning: The returned set contains a mix of items that are not present in both
sets. The symmetric difference of two sets is calculated by ^
operator or symmetric_difference() method.
y = {"google", "microsoft",
"apple"} z =
x.symmetric_difference(y) Output
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
Python allows to use the comparison operators i.e., <, >, <=, >= , == with the
sets by using which we can check whether a set is a subset, superset, or
equivalent to other set. The Boolean value, true or false is returned depending
upon the items present inside the sets.
print (Days1>Days2)
print (Days1<Days2)
Output:
True False True
Built-infunctions like all(), any(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks