[go: up one dir, main page]

0% found this document useful (0 votes)
13 views56 pages

PYTHON Unit 1

The document provides an overview of core Python programming concepts, including conditional statements, looping, string manipulation, and data structures such as lists, tuples, and dictionaries. It discusses the history and features of Python, differences between Python 2 and 3, as well as keywords, identifiers, and various types of literals. Additionally, it covers the syntax for writing Python statements, comments, and variable declarations.

Uploaded by

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

PYTHON Unit 1

The document provides an overview of core Python programming concepts, including conditional statements, looping, string manipulation, and data structures such as lists, tuples, and dictionaries. It discusses the history and features of Python, differences between Python 2 and 3, as well as keywords, identifiers, and various types of literals. Additionally, it covers the syntax for writing Python statements, comments, and variable declarations.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY

16CA5202 – PYTHON PROGRAMMING


(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Introduction- Conditional Statements – Looping and Control statements – String
Manipulation – Lists – Tuples – Dictionaries

Table of Contents

INTRODUCTION TO PYTHON ............................................................................................... 1


Python Keywords ................................................................................................................. 4
Python Identifiers ................................................................................................................. 4
Python Statement.................................................................................................................. 5
Multi-line statement ............................................................................................................. 5
Python Indentation ............................................................................................................... 5
Python Comments ................................................................................................................ 6
Constants ............................................................................................................................... 7
Literals ................................................................................................................................... 8
Python Operators ................................................................................................................ 11
Python Data Types ............................................................................................................. 13
CONDITIONAL STATEMENTS ............................................................................................ 18
LOOPING AND CONTROL STATEMENTS ........................................................................ 21
Syntax .................................................................................................................................. 26
Flow Diagram ..................................................................................................................... 26
Example ............................................................................................................................... 27
STRING MANIPULATION .................................................................................................... 27
LISTS ........................................................................................................................................ 39
TUPLES .................................................................................................................................... 44
DICTIONARIES....................................................................................................................... 51
https://www.stxnext.com/what-is-python-used-for/
https://www.w3schools.com/python/exercise.asp?filename=exercise_strings8

INTRODUCTION TO PYTHON

 Python is an interpreted scripting language


 Python is a widely used general-purpose, high level programming language. It
was initially designed by Guido van Rossum in 1991 and developed by Python
Software Foundation.
 The simple syntax of Python has made it a great tool for embedding in other
languages.
 This syntax also makes it possible to create and deploy Python applications
quickly, with minimal debugging.
 Like the other languages, Python is also fully extensible, providing the ability
to quickly add purpose-specific features simply by adding pre-written
modules.

Page No : 1 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 Python is included in the default installation of Enterprise Linux.
 It was mainly developed for emphasis on code readabil ity, and its syntax
allows programmers to express concepts in fewer lines of code.
 A programming language with strong similarities to PERL, but with powerful
typing and object oriented features.
 Commonly used for producing HTML content on websites. Grea t for text
files.
 Useful built-in types (Tuples, lists, dictionaries).
 Databases: Python provides interfaces to all major commercial databases.
 Clean syntax, powerful extensions.
 It can be used as a scripting language or can be compiled to byte -code for
building large applications.
 Very high-level dynamic data types and supports dynamic type checking.
 Supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java.

There are two major Python versions- Python 2 and Python 3. Both are quite
different.

Finding an Interpreter

Windows:There are many interpreters available freely to run Python scripts like
IDLE ( Integrated Development Environment ) which is installed when you install
the python software from http://python.org/

Linux:For Linux, Python comes bundled with the linux.

Important differences between Python 2.x and Python 3.x with examples
 Division operator
 print function
 Unicode
 xrange
 Error Handling
 _future_ module
Python 2.x Python 3.x
Division Integer division given Integer division given
Operator rounded output exact output
print 7 / 5 gives 1 print 7 / 5 gives 1.4
instead of 1.4
Print Uses the syntax print Uses the syntax print()
Unicode Python 2 uses ASCII Python 3 uses Unicode
format code

Page No : 2 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
xrange It is supported It is supported in the for x in
format of range() range(1, 5):
print(x)

Error Handling try: try:


trying_to_check_error trying_to_check_error
except NameError, err: except NameError as err:
# 'as' is needed in
# as is not required in Python 3.x
2.0 print (err, 'Error
Caused')

_future_module
The idea of
__future__
module is to help
in migration.

_future_module:
This is basically not a difference between two version, but u seful thing to mention
here. The idea of __future__ module is to help in migration. We can use Python 3.x
If we are planning Python 3.x support in our 2.x code,we can ise _future_ imports it
in our code.
For example, in below Python 2.x code, we use Python 3.x’s integer division
behavior using __future__ module
# In below python 2.x code, division works
# same as Python 3.x because we use __future__
from __future__ import division

print 7 / 5
print -7 / 5
Output :
1.4
-1.4
Another example where we use brackets in Python 2.x using __future__ module
from __future__ import print_function

print('GeeksforGeeks')

Unicode
Unicode is an entirely new idea in setting up binary codes for text or script characters.

Page No : 3 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Before Unicode was invented, there were hundreds of different encoding systems for
assigning these numbers. No single encoding could contain enough characters.
Unicode provides a unique number for every character and so you do not have this
problem if you use Unicode
Currently, the Unicode standard contains 34,168 distinct coded characters derived
from 24 supported language scripts. These characters cover the principal written
languages of the world.

Python Keywords
 Keywords are the reserved words in Python.
 A keyword cannot be used as a variable name, function name or any other
identifier.
 They are used to define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.3.

Keywords in Python programming language


False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Python Identifiers
Identifier is the name given to entities like class, functions, vari ables etc. in Python.
It helps differentiating one entity from another.

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). Names 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
perfectly fine.
3. Keywords cannot be used as identifiers.
4. special symbols like !, @, #, $, % etc. cannot be used in defining i dentifiers
5. Identifiers can be of any length
6. Underscore is the only allowed special character

Page No : 4 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement. if statement, for statement, while
statement etc. are other kinds of statements in Python.

Multi-line statement
In Python, end of a statement is marked by a newline character. But a statement can
be extended over multiple lines with the line continuation character (\).

Explicit Line Continuation is done by (\)

Example

a=1+2+3+\
4+5+6+\
7+8+9
print(a)

Output = 45

Implicit Line continuation is done by parentheses ( ), brackets [ ] and braces { }


>>> a = [1+2+3
+4+5+6]
>>> print(a)
[21]
>>> a={1+2+
3+4+5}
>>> print(a)
{15}
Multiple statements can be given in a single line using semicolons

a = 1; b = 2; c = 3

Python Indentation

Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation.
Indentation can be ignored in line continuation. But it's a good idea to always indent.
It makes the code more readable.
Incorrect indentation will result into IndentationError.
if True:
print('Hello')
a=5

Page No : 5 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
and
if True: print('Hello'); a = 5
Python Comments

Comments are used for better understanding of a program. Python Interpreter ignores
comment.
Single Line comment si represented by #
Multiple Line comment is represented by triple quotes, either ''' or """.

Example

"""This is also a
perfect example of
multi-line comments"""

Variable
Variable is a named location used to store data in the memory. Each variable must
have a unique name called Identifier. Variables acts as a container that hold data
which can be changed later throughout programming.

Declaring Variables in Python


a=10
b=10.5
name=”python”
a1=b1=c1=10

OUTPUT
>>> a=10
>>> b=10.5
>>> name="python"
>>> print(a,b,name)
10 10.5 python

Create a program in python and execute it

Page No : 6 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

A window will be opened. Type the python commands one by one and save it with
the extension .py. Run the program by pressing F5

Constants
A constant is a type of variable whose value cannot be changed.
Assigning value to a constant in Python
In Python, constants are usually declared and assign ed on a module. Here, the
module means a new file containing variables, functions etc which is imported to
main file. Inside the module, constants are written in all capital letters and
underscores separating the words.
Create a file called as constants.py

PI = 3.14
GRAVITY = 9.8

Page No : 7 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Save as constant.py

Create another file called as main.py

Invoke the constants created in an another file using the import command

import constant
print(constant.PI)
print(constant.GRAVITY)

save the file and run


OUTPUT
3.14
9.8

Literals

Literals can be defined as a data that is given in a variable or constant.

Numeric Literals
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
Int(signed Long(long float(floating
Complex(complex)
integers) integers) point)
Integers of
Numbers( can be
unlimited size Real numbers In the form of a+bj where a
both positive and
followed by with both integer forms the real part and b
negative) with no
lowercase or and fractional part forms the imaginary part of
fractional
uppercase L eg: eg: -26.2 complex number. eg: 3.14j
part.eg: 100
87032845L
Program No : 1
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal

Output No : 1
10 100 200 300

Page No : 8 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
10.5 150.0
(2+3.14j) 3.14 2.0

Explanation
When the variables are printed all are converted into decimal values.
x.imag and x.real are used to extract the real and imaginary values from the complex
number.

String literals
A string literal is a sequence of characters surrounded by quotes. Strings can be
represented by single, double or triple quotes.
A character literal is a single character surrounded by single or double quotes.
Single line String- Strings that are terminated within a single line are known as
Single line Strings.
Multi line String- A piece of text that is spread along multiple lines is known as
Multiple line String.
There are two ways to create Multiline Strings:
1). Adding black slash at the end of each line.
2) Using triple quotation marks:-

Program No : 2

strings = "This is Python"


char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"
text1 = "hello\
user"
str2 = """welcome
to
SSSIT"""

print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
print (str2)
print(text1)

Output No : 2

Page No : 9 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
This is Python
C
This is a multiline string with more than one line code.
Ünicöde
raw \n string
welcome
to
SSSIT
hellouser

Boolean literals
A Boolean literal can have any of the two values: True or False .
Program No : 3

x = (1 == True)
y = (0 == False)
a = True + 4
b = False + 10

print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)

Output No : 3

x is True
y is True
a: 5
b: 10

Explanation

In Python there are only 2 Boolean values called as True and false. True represents 1
and False Represents 0

Special Literals in Python

Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also used for end of lists
in Python.

Page No : 10 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
val1=10
val2=None
print(val1)
print (val2)
Eg:
====== RESTART: C:/Users/MCA/AppData/Local/Programs/samples/special.py
10
None

Python Operators

Operators are particular symbols that are used to perform operations on operands. It
returns result that can be used in application.

Types of Operators
Python supports the following operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Membership Operators.
6. Identity Operators.
7. Bitwise Operators.
Arithmetic Operators
The following table contains the arithmetic operators that are used to perform
arithmetic operations.
Operators Description
// Perform Floor division(gives integer value after division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division(Modulus)
** Perform exponent(raise to power)

Relational Operators
The following table contains the relational operators that are used to check relations.
Operators Description
< Less than
> Greater than

Page No : 11 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
<> Not equal to(similar to !=)

Assignment Operators
The following table contains the assignment operators that are used to assign values
to the variables.
Operators Description
= Assignment
/= Divide and Assign
+= Add and assign
-= Subtract and Assign
*= Multiply and assign
%= Modulus and assign
**= Exponent and assign
//= Floor division and assign

Logical Operators
The following table contains the arithmetic operators that are used to perform
arithmetic operations.
Operators Description
and Logical AND(When both conditions are true output will be true)
or Logical OR (If any one condition is true output will be true)
not Logical NOT(Compliment the condition i.e., reverse)

Membership Operators
The following table contains the membership operators.
Operators Description
in Returns true if a variable is in sequence of another variable, else false.
not in Returns true if a variable is not in sequence of another variable, else false.
Program No : 4

a=10
b=20
list=[10,20,30,40,50];
if (a in list):

Page No : 12 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print ("a is in given list" )
else:
print ("a is not in given list")
if(b not in list):
print ("b is not given in list")
else:
print ("b is given in list")
Output No : 4

a is in given list
b is given in list

Identity Operators
The following table contains the identity operators.
Operators Description
is Returns true if identity of two operands are same, else false
is not Returns true if identity of two operands are not same, else false.

Program No : 5

a=20
b=20
if( a is b):
print ("a,b have same identity ")
else:
print ("a, b are different ")
b=10
if( a is not b):
print ("a,b have different identity ")
else:
print ("a,b have same identity")

Output No : 5

a,b have same identity


a,b have different identity

Python Data Types

Data Types in Python are


 Python Numbers
 Python List

Page No : 13 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 Python Tuple
 Python Strings
 Python Set

Every value in Python has a datatype. Since everything is an object in Python


programming, data types are actually classes and variables are instance (object) of
these classes.

Python Numbers
Integers, Floating point numbers and complex numbers falls under Python numbers
category. They are defined as int ,float and complex class in Python.

 Integers can be of any length, it is only limited by the memory available.


 A Floating point number is accurate up to 15 decimal places. Integer and
Floating points are separated by decimal points.
 1 is integer, 1.0 is Floating point number.
 Complex numbers are written in the form, x + yj , where x is the real part and
y is the imaginary part.
 The type() function determines the type of class a variable belong to
 The isinstance() function is used to check if an object belongs to a particular
class.
 Class can be int, float, complex.

Program No : 6
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
print(isinstance(1+4j,complex))

Output No : 6
C:/Users/MCA/AppData/Local/Programs/Python/sample programs/num.py =
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
True

Python List
 List is an ordered sequence of items.
 It is one of the most used datatype in Python and is very Flexible.

Page No : 14 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 All the items in a list do not need to be of the same type.
 List is a collection of Heterogenous data types
 The slicing operator [ ] can be used to extract an item or a range of items from
a list. Index starts form 0 in Python.
 Lists are mutable, meaning, value of elements of a list can be altered

Declaration of List
<list_name>=[value1,value2,value3,...,valuen];
a = [1, 2.2, 'python']

Accessing a List
<list_name>[index]
Program No : 7

list = [5,'program', 1+3j]


print(list)
list[2]="hello"
print(list)

Output No : 7

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/list1.py
[5, 'program', (1+3j)]
[5, 'program', 'hello']

Python Tuple
 Tuple is an ordered sequence of items same as list.
 The only difference is that tuples are immutable.
 Tuples once created cannot be modified
 Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically.
 It is defined within parentheses () where items are separated by commas.

Program No : 8

t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# generates error since it does not support assignment

Page No : 15 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
t[0] = 100
print(t[0])

Output No : 8
t[1] = program
t[0:3] = (5, 'program', (1+3j))

Traceback (most recent call last):


File "C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/tuple.py", line 6, in <module>
t[0] = 100
TypeError: 'tuple' object does not support item assignment

Python Strings
 String is sequence of Unicode characters.
 Single quotes or double quotes are used to represent strings.
 Multi-line strings can be denoted using triple quotes, ''' or """
 Strings are immutable in Python

Program No : 9

s = 'Hello world!'
print("s[4] = ", s[4])
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'

Output No : 9

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/string.py
s[4] = o
s[6:11] = world

Traceback (most recent call last):


File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/string.py",
line 6, in <module>
s[5] ='d'
TypeError: 'str' object does not support item assignment

Python Set a={6,7,8}


Set is an unordered collection of unique items.

Page No : 16 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Set is defined by values separated by comma inside braces { }.
Items in a set are not ordered.
We can perform set operations like union, intersection on two sets. Set have unique
values. They eliminate duplicates.
Since, set are unordered collection, indexing has no meaning. Hence the sli cing
operator [] does not work.

Program No : 10

a = {5,2,3,1,4}
print("a = ", a)
print(type(a))
print(a[0])

Output No : 10

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/set.py =
a = {1, 2, 3, 4, 5}
<class 'set'>

Traceback (most recent call last):


File "C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/set.py", line 4, in <module>
print(a[0])
TypeError: 'set' object does not support indexing

Python Dictionary

Dictionary is an unordered collection of key-value pairs.


It is generally used when we have a huge amount of data.
Dictionaries are optimized for retrieving data.
The key value has to be known to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value .
Key and value can be of any type.

Program No : 11

d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);

Page No : 17 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
# Generates error
#print("d[2] = ", d[2]);

Output No : 11

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/dict.py =
<class 'dict'>
d[1] = value
d['key'] = 2

Traceback (most recent call last):


File "C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/dict.py", line 6, in <module>
print("d[2] = ", d[2]);
KeyError: 2

CONDITIONAL STATEMENTS

Decision making process are carried out using conditional Statements.


The Python if statement is a statement which is used to test specified condition
The if statement executes only when specified condition is true.
There are various types of if statements in Python.
 if statement
 if-else statement
 nested if statement
Python if Statement Syntax
if test expression:
statement(s)

In Python, the body of the if statement is


indicated by the indentation. Body starts
with an indentation and the first
unindented line marks the end.
Program No : 12

# voting eligibity using IF structure


age = int(input("Enter the Age : "));
if age >= 18:
print("\n Eligible to Vote ")

Output No : 12

Page No : 18 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Age : 21

Eligible to Vote

Python if else Statement Syntax

if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test
expression and will execute body of if
only when test condition is True .
If the condition is False , body of else is
executed. Indentation is used to separate
the blocks.
Program No : 13

# voting eligibity using IF structure


age = int(input("Enter the Age"));
if age >= 18:
print("\n Eligible to Vote ")
else:
print("\n Not Eligible to Vote ")

Output No : 13

Enter the Age12

Not Eligible to Vote

Enter the Age24

Eligible to Vote

Python if...elif...else Statement

if test expression:
Body of if

Page No : 19 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
elif test expression:
Body of elif

The elif is short for else if. It allows


us to check for multiple expressions.
If the condition for if is False , it
checks the condition of the next elif
block and so on.
If all the conditions are False , body
of else is executed.
Only one block among the several
if...elif...else blocks is executed
according to the condition.
The if block can have only one else
block. But it can have multiple elif
blocks.
An if … elif … elif … sequence is a
substitute for the switch or case
statements found in other
languages.
Program No : 14

num = int(input("Enter the Number"));


if num > 0:
print("\n Number is positive ")
elif num < 0:
print("\n Number is Negative")
else:
print("\n Number is Zero ")

Output No : 14

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Number1

Number is positive
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Number0

Number is Zero

Page No : 20 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Number-34

Number is Negative

LOOPING AND CONTROL STATEMENTS

Looping statements are used for executing a set of statements for a pr edefined times.

Types of Loop
For Loop
While Loop

For Loop
Python for loop is used to iterate the elements of a collection in the order that they
appear. This collection can be a sequence(list or string). Loop continues until we
reach the last item in the sequence.

Python For Loop Syntax


for <variable> in <sequence>:

Program No : 15

# Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)

Page No : 21 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Output No : 15

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample programs/for.py


The sum is 48

The range() function


Range function is used to generate a sequence of numbers. range(10) will generate
numbers from 0 to 9 (10 numbers).
Range function can define the start, stop and step size as range(start,stop,step size) .
step size defaults to 1 if not provided.

Program No : 16

# sum of n natural numbers


sum = 0
n= int(input("Enter the value of N : "))
# iterate over the list
for val in range(1,n):
sum = sum+val
print("The sum is", sum)

Output No : 16

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/for.py =
Enter the value of N : 5
The sum is 10

Program No : 17

# display odd numbers using range function


n= int(input("Enter the value of N : "))
# iterate over the list
for val in range(1,n,2):
print("\n", val)

Output No : 17

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/for.py =
Enter the value of N : 10

Page No : 22 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

7
9

for loop with else


A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.

Program No : 18

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

Output No : 18

= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/for.py =
0
1
5
No items left.

While Loop

The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

Syntax of while Loop in Python


while test_expression:
Body of while

Page No : 23 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False .

Program No : 19

# Program to add natural


# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("\n The Sum of Natural Numbers upto", n, "is =", sum)

Output No : 19

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/while.py
Enter n: 10

The Sum of Natural Numbers upto 10 is = 55

While loop with else part

Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False . The
while loop can be terminated with a
break statement.

Page No : 24 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

Program No : 20

# Program to add natural


# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
else:
print("\n The Sum of Natural Numbers upto", n, "is =", sum)
print("While Loop Over")

Output No : 20

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/while.py
Enter n: 5

The Sum of Natural Numbers upto 5 is = 15


While Loop Over

Python Break and Continue Statements

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

Python 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 break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

Page No : 25 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

Program No : 21

for i in [1,2,3,4,5]:
if i==4:
print ("Element found")
break
print (i)

Output No : 21

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/continue.py
Element found
4

Continue Statement
It returns the control to the beginning of the while loop.. The continue statement
rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram

Page No : 26 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

for letter in 'Python': # First Example


if letter == 'h':
continue
print ('Current Letter :', letter)

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Example

STRING MANIPULATION

 String is a sequence of Unicode characters enclosed within single or double


quotes
 Python does not support a character type; these are treated as strings of length
one, thus also considered a substring.
 To access substrings, use the square brackets for slicing along with the index
or indices to obtain your substring.
 String pythons are immutable.(error : It does not support assignment)
o a = 'Geeks'
o print a # output is displayed
o a[2] = 'E'
o print a # causes error
 Strings in Pythons can be appended
o a = 'Geeks'
o print a # output is displayed
o a = a + 'for'a
o print a # works fine

Page No : 27 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 Concatenation of strings are created using + operator

String Creation
Strings can be created by enclosing characters inside a single quote or double quotes

Example
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

Accessing Strings:
 In Python, Strings are stored as individual characters in a contiguous memory
location.
 The benefit of using String is that it can be accessed from both the directions
in forward and backward.
 Both forward as well as backward indexing are provided using Strings in
Python.
o Forward indexing starts with 0,1,2,3,....
o Backward indexing starts with -1,-2,-3,-4,....

Printing of single quote or double quote on screen


It can be done in the following two ways
 First one is to use escape character to display the additional quote.
 The second way is by using mix quote, i.e., when we want to print single
quote then using double quotes as delimiters and vice -versa.

\newline Backslash and newline ignored


\\ Backslash
\' Single quote
\" Double quote

Page No : 28 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Program No : 22
print( "Hi Mr Ram.")
# use of escape sequence
print ("He said, \"Welcome to the Show\"")
print ('Hey so happy to be here')
# use of mix quotes
print ('Getting Excited, "Loving it"' )

Output No : 22

Hi Mr Ram.
He said, "Welcome to the Show"
Hey so happy to be here
Getting Excited, "Loving it"

Program No : 23
Simple program to retrieve String in reverse as well as normal form.

name="MCA"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print (name[i],"\t",name[n])
i= i+1

Output No : 23
C:/Users/MCA/AppData/Local/Programs/Python/sample programs/str1.py
M A
C C
A M

Strings Operators
There are basically 3 types of Operators supported by String:
1. Basic Operators.
2. Membership Operators.
3. Relational Operators.
https://py3.codeskulptor.org/#user305_tw0W4ofIHP_0.py

Basic Operators:
There are two types of basic operators in String. They are "+" and
"*".
String Concatenation Operator :(+)
The concatenation operator (+) concatenate two Strings and forms a new String

Page No : 29 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

print ("MCA" + "DEPARTMENT")


print('mca'+'department')
print (1+3)
print(10.4+11.5)
print("a"+1)
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/str1.py
MCADEPARTMENT
mcadepartment
4
21.9
Traceback (most recent call last):
File "C:/Users/MCA/AppData/Local/Programs/Python/sample programs/str1.py",
line 5, in <module>
print("a"+1)
TypeError: must be str, not int

Replication Operator: (*)


 Replication operator uses two parameter for operation. One is the integer
value and the other one is the String.
 The Replication operator is used to repeat a string number of times. The string
will be repeated the number of times which is given by the integer value.
 Replication operator can be used in any way i.e., int * string or string * int.
Both the parameters passed cannot be of same type.
o print(5 * "MCA")
o print ("MCA" * 5)

Membership Operators
 Membership Operators are already discussed in the Operators section. Let see
with context of String.
 There are two types of Membership operators:
o in:"in" operator return true if a character or the entire substring is
present in the specified string, otherwise false.
o not in:"not in" operator return true if a character or entire substring
does not exist in the specified string, otherwise false.

Program No : 24

str1="javatpoint"
str2='sssit'
str3="seomount"
str4='java'

Page No : 30 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
st5="it"
str6="seo"
print(str4 in str1)
print(st5 in str2)
print(str6 in str3)
print(str4 not in str1)
print(str1 not in str4)

Output No : 24

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/str1.py
True
True
True
False
True

Relational Operators:
All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings.
The Strings are compared based on the ASCII value or Unicode(i.e., dictionary
Order).
Eg:
>>> "RAJAT"=="RAJAT"
True
>>> "afsha">='Afsha'
True
>>> "Z"<>"z"
True

Slice Notation:
String slice can be defined as substring which is the part of string. Therefore further
substring can be obtained from a string.
There can be many forms to slice a string. As string can be accessed or indexed from
both the direction and hence string can also be sliced from both the direction tha t is
left and right.
Syntax:
<string_name>[startIndex:endIndex:Stepvalue],
<string_name>[:endIndex],
<string_name>[startIndex:]
Program No : 25

Page No : 31 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

str="Nikhil"
str[0:6]
print(str[0:3])
print(str[2:5])
print(str[:6])
print(str[3:])

Output No : 25
Nik
khi
Nikhil
Hil

How to change or delete a string?

Strings are immutable.


This means that elements of a string cannot be changed once they have been
assigned.
We can simply reassign different strings to the same name.

a="raja"
a="ram"
print(a)
del a
print(a)

Line 48: NameError: name 'a' is not defined

Python String Formatting

The format() Method for Formatting Strings.


The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contain curly braces {} as
placeholders or replacement fields which get replaced.

Strings and Numbers cannot be combined

Page No : 32 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

TypeError: cannot concatenate 'str' and 'int' objects

But we can combine strings and numbers by using the format() method!

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

O/P

I want 3 pieces of item 567 for 49.95 dollars.


You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

O/P

I want to pay 49.95 dollars for 3 pieces of item 567.

Page No : 33 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

String Functions and Methods:


There are many predefined or built in functions in String. They are as follows:
It capitalizes the first character of 'abc'.capitalize() Abc
capitalize()
the String.
msg = "MISSISIPPI"; 3
Counts number of times substring substr1 = "I"; 2
count(string,begin,end) occurs in a String between begin print (msg.count(substr1, 4, 16))
and end index. substr2 = "P";
print (msg.count(substr2))
string1="Welcome to SSSIT"; True
substring1="SSSIT"; False
substring2="to"; False
substring3="of"; False
Returns a Boolean value if the
print (string1.endswith(substring1));
endswith(suffix ,begin=0,end=n) string terminates with given suffix
print
between begin and end.
(string1.endswith(substring2,2,16));
print
(string1.endswith(substring3,2,19));
print (string1.endswith(substring3));
str="Welcome to SSSIT"; 3
It returns the index value of the substr1="come"; 8
string where substring is found substr2="to"; 3
find(substring ,beginIndex, endIndex) between begin index and end print (str.find(substr1) ) ; -1
index. If find option fails it result print (str.find(substr2));
in -1 print (str.find(substr1,3,10));
print (str.find(substr2,15));

Page No : 34 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
str="Welcome to SSSIT"; 3
substr1="come"; 8
substr2="to"; 3
print (str.index(substr1) ) ; Traceback (most recent
print (str.index(substr2)); call last):
print (str.index(substr1,3,10)); File
print (str.index(substr2,15)); "C:/Users/Nirmalaa/Ap
Same as find() except it raises an
index(substring, beginIndex, pData/Local/Programs/
exception if string is not found. If
endIndex) Python/Python36-
index option fails it raises an error
32/sample
programs/string1.py",
line 7, in <module>
print
(str.index(substr2,12));
ValueError: substring
not found
It returns True if characters in the str="Welcome to sssit"; False
string are alphanumeric i.e., print (str.isalnum()); True
isalnum() alphabets or numbers and there is str1="Python47";
at least 1 character. Otherwise it print (str1.isalnum());
returns False.
string1="HelloPython"; # Even True
It returns True when all the
space is not allowed False
characters are alphabets and there
isalpha() print (string1.isalpha());
is at least one character, otherwise
string2="This is Python2.7.4"
False.
print (string2.isalpha())
isdigit() It returns True if all the characters string1="HelloPython"; False

Page No : 35 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
are digit and there is at least one print (string1.isdigit()) True
character, otherwise False. string2="98564738"
print (string2.isdigit())
string1="Hello Python"; False
It returns True if the characters of print(string1.islower()) True
islower() a string are in lower case, string2="welcome to "
otherwise False. print (string2.islower())

string1="Hello Python"; False


It returns False if characters of a print string1.isupper(); True
isupper() string are in Upper case, otherwise string2="WELCOME TO"
False. print string2.isupper();

string1=" "; True


print (string1.isspace()) False
It returns True if the characters of
string2="WELCOME TO WORLD
isspace() a string are whitespace, otherwise
OF PYT"
false.
print (string2.isspace())

string1=" "; 4
print (len(string1)); 16
len(string) len() returns the length of a string. string2="WELCOME TO SSSIT"
print (len(string2));

string1="Hello Python"; hello python


Converts all the characters of a
lower() print (string1.lower()) welcome to sssit
string to Lower case.
string2="WELCOME TO SSSIT"

Page No : 36 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print (string2.lower());

string1="Hello Python"; HELLO PYTHON


Converts all the characters of a
upper() print (string1.upper()); WELCOME TO SSSIT
string to Upper Case.

string1="Hello Python"; True


Returns a Boolean value if the print string1.startswith('Hello'); True
startswith(str ,begin=0,end=n) string starts with given str string2="welcome to SSSIT"
between begin and end. print string2.startswith('come',3,7);

string1="Hello Python"; hELLOpYTHON


print (string1.swapcase()); WELCOME TO sssit
Inverts case of all characters in a
swapcase() string2="welcome to SSSIT"
string.
print (string2.swapcase());

string1=" Hello Python"; Hello Python


Remove all leading whitespace of print (string1.lstrip()); welcome to world to
a string. It can also be used to string2="@@@@@@@@welcome SSSIT
lstrip()
remove particular character from to SSSIT"
leading. print (string2.lstrip('@'));

string1=" Hello Python "; Hello Python


Remove all trailing whitespace of
print (string1.rstrip()); @welcome to SSSIT
a string. It can also be used to
rstrip() string2="@welcome to SSSIT!!!"
remove particular character from
print (string2.rstrip('!'));
trailing.

Page No : 37 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Remove all trailing & leading string1=" Hello Python "; Hello Python
whitespace of a string. It can also print (string1.strip()); @welcome to SSSIT
strip()
be used to remove particular
character from trailing.

Page No : 38 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
The constants defined in this module are:
string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase constants
described below. This value is not locale-dependent.
string.ascii_lowercase
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale -
dependent and will not change.
string.ascii_uppercase
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is
not locale-dependent and will not change.
string.digits
The string '0123456789'.
string.hexdigits
The string '0123456789abcdefABCDEF'.
string.octdigits
The string '01234567'.
string.punctuation
String of ASCII characters which are considered punctuation characters in the
C locale.
string.printable
String of ASCII characters which are considered printable. This is a
combination of digits, ascii_letters, punctuation, and whitespace.
string.whitespace
A string containing all ASCII characters that are considered whitespace. This
includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

LISTS

 Python lists are the data structure that is capable of holding different type of data.
 Python lists are mutable i.e., Python will not create a new list if we modify an
element in the list.
 It is a container that holds other objects in a given order.
 Different operation like insertion and deletion can be performed on lists.
 A list can be composed by storing a sequence of different type of values separated
by commas.
 A python list is enclosed between square([]) brackets and each item is separated
by a comma.

The elements are stored in the index basis with starting index as 0.
eg:
1. data1=[1,2,3,4];
2. data2=['x','y','z'];
3. data3=[12.5,11.6];

Page No : 39 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
4. data4=['raman','rahul'];
5. data5=[];
6. data6=['abhinav',10,56.4,'a'];

Methods of List objects


Calls to list methods have the list they operate on appear before the method
name separated by a dot, e.g. L.reverse()

Program No : 26

# Creation of List
L = ['yellow', 'red', 'blue', 'green', 'black']
print (L)

# Accessing or Indexing
print (L[0])

#Slicing
print(L[1:4])
print(L[2:])
print(L[:2])
print(L[-1])
print(L[1:-1])

#length of the List


print(len(L))
print(sorted(L))

# appending an ietm into the List


L.append("Pink")
print(L)

#inserting element inbetween by specifying the index


L.insert(4,"White")
print(L)

#extends - grow list as that of others


L2 = ['purple', 'grey', 'violet']
L.extend(L2)
print(L)

#Remove - remove first item in list with value "white" based on value
L.remove("White")

Page No : 40 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(L)

# Remove an item from a list given its index instead of its value
del L[0]
print(L)

# pop - removes last item from the list


L.pop()
print(L)

#pops element based on index provided


L.pop(1)
print(L)

#reversing the List


L.reverse()
print(L)

#Search list and return number of instances found - count


print(L.count("purple"))

Output No : 26

RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/list2.py
['yellow', 'red', 'blue', 'green', 'black']
yellow
['red', 'blue', 'green']
['blue', 'green', 'black']
['yellow', 'red']
black
['red', 'blue', 'green']
5
['black', 'blue', 'green', 'red', 'yellow']
['yellow', 'red', 'blue', 'green', 'black', 'Pink']
['yellow', 'red', 'blue', 'green', 'White', 'black', 'Pink']
['yellow', 'red', 'blue', 'green', 'White', 'black', 'Pink', 'purple', 'grey', 'violet']
['yellow', 'red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey', 'violet']
['red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey', 'violet']
['red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey']
['red', 'green', 'black', 'Pink', 'purple', 'grey']
['grey', 'purple', 'Pink', 'black', 'green', 'red']

Page No : 41 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Program No : 27
Write a Python program to check whether a list contains a sublist.

LL=[]
SL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)

N = int(input("Enter the Number of elements in sublist :"))


for i in range(0,N):
item = int(input("Enter Elements for List :"))
SL.append(item)
print(LL)
print(SL)

sub_set = False
if SL == []:
sub_set = True
elif SL == LL:
sub_set = True
elif len(SL) > len(LL):
sub_set = False
else:
for i in range(len(LL)):
if LL[i] == SL[0]:
n=1
while (n < len(SL)) and (LL[i+n] == SL[n]):
n += 1
if n == len(SL):
sub_set = True

print(sub_set)

Output No : 27

RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Pyt hon36-32/sample


programs/list2.py
Enter the Number of elements in List :6
Enter Elements for List :1
Enter Elements for List :2

Page No : 42 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Enter Elements for List :3
Enter Elements for List :4
Enter Elements for List :5
Enter Elements for List :6
Enter the Number of elements in sublist :3
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
True
>>>
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/sample programs/list2.py
Enter the Number of elements in List :5
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
Enter Elements for List :4
Enter Elements for List :5
Enter the Number of elements in sublist :3
Enter Elements for List :6
Enter Elements for List :7
Enter Elements for List :8
[1, 2, 3, 4, 5]
[6, 7, 8]
False

Program No : 28

Write a Python program to count the number of elements in a list within a


specified range.

LL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)
min = int(input("Enter the Minimum Range Value :"))
max = int(input("Enter the Maximum Range Value :"))
ctr = 0
for x in LL:
if min <= x <= max:

Page No : 43 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
ctr += 1
print(" Count of Elements between the range ",min, "and" ,max ,"=",ctr)

Output No : 28

RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -32/sample


programs/list3.py
Enter the Number of elements in List :10
Enter Elements for List :34
Enter Elements for List :12
Enter Elements for List :56
Enter Elements for List :78
Enter Elements for List :23
Enter Elements for List :11
Enter Elements for List :89
Enter Elements for List :90
Enter Elements for List :100
Enter Elements for List :121
Enter the Minimum Range Value :50
Enter the Maximum Range Value :100
Count of Elements between the range 50 and 100 = 5

Program No : 29

Write a Python program to generate all permutations of a list in Python.

import itertools
print(list(itertools.permutations([1,2,3])))

Output No : 29
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -32/sample
programs/list3.py
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

TUPLES
A Tuple is a collection of immutable Python objects separated by commas.
The difference between the two is that we cannot change the elements of a tuple once
it is assigned whereas in a list, elements can b e changed.

Advantages of Tuple over List


Since, tuples are quite similiar to lists, both of them are used in similar situations as
well.

Page No : 44 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
 Tuple are generally used for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
 Tuple will guarantee that it remains write-protected.

Creating a Tuple
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).

Description Sample Input Output


Tuple Creation mytuple = 1,2,3,4 (1, 2, 3, 4)
A tuple is created by placing print(mytuple) (6, 2, 1, 3)
all the items (elements) mytuple1 = (6,2,1,3)
inside a parentheses (), print(mytuple1)
separated by comma. The
parentheses are optional but
is a good practice to write it.

Empty Tuples Creation tup1 = (); ()


The empty tuple is written as print(tup)
two parentheses containing
nothing −

Concatenation of Tuples tuple1 = (0, 1, 2, 3) (0, 1, 2, 3, 'python',


tuple2 = ('python', 'geek') 'geek')
Tuples can be concatenates # Concatenating above two
using + operator print(tuple1 + tuple2)

Nesting of Tuples tuple1 = (0, 1, 2, 3) ((0, 1, 2, 3), ('python',


# Code for creating nested tuple2 = ('python', 'geek') 'geek'))
tuples tuple3 = (tuple1, tuple2)
print(tuple3)

Repetition in Tuples tuple3 = ('python',)*3 ('python', 'python',


Tuples can be repeated print(tuple3) 'python')
using Repetition operator

Page No : 45 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
(*)
Immutable Tuples tuple1 = (0, 1, 2, 3) Traceback (most
#code to test tuple1[0] = 4 recent call last):
that tuples are print(tuple1) File
immutable "C:/Users/MCA/AppD
ata/Local/Programs/P
ython/sample
programs/tuple1.py",
line 5, in <module>
tuple1[0] = 4
TypeError: 'tuple'
object does not
support item
assignment
Slicing a=(1,2,3,4,5,6,7,8) (2, 3, 4)
The slice object initialization # starts from initial index value 1 (2, 4)
takes in 3 arguments with the and ends with final index value - 1 (8, 7, 6, 5, 4, 3, 2, 1)
last one being the optional print(a[1:4]) (8, 6, 4, 2)
index increment. The general #last colon mentions the slicing [2, 3]
method format is: slice(start, increment
stop, increment), and it is #By default, Python sets this
analogous to increment to 1, but that extra colon
start:stop:increment when at the end of the numbers allows us
applied to a list or tuple. to specify the slicing increment
print(a[1:4:2])

#reverse print
print(a[::-1])
#reverse with slicing increment
print(a[::-2])

#using slice
a = [1, 2, 3, 4, 5]
sliceObj = slice(1, 3)
print(a[sliceObj])
In order to delete a tuple, the tuple3 = ( 0, 1) NameError: name
del keyword is used del tuple3 'tuple3' is not defined
print(tuple3)
Built in Tuple Functions
Finding Length of a Tuple tuple2 = ('python', 'program') 2
print(len(tuple2))
Converting a list to a tuple # Code for converting a list and a (0, 1, 2)
string into a tuple ('p', 'y', 't', 'h', 'o', 'n')

Page No : 46 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string
'python'
Using cmp(), max() , min() Maximum element in
tuple1 = ('python', 'good') tuples 1 = python
tuple2 = (4,6,7,1) Maximum element in
tuples 2 = 7
print ('Maximum element in tuples Minimum element in
1 = ' +str(max(tuple1))) tuples 1 = good
print ('Maximum element in tuples Minimum element in
2 = ' +str(max(tuple2))) tuples 2 = 1

print ('Minimum element in tuples 1


= ' +str(min(tuple1)))
print ('Minimum element in tuples 2
= ' +str(min(tuple2)))
Take elements in the tuple ('python', 'good',
and return a new sorted list tuple1 = ('python', 'good','able') 'able')
(does not sort the tuple tuple2 = (4,6,7,1) ['able', 'good',
itself). print(tuple1) 'python']
print(sorted(tuple1)) ('python', 'good',
print(tuple1) 'able')
Return the sum of all tuple2 = (4,6,7,1) 18
elements in the tuple. print(sum(tuple2))

Program No : 30

1. Create a tuple named as TUPLE1 with the following items in the tuple
a. TUPLE1 = (‘tupleexample', False, 3.2, 1)
b. TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o",“d”,"e")
2. Display the TUPLE1, TUPLE2
3. Display the 4th Item from the TUPLE2
4. Display the 4th Item from TUPLE2 using Negative Indexing
5. Check whether the element 3.2 exist in TUPLE1
6. Convert the List1 = [1,2,3,4,5,6] to a Tuple
7. Unpack the TUPLE3 = 4,8,3 into Several variables
8. Count the frequency of the Item “o” from the TUPLE2
9. Display the length of the TUPLE2
10. Reverse the TUPLE2

'''Create a tuple named as TUPLE1 with the following items in the tuple

Page No : 47 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
a. TUPLE1 = (‘tupleexample', False, 3.2, 1)
b. TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o",“d”,"e") '''

TUPLE1 = ("tupleexample", False, 3.2, 1)


TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o","d","e")

'''Display the TUPLE1, TUPLE2'''


print(TUPLE1)
print(TUPLE2)

#Display the 4th Item from the TUPLE2


print(TUPLE2[4])

#Display the 4th Item from TUPLE2 using Negative Indexing


print(TUPLE2[-4])

#Check whether the element 3.2 exist in TUPLE1


print(3.2 in TUPLE1)

#Convert the List1 = [1,2,3,4,5,6] to a Tuple


List1 =[1,2,3,4,5,6]
tuplex = tuple(List1)

print(tuplex)

#Unpack the TUPLE3 = 4,8,3 into Several variables


TUPLE3 = 4,8,3
n1,n2,n3 = TUPLE3
print(n1,n2,n3)

#Count the frequency of the Item “o” from the TUPLE2


print(TUPLE2.count("o"))

#Display the length of the TUPLE2


print(len(TUPLE2))

#Reverse the TUPLE2


y = reversed(TUPLE2)
print(y)
T = tuple(y)
print(T)

Output No : 30

Page No : 48 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------

('tupleexample', False, 3.2, 1)


('p', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'd', 'e')
o
c
True
(1, 2, 3, 4, 5, 6)
483
2
10
<reversed object at 0x01C42B10>
('e', 'd', 'o', 'c', 'n', 'o', 'h', 't', 'y', 'p')

Program No : 31
Write a program in python to add and remove and item from tuple.

tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#direct addiotn of value into a tuple through append or insert is not possible
# no direct methods of insert or append.
#tuplex.append(100)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it will create
a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[5:]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)

# to remove an item from the List


# convert a tuple to a list and remove item
listx = list(tuplex)
# to remove an item from list
listx.remove(1)
print(listx)
# converting back to Tuple

Page No : 49 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
tuplex = tuple(listx)
print(tuplex)

Output No : 31

(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 1, 9, 30)
[4, 6, 2, 8, 3, 15, 20, 25, 9, 30]
(4, 6, 2, 8, 3, 15, 20, 25, 9, 30)

Demonstrate the concept of Slicing


Program No : 32

#Demonstrate the concept of Slicing


#create a tuple
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
#used tuple[start:stop] the start index is inclusive and the stop index
slice1 = tuplex[3:5]
#is exclusive
print(slice1)
#if the start index isn't defined, is taken from the beg inning of the tuple
slice1 = tuplex[:6]
print(slice1)
#if the end index isn't defined, is taken until the end of the tuple
slice1 = tuplex[5:]
print(slice1)
#if neither is defined, returns the full tuple
slice1 = tuplex[:]
print(slice1)
#The indexes can be defined with negative values
slice1 = tuplex[-8:-4]
print(slice1)
#create another tuple
tuplex = tuple("HELLO WORLD")
print(tuplex)
#step specify an increment between the elements to cut of the tuple
#tuple[start:stop:step]
slice1 = tuplex[2:9:2]
print(slice1)
#returns a tuple with a jump every 3 items
slice1 = tuplex[::4]

Page No : 50 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print(slice1)
#when step is negative the jump is made back
slice1 = tuplex[9:2:-4]
print(slice1)

Output No : 32

(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')

DICTIONARIES
 Dictionary is an unordered set of key and value pair.
 It is a container that contains data, enclosed within curly braces.
 The pair i.e., key and value is known as item. The key passed in the item must
be unique.
 The key and the value is separated by a colon(:). This pair is known as item.
 Items are separated from each other by a comma(,).
 Different items are enclosed within a curly brace and this forms Dictionary.
Create a Dictionary
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print (data)

 Dictionary is mutable i.e., value can be updated.


 Key must be unique and immutable. Value is accessed by key. Value can be
updated while key cannot be changed.
 Dictionary is known as Associative array since the Key works as Index and
they are decided by the user.
Python Dictionary Example
1. plant={}
2. plant[1]='Ravi'
3. plant[2]='Manoj'
4. plant['name']='Hari'
5. plant[4]='Om'
6. print plant[2]
7. print plant['name']

Page No : 51 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
8. print plant[1]
9. print plant
Output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}

Accessing Dictionary Values


Since Index is not defined, a Dictionary values can b e accessed by their keys only. It
means, to access dictionary elements key has to be passed, associated to the value.

Python Accessing Dictionary Element Syntax


1. <dictionary_name>[key]
2. </dictionary_name>

Accessing Elements Example


data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
print ("Id of 1st employer is",data1['Id'] )
print ("Id of 2nd employer is",data2['Id'] )
print ("Name of 1st employer:",data1['Name'] )
print ("Profession of 2nd employer:",data2['Profession'] )
Output:
>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer

Updating Python Dictionary Elements


The item i.e., key-value pair can be updated. Updating means new item can be added.
The values can be modified.
Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print (data1)
print (data2)
Output:
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}

Page No : 52 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}

Deleting Python Dictionary Elements Example


del statement is used for performing deletion operation.
An item can be deleted from a dictionary using the key only.
Delete Syntax
1. del <dictionary_name>[key]
2. </dictionary_name>

Whole of the dictionary can also be deleted using the del statement.
Example
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print data
del data
print data #will show an error since dictionary is deleted.
Output:
{100: 'Ram', 101: 'Suraj'}

Traceback (most recent call last):


File "C:/Python27/dict.py", line 5, in
print data
NameError: name 'data' is not defined

Python Dictionary Functions and Methods


Functions Description Code Output
data1={'Id':100, 3
'Name':'Suresh', 3
'Profession':'Developer'}
It returns number of data2={'Id':101,
len(dictionary)
items in a dictionary. 'Name':'Ramesh',
'Profession':'Trainer'}
print(len(data1))
print(len(data2))
dict = {'Name': 'Zara', 'Age': Equivalent String :
It gives the string
7}; {'Age': 7, 'Name':
str(dictionary) representation of a
print ("Equivalent 'Zara'}
dictionary
String : %s" % str (dict))
dict = {'Name': 'Zara', 'Age': Variable Type :
Return the type of 7}; <class 'dict'>
type(dictionary)
the variable print ("Variable Type : %s" %
type (dict)

Page No : 53 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
Python Dictionary Methods
Methods Description Code Output
It returns all data1={100:'Ram', 101:'Suraj', dict_keys([100,
the keys 102:'Alok'} 101, 102])
keys()
element of a print(data1.keys())
dictionary.
It returns all data1={100:'Ram', 101:'Suraj', dict_values(['R
the values 102:'Alok'} am', 'Suraj',
values()
element of a print(data1.values()) 'Alok'])
dictionary.
It returns all data1={100:'Ram', 101:'Suraj', dict_items([(10
the 102:'Alok'} 0, 'Ram'), (101,
items() items(key- print(data1.items()) 'Suraj'), (102,
value pair) of 'Alok')])
a dictionary.
data1={100:'Ram', 101:'Suraj', {100: 'Ram',
It is used to 102:'Alok'} 101: 'Suraj',
add items of data2={103:'Sanjay'} 102: 'Alok',
update(dictionary2) dictionary2 data1.update(data2) 103: 'Sanjay'}
to first print (data1 ) {103: 'Sanjay'}
dictionary. print (data2) >>>

It is used to data1={100:'Ram', 101:'Suraj', {100: 'Ram',


remove all 102:'Alok'} 101: 'Suraj',
items of a print (data1) 102: 'Alok'}
clear() dictionary. It data1.clear() {}
returns an print (data1)
empty
dictionary.
It is used to sequence=('Id' , 'Number' , {'Id': None,
create a new 'Email') 'Number':
dictionary data={} None, 'Email':
from the data1={} None}
sequence data=data.fromkeys(sequence) {'Id': 100,
fromkeys(sequence,val
where print (data) 'Number': 100,
ue1)/
sequence data1=data1.fromkeys(sequen 'Email': 100}
fromkeys(sequence)
elements ce,100)
forms the print (data1 )
key and all
keys share
the

Page No : 54 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
values ?value
1?. In case
value1 is not
give, it set
the values of
keys to be
none.
data={'Id':100 , {'Id': 100,
It returns an
'Name':'Aakash' , 'Age':23} 'Name':
copy() ordered copy
data1=data.copy() 'Aakash', 'Age':
of the data.
print (data1) 23}
It returns the data={'Id':100 , 23
value of the 'Name':'Aakash' , 'Age':23} None
given key. If print (data.get('Age') )
get(key)
key is not print (data.get('Email'))
present it
returns none.

Program No : 33
Write a Python program to concatenate following dictionaries to create a new
one.

dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)

Output No : 33

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Program No : 34
Write a Python program to sort (ascending and descending) a dictionary by
value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)

Page No : 55 Prepared by : M.Nirmala / AP / MCA / HICET


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – I – CORE PYTHON

-----------------------------------------------------------------------------------------------------------------
print('Dictionary in descending order by value : ',sorted_d)

Output No : 34

Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}


Dictionary in ascending order by value : [(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
Dictionary in descending order by value : [(4, 3), (3, 4), (2, 1), (1, 2), (0, 0)]

Page No : 56 Prepared by : M.Nirmala / AP / MCA / HICET

You might also like