Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

Python

The document provides a study material for a 3rd semester Python Programming course. It includes 4 modules covering topics like introduction to Python, Boolean expressions, loops, functions, strings, lists, tuples, dictionaries and sets. Example code and explanations are given for key concepts like Python syntax, indentation, comments, identifiers and more.

Uploaded by

subisubish67
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python

The document provides a study material for a 3rd semester Python Programming course. It includes 4 modules covering topics like introduction to Python, Boolean expressions, loops, functions, strings, lists, tuples, dictionaries and sets. Example code and explanations are given for key concepts like Python syntax, indentation, comments, identifiers and more.

Uploaded by

subisubish67
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

Rev.

01 Dated 10/12/2022

NETHAJI MEMORIAL ARTS AND SCIENCE COLLEGE, NEMMARA

DEPARTMENT OF COMPUTER SCIENCE

STUDY MATERIAL

Class & Year of Admission 2022-2025

Course with Code ELE3A11 Python Programming

Semester 3rd semester

Hours per week 4


Credits 4

Prepared By (Name of S.Ranjini


faculty)

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

Python is a widely used general-purpose, high level programming


language. It was created by Guido van Rossum in 1991 at the National Institute
for Mathematics and Computer Science in Netherlands and further developed
by the Python Software Foundation.

It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code.

Version 1.0 in 1994

Python 3.9.7 - Release Date: Aug. 30, 2021

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.

For example, products recommendation in websites like Amazon, Flipkart,


eBay etc. is a machine learning algorithm that recognises user’s interest. Face
recognition and Voice recognition in your phone is another example of machine
learning.

3. Data Analysis[Big data Applications] – Data analysis and data


visualisation in form of charts can also be developed using Python.
4. Scripting – Scripting is writing small programs to automate simple tasks
such as sending automated response emails etc. Such type of applications can
also be written in Python programming language.
5. Game development – In addition to research and business applications,
Python has a critical role in backend game development with logic and mods.

● Desktop applications –Python language can be used to develop


desktop applications.

Why Python?

Python works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.

Web scraping is an automatic method to obtain large amounts of data from


websites.

Most of this data is unstructured data in an HTML format which is then


converted into structured data in a spread sheet or a database so that it can be
used in various applications.

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.

The major features of Python are –

o Easy to Read, Learn and Code


o Free and Open-Source
o Vast Libraries Support
o High Level Language
o Python is interpreted Programming language
o Highly Portable
o Robust

Python – IDLE

IDLE (Integrated Development and Learning Environment) is an integrated


development environment (IDE) for Python. The Python installer for Windows
contains the IDLE module by default.

These are a class of applications that help you write code more efficiently.

IDLE has the following features:

coded in 100% pure Python, using the tkinter GUI toolkit


cross-platform: works mostly the same on Windows, Unix, and
macOS
Python shell window (interactive interpreter) with colorizing of code
input, output, and error messages
multi-window text editor with multiple undo, Python colorizing, smart
indent, call tips, auto completion, and other features
search within any window and search through multiple files
Debugger with persistent breakpoints, stepping, and viewing of global
and local namespaces

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

The enforcement of indentation in Python makes the code look neat


and clean.
This results in Python programs that look similar and consistent.
Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.

Python Comments
Comments can be used to explain Python code. Comments can

be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python interpreter will ignore them:

# This is the print statement

print("Hello Python")

Multiline Python Comment


We must use the hash(#) at the beginning of every line of code to apply the
multiline Python comment. Consider the following example.
Example:

# Variable a holds value 5 #


Variable b holds value 10

# Variable c holds sum of a and b #


Print the result

Num1 = 5

Num2 = 10

Sum = a+b

print("The sum is:", Sum)

Output:

The sum is: 15

We can also use the triple quotes ('''''') for multiline comment. The triple
quotes are also used to string formatting.

Docstrings Python Comment

The docstring comment is mostly used in the module, function, class or method.
It is a documentation Python string.

1) Single Line Comment: In case user wants to specify a single line


comment, then comment must start with #
2) Multi Line Comment: Multi lined comment can be given inside triple
quotes

"""

This is a comment

written in

more than just one line

"""
print("Hello, World!")

Python Identifier

“An identifier is a name given to an entity”.

In very simple words, an identifier is a user-defined name to represent the


basic building blocks of Python. It is used to name a variable,

a function, a class, a module, or any other object.

It helps to differentiate one entity from another.

The identifier is a combination of character digits and underscore.


The identifier should start with a character or Underscore then use a
digit.
The characters are A-Z or a-z, an UnderScore ( _ ) , and digit (0-9).

like myClass, var_1 and print_this_to_screen, all are valid example.

2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is

a valid name.
We should not use special characters ( #, @, $, %, ! ) in identifiers.

3. Keywords cannot be used as identifiers.

● We cannot use special symbols like !, @, #, $, % etc. in our identifier.


● An identifier can be of any length.

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.

1. Python is a case-sensitive language. This

means, Variable and variable are not the same.

2. Always give the identifiers a name that makes sense. While c =

10 is a valid name, writing count = 10 would make more sense,

and it would be easier to figure out what it represents when you


look at your code after a long gap.

3. Multiple words can be separated using an underscore,

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)

A variable name must start with a letter or the underscore


character
A variable name cannot start with a number
A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )

Variable names are case-sensitive (age, Age and AGE are


three different variables)
Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"

print(x)

print(y)

print(z)

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

Example

x = y = z = "Orange"
print(x)

print(y)
print(z)

Built-in Data Types

In programming, data type is an important concept.

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:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range


Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

Type Conversion

You can convert from one type to another with the int(), float(), and
complex() methods:

Example

Convert from one type to another: [complex is not converted to another]

x=1 # int

y = 2.8 # float

z = 1j # complex

#convert from int to float: a


= float(x)

#convert from float to int: b


= int(y)
#convert from int to complex:

c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Specify a Variable Type

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.

'hello' is the same as "hello".

You can display a string literal with the print() function:


print("Hello")

print('Hello')

Boolean Values

In programming you often need to know if an expression is True or False.

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

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)

Python divides the operators in the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operator

Arithmetic operators

Operator Description Example

+ Addition Adds values on either side of the operator. a+b=


30

- Subtraction Subtracts right hand operand from left hand a–b=-


operand. 10

* Multiplies values on either side of the operator a *b =


Multiplication 200

/ Division Divides left hand operand by right hand operand b/a=2

% 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

// Floor Division - 9//2 = 4

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

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then − [


Show Example ]

Operator Description Example

== If the values of two operands are equal, then the (a == b)


condition becomes true. is not
true.

!= If values of two operands are not equal, then condition (a != b)


becomes true. is true.

<> 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

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

= Assigns values from right side operands to left side c=a+b


operand assigns value
of a + b into c

+= 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

-= Subtract It subtracts right operand from the left operand and c -= a


AND assign the result to left operand
is equivalent
to c = c - a

*= Multiply It multiplies right operand with the left operand and c *= a


AND assign the result to left operand
is equivalent
to c = c * a

/= Divide It divides left operand with the right operand and c /= a


AND assign the result to left operand
is equivalent
to c = c / a

%= It takes modulus using two operands and assign the c %= a


result to left operand
is equivalent
Modulus
AND to c = c % a

**= Performs exponential (power) calculation on c **= a


Exponent operators and assign value to the left operand
AND is equivalent
to c = c ** a

//= Floor It performs floor division on operators and assign c //= a


Division value to the left operand
is equivalent
to c = c // a

Python Logical Operators

There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then

[ Show Example ]

Operator Description Example

and [Logical If both the operands are true then condition becomes true. (a and b)
AND]
is true.

or [Logical If any of the two operands are non-zero then condition (a or b)


OR] becomes true.
is true.

not [Logical Used to reverse the logical state of its operand. Not(a
NOT] and b)

is false.
x=5

print(x > 3 and x < 10)

x=5

print(x > 3 or x < 4)

x=5

print(not(x > 3 and x < 10))

Python Identity Operators

Identity operators compare the memory locations of two objects.

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:

Operator Description Example

is Returns True if both variables are x is y


the same object

is not Returns True if both variables are not x is not y


the same object

x = ["apple", "banana"]

y=
["apple",
"banana
"] z = x

print(x is z)

# returns True because z is the same object as x

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)

# to demonstrate the difference between "is" and "==": this


comparison returns True because x is equal to y

Python Membership Operators

Membership operators are used to test if a sequence is presented in


an object:

Operator Description Example

in Returns True if a sequence with x in y


the specified value is present in
the object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

x=

["apple",

"banana

"]

print("ba

nana" in

x)

# returns True because a sequence with the value "banana" is

in the list x = ["apple", "banana"]

print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero Shift left by pushing zeros in from the


fill
left right and let the leftmost bits fall off
shift

>> Signed Shift right by pushing copies of the leftmost


right
shift bit in from the left, and let the rightmost bits fall off

a = 0011 1100

b = 0000 1101

a&b = 0000 1100


a|b = 0011 1101

a^b = 0011 0001

~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

is evaluated as if parentheses were placed as so:


(x + 2) < (y / 10). Expression
V
alue

10 < 20 True

10 >= 20 False

x < 100 True if x is less than 100; otherwise, False

x != y True unless x and y are equal

Compound Boolean Expressions


A combination of two or more Boolean expressions using logical operators is
called a compound Boolean expression. Simple Boolean expressions, each
involving one relational operator, can be combined into more Complex Boolean
expressions using the logical operators and, or, and not.

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.

The syntax of the if-statement is given below.

if condition :

block

6. The reserved word if begins a if statement.


7. The condition is a Boolean expression that determines whether or not the body will
be executed. A colon (:) must follow the condition.
8. The block is a block of one or more statements to be executed if the condition is true.
The Statements within a block must all be indented the same number of spaces from the left.
The block within an if must be indented more spaces than the line that begins the if
statement. The block technically is part of the if statement. This part of the if statement is
sometimes called the body of the if.

if x < 10:
y=x

Eg: num = int(input("enter the number?"))

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.

The syntax of the elif statement is given below

if expression 1:

# block of statements

elif expression 2:

# block of statements

elif expression 3:

# block of statements

else:

# block of statements

marks = int(input("Enter the


marks? ")) if marks > 85 and
marks <= 100:

print("Congrats ! you scored grade


A ...") elif marks > 60 and marks <= 85:

print("You scored grade B


+ ...") elif marks > 40 and marks
<= 60:

print("You scored grade B


...") elif (marks > 30 and marks
<= 40):

print("You scored grade C ...")

else:

print("Sorry you are fail ?")


Nesting in Conditional
The statements in the block of the if or the else may be any Python statements, including
other if/else statements. These nested if statements can be used to develop arbitrarily
complex control flow logic.

value = eval(input("Please enter an integer value in the


range 0...10: ")

if value >= 0: # First check

if value <= 10: # Second check

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.

Multi-way Decision Statements


A simple if/else statement can select from between two execution paths. The if/elif/else
statement is valuable for selecting exactly one block of code to execute from several
different options. The if part of an if/elif/else statement is mandatory. The else part is
optional. After the if part and before else part (if present) you may use as many elif blocks
as necessary.

value = eval(input("Please enter an


integer in the range 0...5: ")) if value
< 0:
print("Too small") elif value == 0:
print("zero") elif value ==
1:
print("one") elif value == 2:

print("two") elif value ==


3:
print("three") elif value == 4:

print("four") elif value ==


5:
print("five")

else:
print("Too large")

print("Done")

Conditional Expressions
The general form of the conditional expression is : expression1 if condition
else expression2 where

9. expression1 is the overall value of the conditional expression if condition is true.


10. condition is a normal Boolean expression that might appear in an if statement.
11. expression2 is the overall value of the conditional expression if condition is false.

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.

There are the following advantages of loops in Python.

● It provides code re-usability.


● Using loops, we do not need to write the same code again and again.
● Using loops, we can traverse over the elements of data structures (array or linked lists).

Python While loop


The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.It can be viewed as a repeating if
statement. When we don't know the number of iterations then the while loop is most
effective to use.

The syntax is given below.

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

#The while loop will iterate until condition


becomes false. While(i<=10):

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.

The syntax of for loop in python is given below.

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)

• The start represents the beginning of the iteration.


• The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1
to 4 iterations. It is optional.
• The step size is used to skip the specific numbers from the iteration. It is optional to use. By
default, the step size is 1. It is optional.

Example-1: Program to print numbers in sequence.

for i in range(10): for n in range(1, 11):

print(i,end = ' ') print(n)

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:

12. range(10) =0,1,2,3,4,5,6,7,8,9


13. range(1, 10)= 1,2,3,4,5,6,7,8,9
14. range(1, 10, 2) =1,3,5,7,9
15. range(10, 0, -1) =10,9,8,7,6,5,4,3,2,1
16. range(10, 0, -2) =10,8,6,4,2
17. range(2, 11, 2) =2,4,6,8,10
18. range(-5, 5)= −5,−4,−3,−2,−1,0,1,2,3,4
19. range(1, 2)= 1
20. range(1, 1)=(empty)
21. range(1, -1)= (empty)
22. range(1, -1, -1) =1,0
23. range(0) =(empty)

Nested Loop in python

Python allows us to nest any number of while or for loops inside another loop. The inner
loop is executed n

number of times for every iteration of the outer loop.

Syntax :-
for iterating_var1 in sequence: #outer loop

for iterating_var2 in sequence:


#inner loop #block of statements

#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

Abnormal Loop Termination


In Python, break and continue statements can alter the flow of a normal loop.Loops iterate
over a block of code until the test expression is false, but sometimes we wish to terminate
the current iteration or even the whole loop without checking test expression.

The break and continue statements are used in these cases.

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

# Program to show the use of continue statement inside loops Output :-


for val in
"string": if val
== "i": t
r
cont
n

Continue

Definite Loops v/s Indefinite Loops

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

while n <= 10:


print(n) n=n + 1
Eg:-

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 :-

done = False # Enter the loop at


least once while not done:

entry = eval(input()) # Get value from user


if entry == 999: # Did user provide the magic
number? done = True # If so, get out

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):

print("Hi! we are inside the infinite while loop")


MODULE 3:
FUNCTIONS
INTRODUCTION

A function is a block of organized, reusable code that is used to perform related


action. Python allows dividing a large program in to simpler building blocks
named functions. Functions provide better modularity for your application and a
high degree of code reusing.

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 advantages of using functions are:


● Reducing duplication of code
● Decomposing complex problems into simpler pieces
● Improving clarity of the code
● Reusability of code

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.

The built-in functions in Python are:-


abs()
The python abs() function is used to return the absolute value of a number. It takes
only one argument (a number whose absolute value is to be returned). The
argument can be an integer and floating-point number.

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.

mylist = [True, True, 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.

mylist = [False, True, False] Result:- True

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.

x = bin(36) Result:- 0b100100

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.

x = complex(3, 5) Result:- (3+5j)

print(x)

float()
The float() function converts the specified value into a floating point

number. x = float(3) Result: 3.0


print(x)

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.

x = hex(255) Result: 0xff

print(x)

input()
The input() method reads a line from input, converts into a string and returns it.
The input() function allows user input.

print("Enter your name:") Result:

x = input() Enter your name: Abi

print("Hello, " + x) Hello Abi

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.

mylist = ["apple", "orange", "cherry"] Result: 3

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.

x = min(5, 10) Result: 5

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.

x = max(5, 10) Result: 10

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 = oct(12) Result: 0o14


pow()
The python pow() function is used to compute the power of a number. It returns
x to the power of y.

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

sequence. alph = ["a", "b", "c", "d"] Result: d c b a

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()

The sum() function returns a number, the sum of all items in an

iterable. a = (1, 2, 3, 4, 5) Result: 15

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.

a = ('apple', 'banana', 'cherry') Result: <class 'tuple'><class


'str'> b = "Hello World"

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.acos(x) Returns the arc cosine value of x

math.asin(x) Returns the arc sine value of x

math.atan(x) Returns the arc tangent value of x

math.ceil(x) Rounds a number upwards to the nearest integer, and returns


the result
math.cos(x) Returns the cosine of x

math.degrees(x) Converts an angle from radians to degrees


math.dist(p, q) Calculates the euclidean distance between two specified points
(p and q), where p and q are the coordinates of that point
math.fabs(x) Returns the absolute value of a number
math.factorial() Returns the factorial of a number

math.floor(x) Rounds a number downwards to the nearest integer, and


returns the result
math.frexp() Returns the mantissa and the exponent, of a specified value
math.fsum(iterable) Returns the sum of all items in an iterable (tuples, arrays, lists,
etc.)
math.gamma(x) Returns the gamma value of x
math.gcd() Returns the highest value that can divide two integers
math.isclose() Checks whether two values are close, or not
math.isfinite(x) Checks whether x is a finite number

math.isnan(x) Checks whether x is NaN (not a number)


math.isqrt(n) Returns the nearest integer square root of n
math.log(x, base) Returns the natural logarithm of a number, or the logarithm of
number to base
math.pow(x, y) Returns the value of x to the power of y

math.radians(x) Converts a degree value (x) to radians

math.sin(x) Returns the sine of x

math.sinh(x) Returns the hyperbolic sine of x

math.sqrt(x) Returns the square root of x

math.tan(x) Returns the tangent of x

math.trunc(x) Returns the truncated integer parts of x

Math Constants

Constant Description
math.e Returns Euler's number (2.7182...)

math.inf Returns a floating-point positive infinity


math.nan Returns a floating-point NaN (Not a Number) value

Math.pi Returns PI (3.1415...)


math.tau Returns tau (6.2831...)

Example Code

Output:
PYTHON: MODULE 3 S.A

RANDOM FUNCTIONS

Python has a built-in module that you can use to make random

numbers. The random module has a set of methods:

Method Description

seed(5) Initialize the random number generator

getrandbits(16) Returns a number representing the random bits

randrange() Returns a random number between the given range

randint() Returns a random number between the given range

choice() Returns a random element from the given sequence

choices() Returns a list with a random selection from the given sequence

shuffle() Takes a sequence and returns the sequence in a random order

sample() Returns a given sample of a sequence

random() Returns a random float number between 0 and 1

uniform() Returns a random float number between two given parameters


triangular() Returns a random float number between two given parameters,
you can also set a mode parameter to specify the midpoint between
the two other parameters
betavariate(alpha,beta) Returns a random float number between 0 and 1 based on the Beta
distribution (used in statistics)

expovariate() Returns a random float number between 0 and 1, or between 0 and

-1 if the parameter is negative, based on the Exponential


distribution (used in statistics)

gammavariate(alpha,beta) Returns a random float number between 0 and 1 based on the


Gamma distribution (used in statistics)

gauss(mu,sigma) Returns a random float number between 0 and 1 based on the


Gaussian distribution (used in probability theories)

lognormvariate(mu,sigma) Returns a random float number between 0 and 1 based on a log-


normal distribution (used in probability theories)

normalvariate(mu,sigma) Returns a random float number between 0 and 1 based on the


normal distribution (used in probability theories)

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,

January 1, 1970 (epoch). Time intervals are floating-point numbers in units

of seconds import time

ticks = time.time()

print (“no of ticks”,

ticks) struct_time

structure

This structure has following attributes.

gmtime(sec) : This function returns a structure with 9 values each representing


a time attribute in sequence. It converts seconds into time attributes(days, years,
months etc.) till specified seconds from epoch.

import time

print (time.gmtime(2244556))

time.struct_time(tm_year=2013, tm_mon=7, tm_mday=17, tm_hour=21,


tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)

asctime(“time”) :- This function takes a time attributed string produced by


gmtime() and returns a 24 character string denoting time.

ctime(188889) :- This function returns a 24 character time string but takes


seconds as argument and computes time till mentioned seconds. If no argument
is passed, time is calculated till present.

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

print

(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.

calendar(year, w, l, c) :- This function displays the year, width of characters,


no. of lines per week and column separations.2.

firstweekday() :- This function returns the first week day number. By default 0
(Monday).

import calendar

print

(calendar.calendar(2019,2,1,6)

) print

(calendar.firstweekday())
isleap (2020) :- This function checks if year mentioned in argument is

leap or not import calendar

if (calendar.isleap(2008)): print

("The year is leap")

else : print ("The year is not leap")

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)

datetime : It allows us to manipulate the combination of date and time (month,


day, year, hour, 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;

Displays current date and time (Eg: )


import datetime Result:2020-07-22

08:22:39.776866 x= datetime.datetime.now()

print(x)
PYTHON: MODULE 3 S.A

import datetime Result: 2020-05-17 00:00:00

x = datetime.datetime(2020,

5, 17) print(x)

import datetime Result : June

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

Get Current Date


import datetime output: 2020-07-22

date_object =

datetime.date.today()

print(date_object)

datetime.weekday() - Return the day of the week as an integer, where


Monday is 0 and Sunday is 6.

datetime.isoweekday() - Return the day of the week as an integer, where Monday


is 1 and Sunday is 7.

datetime.date() - Return date object with same year, month and day.

datetime.time() - Return time object with same hour, minute, second,


microsecond and fold.

datetime.timetz() - Return time object with same hour, minute, second,


microsecond, tzinfo attributes.

USER DEFINED FUNCTION


User-define functions - The user-defined functions are the functions defined by the
user to perform the specific task.

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

documentation string of the function or docstring.


● The code block within every function starts with a colon (:) and is indented.
● The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.

def function_name(
parameters ):
“””function_docstring”””
function_block

return (expression)

def my_function(): > function definition

print("Hello from a function") > function block

my_function() > function call

Parameters and Arguments


The terms parameter and argument can be used in the same sense : information
that are passed into a function.
PYTHON: MODULE 3 S.A

From a function's perspective:


A parameter is the variable listed inside the parentheses in the function

definition. An argument is the value that is sent to the function when it is

called.

Types of arguments (parameters)


Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly
with the function definition.

def my_function(fname, lname):

print(fname + " " + lname)

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.

def my_function(child3, child2, child1):

print("The youngest child is " +

child3) return
PYTHON: MODULE 3 S.A

my_function(child1 = “Aravi", child2 = “Abi", child3 = “Anju")

Default Arguments : A default argument is an argument that assumes a default


value if a value is not provided in the function call for that argument (default
parameters).

def my_function(country =

"Norway"): print("I am from " +

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):

print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

It is used to pass a non-keyworded, variable-length argument list.


PYTHON: MODULE 3 S.A

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):

print("Hello, " + name + ". Good morning!")

student('Paul') function call


Mutable vs Immutable Objects in Python
There are two types of objects in python i.e. Mutable and Immutable
objects. Whenever an object is instantiated, it is assigned a unique object id.

To summarize the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.

Mutable Objects: These are of type list, dict, set

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

color = ["red", "blue",


"green"] print(color)

color[0] = "pink" color[2] = "orange" print(color)

output

Is Python call by reference or call by value


CALL/PASS BY VALUE:

● In pass-by-value, the function receives a copy of the argument objects


passed to it by the caller, stored in a new location in memory.
● You pass values of parameter to the function, if any kind of change done to
those parameters inside the function , those changes not reflected back in
your actual parameters.

CALL / PASS BY REFERENCE:


● In pass-by-reference, the function receives reference to the argument objects
passed to it by the caller, both pointing to the same memory location.
● We pass reference of parameters to the function. if any changes made to
those parameters inside function those changes are get reflected back to your
actual parameters.

Python utilizes a system, which is known as “Call by Object Reference” or


“Call by assignment”. In the event that you pass arguments like whole
numbers, strings or tuples to a function, the passing is like call-by-value
because you cannot change the value of the immutable objects being passed
to the function. Whereas passing mutable objects can be considered as call by
reference because when their values are changed inside the function, then it
will also be reflected outside the function.

In Python, Values are passed to function by object reference.

● If object is immutable (not modifiable) then the modified value is not


available outside the function.
● If object is mutable (modifiable) then modified value is available outside the
function.

Example 1
# call by value string = "Python" def test(string):

string = "Python

Programming"

print("Inside

Function:", string)

test(string)

print("Outside Function:", string)

Output
Example 2:

def add_more(list): list.append(50)


print("Inside

Function", list)

mylist =

[10,20,30,40]

add_more(mylist)

print("Outside Function:", 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

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.

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()

print("Value outside function:",y)

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.

The global Keyword


Normally, when you create a variable inside a function, that variable is local,
and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

We also use the global keyword to change a global variable inside


a function.

def myfunc(): output : Python is


fantastic

global x

x = "fantastic"
myfunc()
print("Python
is " + x)

FUNCTION COMPOSITION IN PYTHON


Function composition is the way of combining two or more functions in
such a way that the output of one function becomes the input of the second
function and so on.
For example, let there be two functions “F” and “G” and their composition
can be represented as F(G(x)) where “x” is the argument and output of G(x)
function will become the input of F() function.
Example
def add(x): return x + 2

def

multip

ly(x):

return

x*2

print("Adding 2 to 5 and multiply result with 2: ",multiply(add(5)))

RECURSION
Python also accepts function recursion, which means a defined function can call

itself. In Python, a function is recursive if it calls itself and has a

termination condition.

Recursion is a common mathematical and programming concept. It means


that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.

Stack diagram for recursive function


In Stack diagrams , we used a stack diagram to represent the state of a
program during a function call. The same kind of diagram can help interpret
a recursive function.

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

Recursion makes our program:

● 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.

A string is a sequence of characters. In Python strings are arrays of bytes


representing Unicode characters. String literals in python are surrounded by
either single quotation marks, or double quotation marks. ‘hello’ is the same as
“hello”.

Display a string literal with the print() function:

my_string = 'Hello' print(my_string) my_string = "Hello"

print(my_string) Output

Hello Hello

Even triple quotes can be used in Python but generally used to represent multiline
strings and docstrings.

# triple quotes string can extend multiple

lines my_string = """Hello, welcome to

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).

a = "Hello, World!" print(a[4])

#Accessing string characters in Python


str = 'programiz'

print(str)

#first character print('str[1] = ', str[1]) #last

character print('str[-1] = ', str[-1])

str[5] will give error : IndexError : string index out of range

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.

Consider the following example:

# Given String

str = "COMPUTER"

# Start 0th index to


end print(str[0:])

# Starts 1th index to 4th


index print(str[1:5])

# Starts 2nd index to 3rd


index print(str[2:4])

# Starts 0th to 2nd


index print(str[:3])

Output: COMPUTER OMPU

MP COM
STRING SPECIAL OPERATORS

Assume string variable a holds 'Hello' and variable b holds 'Python', then –

Operator Description Example

+ Concatenation - Adds values on a + b will give HelloPython


either side of the operator.

* Repetition - Creates new strings, a*2 will give – HelloHello


concatenating multiple copies of the
same string.

[] Slice - Gives the character from the a[1] will give e


given index
[:] Range Slice - Gives the characters a[1:4] will give ell
from the given range

in Membership - Returns true if a txt = "Hello Python"


character exists in the given string
x = "H" in txt

print(x)

Output : True

not in Membership - Returns true if a txt = "Hello Python"


character does not exist in the given
x = "world" not in txt
string
print(x)

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:

General syntax : string_name.method()


Method Description Example

capitalize() Converts the first character to upper mystring = "hello python"


print(mystring.capitalize())
case.

stringname.capitalize()

Hello python

casefold() Converts string into lower case. mystring = "hello PYTHON"


print(mystring.casefold())
stringname.casefold()

hello python

center() Returns a centered string. The center() mystring = "Hello"


method will center align the string, x = mystring.center(12)
print(x)
using a specified character (space is
default) as the fill character.

stringname.center(length)

Hello

count() Returns the number of times a specified


value occurs in a string. txt = "I love apples, apple are
my favorite"

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)

b'My name is St\xc3\xe5le'


coding parameter specifies which
coding technique to be used(UTF-8).
endswith() Returns true if the string ends with the mystr = "Python"
print(mystr.endswith("hon"))
specified value.

stringname.endswith(value)

True

expandtabs() Sets the tab size of the string.


txt = "H\te\tl\tl\to"
stringname.expandtabs(tabsize)
x = txt.expandtabs(2)
print(x)

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.

index() Searches the string for a specified value mystr = "HelloPython"


and returns the position of where it was >>> print(mystr.index("P"))
found. 5

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

isalpha() Returns True if all characters in the string are a = "123"


in the alphabet. >>> print(a.isalpha())

stringname.isalpha()

False

isdecimal() Returns True if all characters in the string are mystr = "HelloPython"
print(mystr.isdecimal())
decimals.

stringname.isdecimal()
False

isdigit() Returns True if all characters in the string are c="133"


digits. print(c.isdigit())

stringname.isdigit()

True
identifier. c="_user_123"
print(c.isidentifier())

True
stringname.isidentifier()

islower() Returns True if all characters in the string are c="Python"


print(c.islower())
lower case. Numbers, symbols and spaces are
not checked, only alphabet characters.

stringname.islower()
False

isnumeric() Returns True if all characters in the string are c="133"


numeric.
print(c.isnumeric())

stringname.isnumeric()

True

isprintable() Returns True if all characters in the string are c="\t"


print(c.isprintable())
printable.

stringname.isprintable()

False

c="133"

print(c.isprintable())
True

isspace() Returns True if all characters in the string are


whitespaces.

stringname.isspace()

istitle() Returns True if the string follows the c="Python Programming"


print(c.istitle())
rules of a title. The istitle() method
returns True if all words in a text start
with a upper case letter, AND the rest of
the word are lower case letters,
otherwise False. True

Symbols and numbers are ignored.


Stringname.istitle()

isupper() Returns True if all characters in the


string are uppercase. txt = "HI "

x = txt.isupper ()
stringname.isupper()
print(x)

True
join() The join() method takes all items in an myTuple = ("John", "Peter")

iterable and joins them into one string. x = "#".join(myTuple)

print(x)

A string must be specified as the


separator.

John#Peter

stringname.join(iterable)

ljust() Returns a left justified version of the


string. The ljust() method will left align txt = "Apple"
the string, using a specified character x = txt.ljust(20)

print(x, "is my favorite")


(space is default) as the fill character. apple is my favorite
fruit.
stringname.ljust(length,character)

lower() Converts a string into lower case. a = "Python"


print(a.lower())
stringname.lower()

python

lstrip() Returns a left trim version of the string.


(White spaces in left are trimmed). txt = " kiwi "
x = txt.lstrip()
stringname.lstrip()
print("of all fruits", x, "is my
favorite")

of all fruits kiwi is my


favorite
partition() Returns a tuple where the string is
parted into three parts txt = "Python is good"

x = txt.partition("is")

print(x)

The partition() method searches for a


specified string, and splits the string into
a tuple containing three elements.
('Python ', 'is', ' good')

The first element contains the part


before the specified string.

The second element contains the

specified string.

The third element contains the part after


the string.

stringname.partition(value)

replace() Returns a string where a specified value mystr = "Hello Python”


print(mystr.replace("Hello",
is replaced with a specified value. "Bye"))

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

rjust() Returns a right justified version of the

string.

string.rjust(length)

rpartition() Returns a tuple where the string is


parted into three parts. The rpartition() txt = "I like python
method searches for the last occurrence programming python is fun"
of a specified string, and splits the string
x = txt.rpartition("python")
into a tuple containing three elements.
print(x)

stringname.rpartition(value)

('I like python programming',


'python', ' is fun')
rsplit() Splits the string at the specified
separator, and returns a list.

stringname.rsplit()

rstrip() Returns a right trim version of the string.


It removes any trailing spaces.

stringname.rstrip()

split() Splits the string at the specified


separator, and returns a list. You can txt = "welcome to
specify the separator, default programming"

separator is any whitespace. x = txt.split()

print(x)

stringname.split(seperator)

['welcome', 'to', 'programming']


splitlines() Splits the string at line breaks and
returns a list. txt = "Thank you\nWelcome"
x = txt.splitlines()
stringname.splitlines()
print(x)

['Thank you', 'Welcome']


specified value. str = "Hello Python"
print(mystr.startswith("P"))

stringname.startswith(value)

False

print(mystr.startswith("H"))

True

strip() Returns a trimmed version of the string


txt = " python "
x = txt.strip()

print("i like ", x, "python")

i like python python


swapcase() Swaps cases, lower case becomes upper mystr = "Hello PYthon"
print(mystr.swapcase())

case and vice versa.


hELLO pyTHON
stringname.swapcase()

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

zfill() Fills the string with a specified number


of 0 values at the beginning. txt = "50"

x = txt.zfill(10)
stringname.zfill()
print(x)

0000000050

ESCAPE CHARACTERS

Following table is a list of escape or non-printable characters that can be


represented with backslash notation. Backspace, newline etc. are represented as
shown below. Escape sequence is a backslash followed by the character that
needs to be inserted.
An escape character gets interpreted in a single quoted as well as double quoted
strings.

Backslash Description
notation

\a Bell or alert

\b Backspace

\n Newline

\s Space

\t Tab

\v Vertical tab

\’ Single quotes

STRING FORMATTING OPERATOR

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

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase


letters)
%X hexadecimal integer (UPPERcase
letters)
%e exponential notation (with
lowercase 'e')
%E exponential notation (with
UPPERcase 'E')

%f floating point real number

PYTHON COLLECTIONS

There are four collection (array) data types in the Python programming language:

● List is a collection which is ordered and changeable. It allows


duplicate members.
● Tuple is a collection which is ordered and unchangeable. It allows
duplicate members.
● Set is a collection which is unordered and unindexed. No duplicate
members are allowed in a set.
● Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members are allowed in dictionary.

When choosing a collection type, it is required to understand the properties of


that collection type.

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

L1 = ['physics', 'chemistry', 1997, 2000]

L2 = [1, 2, 3, 4, 5]

L3 = ["a", "b", "c", "d"]

L4 =
[“c”,”cpp”,”java”]
L5 = []

BASIC LIST OPERATIONS

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.

Python Expression Results Description

len([1, 2, 3]) 3 Length of the


len([“a”,”b”,”c”,”d”]) 4 list

l1 = [1,2,3,4,5]
len(l1) 5

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 5 ['Hi!', 'Hi!', 'Hi!', Repetition


'Hi!'””Hi!”]

2 in [1, 2, 3] True Membership

for x in [1, 2, 3]: 123 Iteration

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.

thislist = ["C", "PYTHON", "JAVA"]

print(thislist[2])

The output will be - JAVA

Negative Indexing

Python supports negative indexing. Negative indexing means beginning from


the end, -1 refers to the last item, -2 refer to the second last item etc.

thislist = ["C", "PYTHON", "JAVA"]

print(thislist[-1])

Output will be -

JAVA

Range of Indexes (Slicing)

Range of indexes can be specified by mentioning where to start and where to


end the range. Slice operation is done on list using : operator.

The syntax for slice operation is – list[begin:end]

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.

thislist = ["C", "PYTHON", "JAVA", "CPP", "PHP", "PERL", "ANDROID"]

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

start at the first item:

thislist = ["C", "PYTHON", "JAVA", "CPP", "PHP", "PERL", "ANDROID"]

print(thislist[:4]).By leaving out the end value, the range will go on to the end of the

list: thislist = ["C", "PYTHON", "JAVA", "CPP", "PHP", "PERL", "ANDROID"]


print(thislist[2:])
Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:

Example

This example returns the items from index -4 (included) to index -1

(excluded) thislist = ["C", "PYTHON", "JAVA", "CPP", "PHP", "PERL",

"ANDROID"]

print(thislist[-4:-1])
CHANGE ITEM VALUE

To change the value of a specific item, refer to the index number:

thislist = ["C", "PYTHON", "JAVA"]

thislist[1] =
"CPP"
print(thislist)

In this case the item in the index position 1 (PYTHON) will be changed to “CPP”

Output

['C', 'CPP', 'JAVA']

LOOP THROUGH A LIST

for loop can be used to loop through a list:

thislist= ["C", "PYTHON", "JAVA"]

for x in
thislist:
print(x)

Output will be

PYTH

ON

JAVA

CHECK IF ITEM EXISTS

To determine if a specified item is present in a list use the in keyword:

thislist = ["C", "PYTHON", "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:

thislist = ["C", "PYTHON", "JAVA"]

print(len(thislist)) Output will be 3

ADDING NEW ITEMS TO THE LIST

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.

It has general syntax – list.append(element)

Only one element can be added using append() method at a


time. thislist = ["C", "PYTHON", "JAVA"]

thislist.append("CPP")
print(thislist)
Output

['C', 'PYTHON', 'JAVA', 'CPP']

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

thislist = ["C", "PYTHON", "JAVA"]

thislist.insert(1, "CPP") print(thislist)

Output

['C',’CPP’, 'PYTHON', 'JAVA']

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

thislist = ["C", "CPP",

"PHP"] newlist=

["PYTHON", "R"]

thislist.extend(newlist)

print(thislist)

Output

['C', 'CPP', 'PHP', 'PYTHON', 'R']


REMOVING ITEMS FROM THE LIST

There are several methods to remove items from a list.

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

the list. The remove() raises an error if element to be removed is not in

the list. The method removes a single specified item.

thislist = ["C", "PYTHON", "JAVA"]

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 = ["C", "PYTHON", "JAVA"]

thislist.pop() print(thislist)

Output

'C', 'PYTHON'
del keyword
The del keyword removes the specified index.

thislist = ["C", "PYTHON", "JAVA"]

del thislist[0] print(thislist)

Output

'PYTHON', 'JAVA'

The del keyword can also delete the list


completely: thislist = ["C", "PYTHON",
"JAVA"]

del thislist

The list will be deleted entirely.

clear() method
The clear() method empties the list. All elements in the list will be deleted.
thislist = ["C", "PYTHON", "JAVA"]

thislist.clear() print(thislist)

Output will be empty list

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().

thislist = ["C", "PYTHON", "JAVA"]

mylist =
thislist.copy()
print(mylist)

The mylist will be a copy of thislist.

Another way to make a copy is to use the function list().

Make a copy of a list with the list()

method: thislist = ["C", "PYTHON",

"JAVA"]

mylist = list(thislist) print(mylist)

REVERSE A LIST

Python list method reverse() reverses objects of

list. fruits = ['apple', 'banana', 'cherry']


fruits.revers

e()

print(fruits)

Output

['cherry', 'banana', 'apple']

ELEMENT COUNT

The count() method returns the number of elements with the specified value.

lists = ["c", "cpp", "c"]

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

The sort() method sorts the list ascending by

default. cars = ['Ford', 'BMW', 'Volvo']

cars.sort() print(cars)
Output

['BMW', 'Ford', 'Volvo']

JOIN TWO LISTS

There are several ways to join, or concatenate, two or more lists in

Python. One of the easiest ways are by using the + operator.

list1 = ["a", "b", "c"]

list2 = [“x”, “y”, “z”] list3 = list1 + list2

print(list3)

Another way to join two lists is by appending all the items from list2 into list1,
one by one:

list1 = ["a", "b", "c"]

list2 = [“x”, “y”,

“z”] for x in list2:

list1.append(x)

print(list1)

The list() Constructor


It is also possible to use the list() constructor to make a new list.

Example

Using the list() constructor to make a List:

thislist = list(("C", "PYTHON", "JAVA")) # note the double round-

brackets print(thislist)
A new list name thislist is created here.

Built-in List Functions

Python includes the following list functions −

Sr.No. Function with Description

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.

Compares elements of both lists.

2 len(list)

Gives the total length of the list.


3 max(List1)

Returns item from the list with max value.


4 min(list)

Returns item from the list with min value.


5 list(seq)

Converts a tuple into list.

Examples:

cmp()

stock_price_1 = [50.23]

stock_price_2 = [75.14] print(cmp(stock_price_1, stock_price_2))

print(cmp(stock_price_1, stock_price_1)) print(cmp(stock_price_2,

stock_price_1))

When you run the above code, it produces the following result:

-1

len()

list1 = [‘abc’, 'xyz', 'zara']


print "First list length : ", len(list1)

When we run above program, it produces following result −

First list length: 3

max()

list1 = [123, '800', '999', '976']

print "Max value element : ", max(list1)

When we run above program, it produces following result −

Max value element: 999

min()

list1 = [123, '800', '999', '976']

print "Min value element : ", min(list1)

When we run above program, it produces following result −

Min value element: 123

list() method.

aTuple = (‘acl’, 'xyz', 'zara', 'abc') aList = list(aTuple)

print "List elements : ", aList

When we run above program, it produces following result

− List elements : [‘acl’, 'xyz', 'zara', 'abc']


TUPLES

A tuple is a collection of objects which ordered and immutable. Tuples are


sequences, just like lists. The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas lists use
square brackets.

Creating a tuple is as simple as putting different comma-separated values. A


tuple is a collection which is ordered and unchangeable.

Advantages of Tuple over List


Since tuples are quite similar to lists, both of them are used in similar situations.
However, there are certain advantages of implementing a tuple over a list.

● We generally use tuples for heterogeneous (different) data types and


lists for homogeneous (similar) data types.
● Since tuples are immutable, iterating through a tuple is faster than with
list. So there is a slight performance boost.
● If there exists that doesn't want to be changed, implementing it as tuple
will guarantee that it remains write-protected.

CREATING A TUPLE

Example 1:

thistuple = ("apple", "banana",


"cherry") print(thistuple)
example 2

tup1 = ('physics', 'chemistry', 1997, 2000)

tup2 = (1, 2, 3, 4, 5 )

tup3 = "a", "b", "c", "d"

The empty tuple is written as two parentheses containing

nothing − tup1 = ()

To write a tuple containing a single value include a comma, even though there is

only one value tup1 = (50,)

ACCESS TUPLE ITEMS

Tuple items can be accessed by referring to the index number, inside square
brackets:

thistuple = ("apple", "banana", "cherry")

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.

thistuple = ("apple", "banana", "cherry")

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.

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",


"mango")

print(thistuple[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.

Range of Negative Indexes

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)

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

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')

BASIC TUPLES OPERATIONS

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 −

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 3 ('Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x 123 Iteration


CHANGE TUPLE VALUES

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.

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")

y = list(x) y[1] = "kiwi" x = tuple(y) print(x)

Output

(“apple”, “kiwi”, “cherry”)

LOOP THROUGH A TUPLE

for loop is used to loop through the tuple items .

Iterate through the items and print the values:

thistuple = ("apple", "banana", "cherry")

for x in thistuple: print(x)

CHECK IF ITEM EXISTS

To determine if a specified item is present in a tuple use the in keyword:

Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")

if "apple" in thistuple:

print("Yes, 'apple' is in the fruits tuple")


TUPLE LENGTH

To determine how many items a tuple has, use the len() method:

Print the number of items in the tuple:

T1 = ("apple", "banana", "cherry")

print(len(T1)) Output

ADD ITEMS TO TUPLE

Once a tuple is created, new items cannot be added to it. Tuples are unchangeable.

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an
error print(thistuple)

REMOVE ITEMS

Note: Elements cannot be removed from a tuple.

Tuples are unchangeable, so items cannot be removed from it, but the tuple can be
deleted completely.

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")

del thistuple

print(thistuple) #this will raise an error because the tuple no longer exists
JOIN TWO TUPLES

To join two or more tuples use the + operator:


Join two tuples:

tuple1 = ("a", "b", "c")

tuple2 = (1, 2, 3)

tuple3 = tuple1 +
tuple2 print(tuple3)

The result will be the combination of two tuples.

('a', 'b', 'c', 1, 2, 3)

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)

METHODS IN TUPLE

count()

Return the number of times the value 5 appears in the tuple:

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5,5,5)

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.

The index() method raises an exception if the value is not found.

Reverse the order of items in the Python tuple – reverse()

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)

tup.reverse() #this will make the tuple as (8,6,4,2)

BUILT-IN TUPLE FUNCTIONS

Python includes the following tuple functions −

Sr.No. Function with Description

1 cmp(tuple1, tuple2)

Compares elements of both tuples.


2 len(tuple)

Gives the total length of the tuple.


3 max(tuple)

Returns item from the tuple with max value.


4 min(tuple)

Returns item from the tuple with min value.


5 tuple(seq)

Converts a list into tuple.

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:

● if T1 > T2, then cmp(T1, T2) returns 1

● if T1 = T2, then cmp(T1, T2) returns 0

● if T1 < T2, then cmp(T1, T2)

returns -1 Syntax

Following is the syntax for cmp() method

− cmp(tuple1, tuple2)
max() function

Python tuple method max() returns the elements from the tuple with maximum
value.

max(tuple)

tuple − This is a tuple from which maximum valued element to be returned.

This method returns the elements from the tuple with maximum value.

Example

The following example shows the usage of max() method. tuple1, tuple2 =

( 'xyz', 'zara', 'abc'), (456, 700, 200)

print "Max value element : ",

max(tuple1) print "Max value element

: ", max(tuple2)

When we run above program, it produces following result

− Max value element : zara

Max value element : 700

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

value. tuple1= (456, 700, 200)

print "min value element : ", min(tuple1)

min value element : 200

tuple()

Python tuple method tuple() converts a list of items into

tuples tuple( seq )

● seq − This is a sequence to be converted into tuple.

This method returns the

tuple. aList = [123, 'xyz',

'zara', 'abc'] aTuple =

tuple(aList)

print (aTuple)

When we run above program, it produces following result

− Tuple elements: (123, 'xyz', 'zara', 'abc')

sorted()

The sorted() function returns a sorted list of the specified iterable object.

The order can be ascending or descending order. Strings are sorted


alphabetically, and numbers are sorted numerically.
a = ("b", "g", "a", "d", "f", "c", "h", "e")

x=

sorted(a)

print(x)

Output

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

a = ("h", "b", "a", "c", "f", "d", "e", "g")

x = sorted(a, reverse=True) print(x)

Output

['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']


DICTIONARY

A dictionary is a collection which is unordered, changeable and indexed. In


Python dictionaries are written with curly brackets, and they have keys and
values (key- value pair).

● Keys must be a single element


● Value can be any type such as list, tuple, integer, etc.

Dict = {}

An empty dictionary without any items is written with just two curly braces,
like this: {}.

thisdict = {"name": "Aravi", "age": 27, "job": “Engg” } print(thisdict)

ACCESSING ITEMS

Items in the dictionary can be accessed by referring to its key name, inside square
brackets:

x = thisdict["age"] #27 will be the output

y = thisdict[“job”] #Engg will be the output

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:

thisdict = { "name": "Aravi", "age": 27, "job": “Engg” } thisdict["name"] = “Abi”

Output

{‘name’: ‘Abi’, ‘age’: 27, ‘job’: ‘Engg’}

Here the name Aravi will be changed to Abi

LOOP THROUGH A DICTIONARY

In a dictionary items can be looped by using a for loop.


When looping through a dictionary, the return values are the keys of the
dictionary, but there are methods to return the values as well.

Print all key names in the dictionary, one by one:

thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}

for x in thisdict: print(x)

Output brand model year

Print all values in the dictionary, one by one:

thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}

for x in thisdict:
print(thisdict[x]
)

Output Ford Mustang 1964

Use the values() method to return values of a dictionary:

thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}

for x in thisdict.values(): print(x)

Outp

ut

Ford

Must
ang

1964

Loop through both keys and values, by using the items() method:

thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}

for x, y in thisdict.items(): print(x, y)

Output

brand

Ford

model

Mustang

year 1964

CHECK IF KEY EXISTS

To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:

thisdict = { "name": "John", "age": 30, "year": 1990}

if "age" in thisdict: print("Yes”)

DICTIONARY LENGTH

To determine how many items (key-value pairs) a dictionary has,


use the len() function.

Print the number of items in the dictionary:

print(len(thisdict

)) len(thisdict)

thisdict = {"brand": "Ford","model": "Mustang","year":

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 = { "brand": "Ford", "model": "Mustang", "year": 1964}

thisdict["color"] = "red"

thisdict[“place”]=” India”
print(thisdict)

REMOVING ITEMS

There are several methods to remove items from a dictionary:

The pop() method removes the item with the specified key name:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.pop("model")

print(thisdict)

Output

{'brand': 'Ford', 'year': 1964}

In this case the dictionary item model will be deleted.

The popitem() method removes the last inserted item:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}

thisdict.popite
m()
print(thisdict)

Output

{'brand': 'Ford', 'model': 'Mustang'}

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:

thisdict = {"brand": "Ford","model": "Mustang","year": 1964}

del thisdict["model"] print(thisdict)

Output

{'brand': 'Ford', 'year': 1964}

The del keyword can also delete the dictionary completely:


thisdict = { "brand": "Ford","model": "Mustang", "year": 1964}

del thisdict

print(thisdict) #this will cause an error because "thisdict" no longer exists.

The clear() method empties the dictionary:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}

thisdict.clear() print(thisdict)

In this case all the elements in the dictionary will be deleted.

COPY A DICTIONARY

A dictionary cannot be copied simply by typing dict2 = dict1, because: dict2


will only be a reference to dict1, and changes made in dict1 will automatically
also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

Make a copy of a dictionary with the copy() method:

thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}


mydict = thisdict.copy()

print(mydict)

A copy of the dictionary named mydict is created here.

Another way to make a copy is to use the built-in function dict().

Make a copy of a dictionary with the dict() function:


thisdict = { "brand": "Ford", "model": "Mustang","year": 1964}

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 = {

"name" : "Emil", "year" : 2004

child2 = {

"name" : "Tobias", "year" : 2007

child3 = {

"name" : "Linus", "year" : 2011

myfamily = { "k1" : child1,"child2" : child2, "child3" : child3}

Here there exists 3 dictionaries named child1, child2 and child3.


The dictionary named “myfamily” contains all the three dictionaries.

The dict() Constructor

It is also possible to use the dict() constructor to make a new dictionary:

thisdict = dict(brand="Ford", model="Mustang",


year=1964) print(thisdict)

A new dictionary named thisdict is created.

DICTIONARY METHODS

Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys


pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

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:

thisset = {"C", "CPP", "PYTHON”}

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 = {}

# check data type of a

print(type(a))

# initialize a with set()


a = set()

# check data type of a


print(type(a))

Output
<class 'dict'>

<class 'set'>

ACCESS SET ITEMS

Set items can’t be referenced using index or a key.

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:

thisset = {"PHP", "CPP", "C"}

for x in thisset:
print(x)

CHANGE ITEMS

Once a set is created, you cannot change its items, but you can add new items.

ADD ITEMS TO SET

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

Add an item to a set, using the add() method:

thisset = {"C", "CPP", "PYTHON"}

thisset.add("JAVA") print(thisset)

{'JAVA', 'CPP', 'C', 'PYTHON'}

Example

Add multiple items to a set, using the update() method:

thisset = {"C", "CPP", "PYTHON"}

thisset.update(["JAVA", "PHP",
"RUBY"]) print(thisset)
{'C', 'PYTHON', 'CPP', 'JAVA', 'PHP', 'RUBY'}

GET THE LENGTH OF A SET

To determine how many items a set has, use the len() method.

Example

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

x= len(thisset) print(x)

Output 3

REMOVE SET ITEM

To remove an item in a set, use the remove(), or the discard() method.

Example

Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana") print(thisset)

Output

{'cherry', 'apple'}

Note: If the item to remove does not exist, remove() will raise an error.

Example

Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}


thisset.discard("banana")
print(thisset)

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.

The return value of the pop() method is the removed item.

pop()

Remove item by using the pop() method:

thisset = {"apple", "banana", "cherry"}

x = thisset.pop() print(x) print(thisset)

Output

apple

{'cherry', 'banana'}

clear()

The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}


del keyword

The del keyword will delete the set completely:

thisset.clear() print(thisset) # set()

thisset = {"apple", "banana", "cherry"}

del thisset print(thisset)

The set() Constructor

It is also possible to use the set() constructor to make a set.

Example

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets

print(thisset)

Different methods for creating sets

subject = set((“C”,”PYTHON”,”MATHS”))

subject = {“c”,”cpp”,”python”}

subject = set([“c”,”cpp”.python”])

Join Two Sets – UNION OPERATION

There are several ways to join two or more sets in 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:

set1 = {"a", "b", "c", ”a”}

set2 = {“a”, “x”,


“y”} set3 =
set1.union(set2)
print(set3)

Output

{'b', ‘a’, ‘c’,‘x’, ‘y’}

using union | operator

Weekdays= {"Monday","Tuesday","Wednesday","Thursday", "Friday"}

Holidays = {" Saturday","Sunday"} Days = Weekdays|Holidays print(Days)

{'Wednesday', 'Monday', 'Friday', 'Thursday', ' Saturday', 'Sunday', 'Tuesday'}

The update() method inserts the items in set2 into set1:

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.

Difference is performed using - operator. Same can be accomplished using the


difference() method.

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.

The difference_update() method is different from the difference() method,


because the difference() method returns a new set, without the unwanted items,
and the difference_update() method removes the unwanted items from the
original set.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

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 = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

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.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft",

"facebook"} z = x.isdisjoint(y)

print(z) Output True

The issubset() method returns True if all items in the set exists in the specified
set, otherwise it returns False.
x = {"a", "b", "c"}

y = {"f", "e", "d", "c", "b", "a"}

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).

x = {"f", "e", "d", "c", "b",

"a"} y = {"a", "b", "c"}

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.

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft",

"apple"} z =

x.symmetric_difference(y) Output

{'cherry', 'microsoft', 'google', 'banana'}

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.

Consider the following example.

Days1 = {"Monday", "Tuesday", "Wednesday",


"Thursday"} Days2 = {"Monday", "Tuesday"}

Days3 = {"Monday", "Tuesday"}

#Days1 is the superset of Days2 hence it will print true.

print (Days1>Days2)

#prints false since Days1 is not the subset of Days2

print (Days1<Days2)

print (Days2 == Days3)

Output:
True False True

Built-in Functions with Set

Built-infunctions like all(), any(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks

You might also like