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

Python notes 45

Uploaded by

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

Python notes 45

Uploaded by

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

PYTHON PROGRAMMING

Syllabus

MODULE 1

Introduction to Python - The IDLE Python Development Environment - The Python Standard Library - Literals -
Numeric Literals - String Literals - Control Characters - String Formatting - Implicit and Explicit Line Joining Variables
and Identifiers - Variable Assignment and Keyboard Input- Identifier-Keywords and Other Predefined Identifiers in Python
– Operators - Various Operators - Relational Operators-Membership Operators – Boolean Operators - Expression and
Data Types -Operator Precedence and Boolean Expressions - Operator Associativity - Mixed-Type Expression

MODULE 2

Control Structure -Selection Control- If Statement - Indentation in Python - Multi-Way Selection - Iterative Control -
While Statement - Input Error Checking - Infi nite loops - Definite vs. Indefinite Loops

MODULE 3

List Structures - Common List Operations - List Traversal - Lists (Sequences) in Python- Python List Type -
Tuples- Sequences- Nested Lists Iterating Over Lists (Sequences) in Python - For Loops - The Built-in range Function
- Iterating Over List Elements vs. List Index Values-While Loops and Lists (Sequences) - Dictionaries and sets

MODULE 4

Defining Functions - Calling Value-Returning Functions - Calling Non-Value-Returning Functions - Parameter Passing -
Keyword Arguments in Python Default Arguments in Python - Variable Scope - Recursive functions - Exception Handling
-The Propagation of Raised Exceptions - Catching and Handling Exceptions -Exception Handling and User Input

MODULE 5

String Processing - String Traversal - String-Applicable Sequence Operations -String Methods - Using Text Files -
Opening Text Files - Reading Text Files - Writing Text Files

TEXT BOOK

1, Charles Dierbach, Introduction to Computer Science using Python , Wiley First Edition (2015),ISBN-10:
81265560132015

REFERENCE BOOKS

1, Zed A.Shaw, Learn Python the Hard Way Paperback, Pearson Education, Third Edition edition(2017), ISBN-10:
9332582106

2. Paul Barry, Head First Python, O' Reilly Publishers, First Edition, 2010, ISBN:1449382673.
PYTHON PROGRAMMING

UNIT – I

 Python is a dynamic, high level, free open source and interpreted programming language.
 It supports object-oriented programming as well as procedural oriented programming.
 It was initially designed by Guido van Rossum in 1991 at Centrum Wiskunde & Informatica (CWI) which is
situated in Netherland.
 The inspiration for the name came from BBC’s TV Show – ‘Monty Python’s Flying Circus’, as he was a big
fan of the TV show and also he wanted a short, unique and slightly mysterious name for his invention and
hence he named it Python!
 It was mainly developed for emphasis on code readability, and its syntax allows programmers to express
concepts in fewer lines of code.
 Due to its elegance and simplicity, top technology organizations like Dropbox, Google, Quora, Mozilla, Hewlett-
Packard, Qualcomm, IBM, and Cisco have implemented Python.

Features in Python

There are many features in Python, some of which are discussed below –

1. Simplicity
a. Python is its own kind of simple. All you need to know is how the indentations work and you can code
the most complex of problems in the fewer lines of code.
2. Open Source
a. Python is free for anyone to use. You even have the freedom to modify the code of Python to
better your own needs without facing any repercussions.
3. Portability
a. Code writing can be done once and run across different systems without any changes. This makes it
super helpful when a team works on a project.
4. Embedding Properties
a. Python allows the code of other languages such as C, C++ to be embedded, which makes it much more
powerful and versatile.
5. Interpretation
a. As you know, Python is compiled line-by-line, making debugging easier and memory management much
more efficient
6. Library Support
a. Python supports libraries that you can use and get started off to obtain your solutions much faster
and easier. And the community for these libraries is very active and helpful
7. OOPS
a. Object-Oriented concepts help you replicate real-world scenarios in your code and also
provide security to them so that you can obtain a well-made application
8. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython in python. PyQt5 is
the most popular option for creating graphical apps with Python.
9. Dynamically Typed Language:
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don’t need to specify the type
of variable.

Applications:
 Web Development
 Game Development
 Machine Learning and Artificial Intelligence
 Data Science and Data Visualization
 Desktop GUI
 Web Scraping Applications
 Business Applications
 Audio and Video Applications
 CAD Applications
 Embedded Applications

Python – IDLE(Integrated Development and Learning Environment)

IDLE has the following features:

 IDLE is an integrated development environment (IDE) for Python.


 Coded in 100% pure Python, using the tkinter GUI toolkit
 Cross-platform: works mostly the same on Windows, Unix, and macOS

 IDLE can be used to execute a single statement just like Python Shell and also to create, modify, and
execute Python scripts.
 Python shell window (interactive interpreter) with colorizing of code input, output, and error messages

 IDLE provides a fully-featured text editor to create Python script that includes features like syntax
highlighting, autocompletion, and smart indent.

 It also has a debugger with stepping and breakpoints features.


 search within any window, replace within editor windows, and search through multiple files (grep)

To start an IDLE interactive shell, search for the IDLE icon in the start menu and double click on it.

To execute a Python script, create a new file by selecting File -> New File from the menu.
press F5 to run the script in the editor window. The IDLE shell will show the output.

The Python Standard Library:

1. A Python library is a reusable chunk of code that you may want to include in your programs/ projects.
2. These libraries are the collection of modules, classes which can be used easily.
3. A module is a file containing python definition, functions, variables, classes and statements. The extension of
this file is “.py”.
4. The Python Standard Library is a collection of exact syntax, token, and semantics of Python. It comes bundled
with core modle Python distribution. We mentioned this when we began with an introduction.

5. It is written in C, and handles functionality like I/O and other core modules. All this functionality together
makes Python the language it is.

6. More than 200 core modules sit at the heart of the standard library. This library ships with Python.

7. But in addition to this library, you can also access a growing collection of several thousand components from
the Python Package Index (PyPI)
8. “import” command is used to import the library file into our program.

Tlhere are two methods to import library

i. Import <module> : Imports all classes which belongs to that module

Ex: import numpy

Import math

It will import total math module in to the namespace.

ii. from <module>import<object> : It imports only the object which belongs to the module.

Ex: from math import pi

It will import only pi value from math module but not entire module.

Some of the important libraries in python.

1. Matplotlib: It helps with data analyzing, and is a numerical plotting library. We talked about it in Python for
Data Science.
2. Pandas : It provides fast, expressive, and flexible data structures to easily (and intuitively) work with
structured (tabular, multidimensional, potentially heterogeneous) and time-series data.
3. NumPy : It has advanced math functions and a rudimentary scientific computing package.
4. SQLAlchemy :SQLAlchemy is a library with well-known enterprise-level patterns.It was designed for efficient and
high-performing database-access.
5. BeautifulSoup : It may be a bit slow, BeautifulSoup has an excellent XML- and HTML- parsing library for
beginners.

Advantages–

– Its biggest advantage is that we can import its functionality in any program and use it.
– Re-usability is one of the biggest advantages.
– It helps in logically organization of Python code.
– Programming becomes very easy when we use the collection of same types of codes.
– Categorization : same attributes can be stored in one module.

Tokens:
Tokens are the smallest individual unit of a program. Tokens in the python are as follows
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Delimiters

1. Keywords:

 They are the words convey a special meaning to the Python interpreter .

 As these words have specific meaning for interpreter,.


 Reserved words or keywords must not be used for normal identifier names.
Example:

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

2. Identifiers:

Identifiers are generally defined by users. They are used to name a variable, constant, function, class, or array.

Let’s have a look at the rules to declare identifiers:

 Identifiers are always case-sensitive.


 The first letter of an identifier will always be an alphabet, underscore, or the dollar sign.
 No white spaces are allowed.
 Identifiers must not be a keyword
 Can not contain any special characters except underscore(_)

Examples of some valid identifiers:

x,y,Sum , AVERAGEr,a1,_carname,$radius,name_list

3. Literals:

Literals means the value which is assigned to the variable. The value of a literals fixed can not be changed.

Types of literals:
i. String Literal
ii. Numeric Literal
iii. Boolean Literal
iv. Special Literal

i. String Literal :

 The text that is enclosed in a quotes are called string literals.

 Single or double quotes can be used to specify a string literal.

 There are multiple ways to specify string literal that basically forms various types.

Single Line String Literal


When strings are specified in a single line only then, that becomes a single line literal.
Ex: name=’ram’
Gender=”Male”

Multiline String Literal

When we intend to use multiple lines for specifying the string, that becomes a multiline string literal. In order to
accomplish this, backslash ‘\’ is used.

Ex : t = "Hi!\
How are you?"
ii. Numeric Literals:

Numeric literals are of multiple types based on the number type and size.
They are immutable and there are three types of numeric literal :

1. Integer

2. Float

3. Complex.

Integer literal:

 Both positive and negative numbers including 0. There should not be any fractional part.

 Binary literals starts with 0b, Octal literals starts with 0o and Hexadecimal literals starts with 0x.

Examples:
 Binary Literals
a = 0b10100
 Decimal Literal
b = 50
 Octal Literal
c = 0o320
 Hexadecimal Literal
d = 0x12b
print(a,b,c,d)

Output :
20 50 208 299

Float literal:

These are real numbers having both integer and fractional parts.
Example: e = 24.8

f = 45.0

iii. Complex literals:


The numerals will be in the form of a+bj, where ‘a‘ is the real part and ‘b‘ is the complex part.

z = 7 + 5j

# real part is 0 here.

k = 7j

print(z, k)

Output:
(7+5j) 7j

iv. Boolean literals


There are only two Boolean literals in Python. They are true and false.

Example:

a = (1 == True)

b = (1 == False)

c = True + 3

d = False + 7

print("a is", a)

print("b is", b)

print("c:", c)

print("d:", d)

Output

a is True
b is False
c: 4
d: 7

v. Special literal:
None literal is used to denote an absence of a value.
Example:
A= None

4. Operators:

An operator is used to perform specific mathematical or logical operation on values


The values that the operators work on are called operands.

Ex : 10 + num

The value 10, and the variable num are operands. the + (plus) sign is an operator.

Unary Operators:

They require a single operand to perform an operation.

. For eg.
unary +, unary - operator.

UNARY - : To make the value of the number negative: -5


UNARY + : To make the value of the number positive : +5
Binary Operators:
They require two operands to perform an operation.
Python divides the operators in the following groups:

 Arithmetic operators
 Relational or Comparison Operators
 Assignment operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Arithmetic Operators:

Python supports arithmetic operators that are used to perform the four basic arithmetic operations as
well as modular division, floor division and exponentiation

Relational Operators or Comparison Operators

Relational operator compares the values of the operands on its either side and determines the relationship among them.

Assume the Python variables num1 = 10,

num2 = 0,

num3 = 10, str1 = "Good",

str2 ="Afternoon" for the following examples:


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

Ex: M=10+5

Logical Operators
 There are three logical operators supported by Python. These operators (and, or, not) are to be written in
lower case only.
 The logical operator evaluates to either True or False based on the logical operands on either side.
 Every value is logically either True or False.
 By default, all values are True except None, False 0 (zero)

More Examples:
1. >>> NOT(5>10)
TRUE
2. >>> (10<5) OR (15>20)
FALSE
Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or not.
Identity operators can also be used to determine whether two variables are referring to the same object or not.
There are two identity operators

Membership Operators
Membership operators are used to check if a value is a member of the given sequence or not.

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 fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off

>> Signed right Shift right by pushing copies of the leftmost bit in from the
shift left, and let the rightmost bits fall off
Example for Bitwise Operators:
a=0b0010
b=0b0011
print(a&b)
Print(15>>2) 1111>>2 0111 0011

Output:
2
3

Delimiters:

They the are symbols used to organize program structure and statements..
{ }, [ ], ( ), , , ; , :

EXPRESSION:
 An expression is defined as a combination of constants, variables, and operators.
 An expression always evaluates to a value.
 A value or a standalone variable is also considered as an expression but a standalone operator is not an
expression.
Example :
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"

Boolean Expression:
A boolean expression is an expression that evaluates to a boolean value. The equality operator, ==, compares two
values and produces a boolean value related to whether the two values are equal to one another.
Example :
x=(5 == 5)
y=(5 == 6)
print(x)
print(y)

Output:
True
False
Precedence of Operators
 Evaluation of the expression is based on precedence of operators.
 When an expression contains different kindsof operators, precedence determines which operator should be
applied first.
 Higher precedence operator is evaluated before the lower precedence operator.
 The unary operators need only one operand, and they have a higher precedence than the binary operators.
 The minus (-) as well as + (plus) operators can act as both unary and binary operators, but not is a unary
logical operator.

The following table lists precedence of all operators from highest to lowest.
Operators Associativity:

 When two operators have the same precedence, associativity helps to determine the order of operations.

 Associativity is the order in which an expression is evaluated that has multiple operators of the same
precedence. Almost all the operators have left-to-right associativity.

Comments:

 Comments are non-executable statements which are ignored by Python interpreter.


 They are used to make the code understandable.
 In Python, comment start with "#" symbol and extends till the end of the physical line.
 Anything written after # in a line is ignored by interpreter.A comment can appear on a line by itself or they
can also be at the end of line.
Example
# This program calculates the sum of two numbers
>>>n1=10
>>>n2=20
>>>sum= n1 + n2 # sum of numbers 10 and 20
>>>print ("sum=", sum)

For adding multi-line comment in a program, we can

Place "#" in front of each line

Use triple quoted string.


EXAMPLE
'''This is a
multiline comment'''

Variables in Python:
 Variables are like containers which are used to store the values for some input,intermediate result of
calculations or the final result.
 Python has no command for declaring a variable.
 A variable is created the moment you first assign a value to it.
 Variables do not need to be declared with any particular type, and can even change type after they have
been set.

Variable naming conventions:

 Variable names are case sensitive. For eg. num and NUM are treated as two differentvariable names.
 Keywords should not be used as the variable names.
 Variable names should be short and meaningful.
 All variable names must begin with a letter or an underscore (_).
 After the first letter, variable names may contain letters and digits (0 to 9) and anunderscore (_),
 no spaces or special characters are allowed.

Examples of valid variable names:


sum, marks1, first_name, _money

Assigning Values To Variables

● We do not need to explicitly declare the variable.


● Variables are declared automatically when they are assigned value.
● The assignment operator (=) is used to assign value to a variable.

EXAMPLES
a=17
name='Rachit'
num=10.5

NOTE : Variables do not need to be declared with any particular type and can evenchange type after they have been s
et

EXAMPLE
num=10
num = 'Raman'

 Assign a single value to several variables simultaneously.


For example:
>>>x=y=z=10

 Assign multiple values to multiple variables in a single statement.


For example:
>>> x,y,z=12, 70.5, "Vikul"

L-value and R-value

 L-value is a value which has an address.


 L-value often represents as identifier.
 R-value refers to data value
EXAMPLE
>>>a=1
# here the variable a refers to as l-value and 1 is the R-value
>>> b = a
# valid, as l-value can appear on right

Output A Variable

The print statement is used to display the value of a variable.

PRINT statement

 The print() function is used to send output to standard output device.


 The print statement is used to value of a variable.
 If an expression is given with the print statement, it first evaluates the expressionand then print it.
 To print more than one item on a single line, comma (,) may be used.
 By default, print uses a single space as a separator and a \n as a terminator(appears at the end of the
string).
 Both of these defaults can be changed to desired values.

Syntax:
print(*objects, [sep=’ ‘ or <separator-string> end=’\n’ or <end-string>])

>>>x="welcome"
>>>print (x)
welcome

>>> x="Year"
>>> y="New"
>>> print(y + x)
NewYear

>>> print('a', 'b', 'c', 'd')


abcd
>>> print('a', 'b', 'c', 'd', sep='@', end='!!')
a@b@c@d!!

 print can also be called with no arguments to print a blank line.


a,b=5,7
print(a)
print()
print(b)

output:
5

7
Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format()
method. This method is visible to any string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using
numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))


print('I love {1} and {0}'.format('bread','butter'))

INPUT A VARIABLE

input statement
 To get input from user interactively, you can use built-in function input().
 input() returns the value which is usually stored in a variable.
 Input function always returns a string value.

Syntax:
Variable name = input(<prompt to be displayed>)

For example:
>>>name = input("What is your name?")

 To input numeric data from input() function we can use typecasting, i.e.,changing the datatype using function.

 The string data accepted from the user can be converted to appropriate numericdata type using int(), float()
and eval() functions


>>>y=int (input("enter your marks"))
m=y+5
print(m)
enter your marks 92
97

DATA TYPES

 Data type states the way the values of that type are stored, the operations that can bedone on that type,
and the range for that type.
 Different types of data like character, integer and numbers with decimals etc. can bestored in variables.
 Different kinds of data require different amount of memory for storage.

Python offers five standard data types:


1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

1. Number
Number data type is used to store Numerical Values.
Python supports three different numerical types
1. integer
2. float point numbers
3. complex numbers
In addition, Booleans are a subtype of integers.

1) Integer: Integer are whole numbers without decimal point. They can be positive or negativewith unlimited length.
For example:
>>>a=20

Integers contain Boolean Type which is a unique data type, consisting of two constants,
True & False.
A Boolean True value is Non-Zero, Non-Null and Non-empty.
For example:
>>>entry=true

2)Floating point numbers: Numbers with fractions or decimal point are called floating point numbers.
Forexample:
>>> k=200.789

c) Complex Numbers: A complex number is an ordered pair of two floating-point numbers denoted by a + bi,where a
and b are the real numbers and i is the imaginary unit. For example:
>>>x=10+5i

For accessing different parts of variable a; we will use a.real and a.imag.
>>>print (x.real, x.imag)
10.0 5.0

2. STRINGS
String is an ordered set of characters enclosed in single or double quotation marks.
Strings are immutable.
Each character can be individually accessed using its index.
Valid string indices are 0,1,2,….upto length-1 in forward direction and -1,-2,-3,….-length in backward direction .

For example:
>>>str="I love Python"
Print(str[2])
Print(str[-1])
Output: l
n

3. LISTS
 A list is a collection of comma-separated values (items) within square brackets.
 Values in the list can be modified, i.e. it is mutable.
 The values that make up a list are called its elements.
 Elements in a list need not be of the same type.
EXAMPLES
list1=[100, 200, 300, 400, 500]
list2=["Raman", 100, 200, 300, "Ashwin"]
list3=["A", "E", "I", "O", "U"]

4. TUPLE

 A tuple is a sequence of comma separated values.


 Values in the tuple cannot be modified, i.e. it is immutable.
 The values that make up a tuple are called its elements.
 Elements in a tuple need not be of the same type.
 The comma separated values can be enclosed in parenthesis but parenthesis are notmandatory.
EXAMPLES
tup1=("Sunday", "Monday", 10, 20)
tup2=("a", "b", "c", "d", "e")
tup3=(1,2,3,4,5,6,7,8,9)

5. DICTIONARY
 Python dictionary is an unordered collection of items where each item is a key: valuepair.
 We can also refer to a dictionary as a mapping between a set of keys and a set ofvalues.
 Each key is separated from its value by a colon (:),the items are separated by commas andthe entire dictionary
is enclosed in curly braces.
 Dictionary is mutable.
 We can add new items or change the value of existing items.
EXAMPLES
dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}
dict2={1: 'robotics', 2:'AR' , 3:'AI' , 4:'VR'}
dict3={'num':10, 1:20}
. We can use the type() function to know the data type of a variable. For example:
>>>num=10
>>> type(num)
<class 'int'>
>>> name='Kapil'
>>> type(name)
<class 'str'>
Mutable and Immutable types:

The python data objects can be broadly categorized into two


Mutable (modifiable)
Immutable(non-modifiable)

Mutable:
The Mutability means that in the same memory address, new value can be stored as and when required.
Mutable types are those whose values can be changed to place.
Mutable types in Python are
Lists, dictionaries and sets.
Ex:
A=[1,2,3]
A[1]=20
It will change the A as [1,20,3]

Immutable :
The immutable types arethose that can never change their value in place. In Python the following are immutable
types
Integers, floating point numbers, Booleans, strings, tuples.

DATA TYPE CONVERSION(Type casting):


It is a conversion of one data type into another data type.
The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically
converts the data type).
For explicit type casting, we use functions:
int ()
float ()
str ()
bool ()

EXAMPLE
>>> x= 158.19
>>> y= int(x)
>>> print (y)
158
EXAMPLE
>
>>>y=float(x)
>>>print y
165.0

Python explicit line joining


When we want to join many logical lines to render a suitable condition, we can use the backslash characters (\). This
character (\) will join the logical lines together as if they are declared in one single line. Such method of joining the
lines using the backslash(\) is known as explicit line joining.
i)There cannot be comment after the backslash character.
>>> a<100 and b>20 | \ #comment
SyntaxError: unexpected character after line continuation character
You get error message if there is any comment after the backslash.

ii)A backslash cannot continue comment.

iii)A backslash can continue only string literals. It cannot continue any other literals type.

>>> str="Happy " \


'new year and '\
"marry Christmas!"
>>> str
'Happy new year and marry Christmas!'
>>> #Using '\' to continue integers literals
>>> i=890 \
234
SyntaxError: invalid syntax

Trying to continue the integer literals using ‘\’ render an error message.

iv) A backslash is illegal everywhere except the in string literals.

Example:
>>> x> 80andx< 100| \

y<101andx < y

True

>>> a<100andb>20| \

a>100andc>100| \

b<50| c>=100

False

Python Implicit line joining

In Python implicit line joining we uses parentheses, square brackets or curly braces to split the expression in multiple
lines. For instance consider the code below.

>>> #Using parentheses

>>> Month=( 'Jan' , 'Feb' , 'Mar' , 'April' , 'May' ,

'June' , 'July' , 'Aug' , 'Sept' ,

'Nov' , 'Dec' )

>>> #Using curly braces

>>> Weekdays={ 'Monday' , 'Tuesday' ,

'Wednesday' , 'Thursday' , 'Friday' ,

'Saturday' , 'Sunday' }

i)There can be comment after the line.

>>> Weekdays={ 'Monday' , 'Tuesday' , #First line

'Wednesday' , 'Thursday' , 'Friday' , #Second line


'Saturday' , 'Sunday' } #third line

ii)Blank lines are allowed to continue.

>>> Var={ #Blank

'new',

'old'}

iii)Triple-quoted strings are also allowed to have continued lines but here there cannot be comment in each line.

>>> tri_str={ """new and old""",

"""Sad and joy""" ,

'''Delight and dismay''' }

>>> tri_str

{'Delight and dismay', 'Sad and joy', 'new and old'}

Assignment :

1. Write a program to input a number and print its cube.


2. Write a program to input two numbers and print their sum and difference.
3. Write a program to read your name and print it ten times.
Unit – II

2.1: Control Structures:

 A program’s control flow is the order in which the program’s code executes.

 The control flow of a Python program is regulated by conditional statements, loops, and function calls.

 Python has three types of control structures:

1. Sequential - default mode


2. Selection - used for decisions and branching
3. Repetition - used for looping, i.e., repeating a piece of code multiple times.
1. Sequential

 Sequential statements are a set of statements whose execution process happens in a sequence.

Example:

## This is a Sequential statement

a=20

b=10

c=a-b

print("Subtraction is : ",c)

Selection/Decision control statements

 In Python, the selection statements are also known as Decision control statements or branching statements.

 The selection statement allows a program to test several conditions and execute instructions based on which
condition is true.

 Some Decision Control Statements are:

1. Simple if
2. if-else
3. nested if
4. if-elif-else

1. Simple if: If statements are control flow statements that help us to run a particular code, but only when a
certain condition is met or satisfied. A simple if only has one condition to check.
Syntax:

If <conditional expression>:

Statement

[statements]
Flow Control:

Example:

n = 10

if n % 2 == 0:

print("n is an even number")

2. if-else: The if-else statement evaluates the condition and if the condition evaluates to True, it carries out
statements indented below if statement, but if the condition is False, then the body of else is executed.

Syntax:
If <conditional expression>:
Statement(s)
else:
statement(s)

Flow Control:

Example:
Check whether the given no is positive or negative.

A=int(input(“Enter a number :”)


if a>0:
print(a,” is positive “) # The statements in if or else blocks must be indented.
Else:
print(a,” is negative”)

Write a program to check whether the given number is even or odd.

n = int(input(“Enter a number : ”)
if n % 2 == 0:
print("n is even")
else:
print("n is odd")

3. nested if: Nested if statements are an if statement inside another if statement.


Syntax:

If condition:
If condition:
statement(s)
else:
statement(s)
else:
statement(s)

Flow Control:
Example: Write a program in python to find the biggest of three numbers

a = int(input(‘Enter a value : “))

b = int(input(‘Enter b value : ‘))

c = int(input(“Enter c value : “))

if a > b:

if a > c:

print("a value is big")

else:

print("c value is big")

elif b > c:

print("b value is big")

else:

print("c is big")

4. if-elif-else: Python evaluates each expression one by one and if a true condition is found the statement(s)
block under that expression will be executed. If no true condition is found the statement(s) block under else
will be executed.

Syntax:
if (condition):

statement

elif (condition):

statement

..

else:

statement

Flow Control:
Example: Program to check whether the given number is positive, negative or zero.

a=int(input(“Enter a number : “))

if a<0:

print(“Given number is Negative “)

elif a==0:

print(“Given number is Zero”)

else:

print(“Given number is Positive “)

Short Hand if statement

 Whenever there is only a single statement to be executed inside the if block then shorthand if can be used.
The statement can be put on the same line as the if statement.

Syntax:
if condition: statements

Example:
# Python program to illustrate short hand if
i = 10
if i< 15: print("i is less than 15")

Output:

i is less than 15

Short Hand if-else statement

 This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.

Syntax:
statement_when_True if condition else statement_when_False

Example:

# Python program to illustrate short hand if-else


i = 10
print(True) if i< 15 else print(False)

Output:

True

2.2: Python Indentation

 Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python,
however, uses indentation.

 A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line.
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.

if i == 5:

break

2.3: Loops OR Iterative Control Structures :

 In Python, the iterative statements are also known as looping statements or repetitive statements. The
iterative statements are used to execute a part of the program repeatedly as long as a given condition is
True.

 Python provides the following iterative statements.

1. while statement
2. for statement

3.

2.3.1: while statement

 In Python, the while statement is used to execute a set of statements repeatedly.

 The while statement is also known as entry control loop statement because in the case of the while statement,
first, the given condition is verified then the execution of statements is determined based on the condition
result.

 Python while loop is used to repeat a block of code until the specified condition is False.

 The while loop is used when we don’t know the number of times the code block has to execute
Syntax:

while condition:

Statements

Flow Control :

Example:

Find the sum of first n natural numbers

n = int(input('Enter n value :": '))

i=1

sum=0

while i<= n:

sum=sum+i
i += 1

print(“Sum = “,sum)

while statement with 'else' clause in Python

 In Python, the else clause can be used with a while statement. The else block is gets executed whenever the
condition of the while statement is evaluated to false. But, if the while loop is terminated with break
statement then else doesn't execute.

Example:

count = int(input('How many times you want to say "Hello": '))


i=1
while i<= count:
if count > 10:
print('I cann\'t say more than 10 times!')
break
print('Hello')
i += 1
else:
print('This is else block of while!!!')
2.3.2: for statement

 In Python, the for statement is used to iterate through a sequence like a list, a tuple, a set, a dictionary, or
a string. The for statement is used to repeat the execution of a set of statements for every element of a
sequence.

Syntax
for <variable> in <sequence>:

Statements

In the above syntax,the variable is stored with each element from the sequence for every iteration.

Flow control

# Python code to illustrate for statement with List

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

for value in my_list:

print(value)

Output:

1.Write a program to print elements of a string.

s=input(“Enter a string : “)
for i in s:
print(i)

Output:

Enter a string: hello

h
e
l
l
o
# Python code to illustrate for statement with Tuple

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

for value in my_tuple:

print(value)

for statement with 'else' clause in Python

 In Python, the else clause can be used with a for a statement. The else block is gets executed whenever the
for statement is does not terminated with a break statement. But, if the for loop is terminated with break
statement, then else block doesn't execute.

# Here, else block is gets executed because break statement does not execute.

n=int(input(‘Enter no.of times ‘))

for i in range(1,n):

if i>10:

print(“n value is more than 10 “)

print(“hello”)

else:

print('This is else block of for!!!')

2.3.3: Loop Control Statements

 break

 continue

 Pass

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.
Syntax:
break

Flow Control:

The working of break statement in for loop and while loop is shown below.

Example: Print the contents of a string

for val in "string":

if val == "i":

break
print(val)

Output:

Program to exit from the loop when an odd number occers

for i in [12, 16, 17, 24,29]:


if i % 2 == 1: # if the number is odd
break # immediately exit theloop
print(i)

Output:

12

16

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:

continue

Flow Control
Example: print the contents of a string except ‘i’

for val in "string":

if val == "i":

continue

print(val)

Output:

pass Statement:

In Python programming, pass is a null statement.

Syntax:

Pass

Example:

sequence = {'p', 'a', 's', 's'}

for val in sequence:

pass
2.3.4 : RANGE() FUNCTION:

 range function is used to iterate the elements in sequencemanner


 range function is used in forloops
 range function makes programmer to index free while iterating theloops
RANGE() FUNCTION ARGUMENTS:

range () function has two set of arguments. They are,

1. Single Argument Range Function:

Syntax:

range (stop)

Stop:

To generate the numbers in sequence up to “stop-1” numbers. It will start from zero.

Ex:

range(5)=[0,1,2,3,4]

2.Two Argument Range Function: SYNTAX:

Syntax :

range (start, stop)

Start:

Generating the numbers starting from “start”

Stop:

To generate the numbers in sequence up to “stop-1” numbers.

3.Three Argument Range Function

Syntax:

range([start], stop [, step])

Start:
Generating the numbers starting from “start”
Stop:
To generate a number in sequence up to “stop-1” numbers.
Step:
difference between each number in the sequence

1. Write a program to print 1 to 15

for i in range(15):
print(i+1)

2. Write a program to find sum of first 10 numbers

sum=0
for i in range(1,11):
sum=sum+i
print("Sum = ",sum)

3. Write a program to print odd numbers between 1 to 100

for i in range(1,100,2):
print(i)

4. Program to print multiplication table of a given number

N=int(input(“enter the number”))


for I in range (1,11):
print(n, “X”, I , “=”, (n*I) )

Output:
enter the number5
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

2.3.5 :Nested Loops:

 A nested loop is a loop inside the body of another loop.


 The nested loop is known as the inner loop and the loop in which it is nested is known as out loop.
Syntax
for iterating in sequence:
for iterating in sequence:
statements(s)
statements(s)

(OR)

while expression:
while expression:
statement(s)
statement(s)

Example:
-------------------------------------------------------------------------------------
Write a program to print the following pattern:
12345
1234
123
12
1

n=5
s=0
for i in range(n,0,-1):
for j in range(1, i+1):
print(j, end= ' ')
print()
--------------------------------------------------------------------------

Program to find maximum and minimum of n numbers entered by the user.

n=int(input("enter no.of elements : "))


a=int(input("enter a number : "))
min= max = a
for i in range(n) :
a=int(input("enter a number : "))
if max<a:
max = a
if min>a:
min =a
print("Maximum number is : ",max)
print(Minimum number is :" ,min)

Output:
enter no.of elements : 5
enter a number : 45
enter a number : 3
enter a number : 78
enter a number : 30
enter a number : 12
Maximum number is : 78
Minimum number is : 3
2.4: Input Error Checking

This occurs when we have asked the user for input but have not provided any input in the input box. We
can overcome this issue by using try and except keywords in Python.

2.5: Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because
of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a
loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client
programs can communicate with it as and when required.

Example:
i=1
while True:
if i==4:
break;
print(i)
i=i+2

2.6: Definite and Indefinite loops:

 In definite loops, the number of iterations is known before we start the execution of the body of the loop.

Example: repeat for 10 times printing out a *.

for I in range(1,11):

print(‘*’)

 In indefinite loops, the number of iterations is not known before we start to execute the ody of the loop, but
depends on when a certain condition becomes true (and this depends on what happens in the body of the loop)

Example: while the user does not decide it is time to stop, print out a * and ask the user whether he wants
to stop.

2 Marks

1. Define if statement.

2. Write the difference between break and continue.

3. Define definite and indefinite loop.

4. What is the role of indentation in Python?

5. Predict the output of the following

a,b,c=2,3,4
a,b,c=a*a,a*b,a*c
print(a,b,c)
6. Write a program to print the area of circle when radius of the circle is given by user.

7. What a range() function does? Give an example

8. What are loops in Python? How many types of loop are there in Python?

9. How to check errors in input?

10. Write about pass statement with an example.

5 Marks

1. a.Write a Python program to find the sum of N natural numbers.

b. What is the use of pass statement? Illustrate with an example.

2. Write a program to print the following pattern


*
* *
* * *
* * * *
3. Write a program to print the following pattern:
12345
1234
123
12
1
4. Explain conditional control structures with an example.

5. Write a program to check biggest of three numbers.

6. Explain range statement with an example.

10 Marks

1. Explain loop structures with an examples.


Unit – III

3.1: LIST Structure:

 List is a standard data type of Python that can store a sequence of values belonging to any type.

 lists are defined by having values between square brackets [ ].

 Each value in a list is called an item.

 Lists are mutable (modifiable), that means we can change the elements of a list in place.

 Each item in a list can be accessed through indexing.

 The index value starts from 0 and goes on until the last element called the positive index.

 There is also negative indexing which starts from -1 enabling you to access elements from the last to first.
Ex: a=[1,2,3,4]

Names=[“ram”,”Sam”,”Anil”]

3.1.1 Creating Lists:

To create a list put a number of expressions, separated by commas in square brackets.

L=[] # This statement creates empty list

L=[value1,value2,……..]

 We can also create an empty list as


L= list()
List() function will generate an empty list
 Creating a list from existing sequences
Use list type object to create lists from sequences.
Syntax:
L = list(<sequence>)
Where <sequence> can be any kind of sequence object including string, tuples and lists.

Examples:
>>> l1=list(‘hello’) # creating list from string
>>>print(l1)
[‘h’,’e’,’l’,’l’,’o’]
>>> t=(‘w’,’e’,’l’,’c’,’o’,’m’,’e’)

>>> l2=list(t) # creating a list from tuple


>>>print(l2)
[‘w’,’e’,’l’,’c’,’o’,’m’,’e’]

 Creating a list from keyboard Input:


We can use list() for creating lists of single character or single digits via keyboard input.
>>> L1= list(input(“Enter list elements : “)
Enter list elements : 12345
>>>L1 [‘1’,’2’,’3’,’4’]
3.1.2: List Operations:

 Adding elements

 Updating or Modifying elements

 Deleting elements

 Slicing the list

 Joining Lists

 Replicating List

 Traversing a List
Adding Elements

Adding the elements in the list can be achieved using the append(), extend() and insert()

functions.

 The append() method adds a single item to the end of the list.
L.append(item)

Ex: >>> L1=[1,2,3,4]

>>>L1.append(20)

>>>L1

[1, 2, 3, 4, 20]

 The insert() method inserts an item at a given position.

Syntax:

List. insert(<pos>,<item>)

<pos> is the index of the element where the <item> is to be added.

Ex:

>>>vowels=[‘a’, ’e’,’o’,’u’]

>>>vowels. Insert(2,’i’)

>>>vowels

[‘a’,’e’,’i’,’o’,’u’]
 The extends() method is also used for adding multiple elements to a list.

Syntax:

List.extend(<list>)

Ex:

>>>L1=[1,2,3]

>>>L2=[4,5,6]

>>>L1.extend(L2)

>>>L1

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

Updating Elements in a list

To update or change an element of the list in place, you just have to assign new value to the element’s index in list
.

Syntax:

List[index] = <new value>

Example:

>>>list1=[10,20,30,40]

>>>list1[2]=25

>>>list1

[10,20,25,40]

Deleting elements from a list

del statement

We can delete elements from list using del statement. del statement can remove an individual item or all items
identified by a slice or entire list.

Syntax:

del list[<index>] # to remove an element at index

del list[<start> : <stop>] # to remove elements from start to stop index

del list # deletes entire list


Example:

>>>L=[1,2,3,4,5,6,7,8]

>>> del L[2]

>>> L [1, 2, 4, 5, 6, 7, 8]

>>>del L

pop() method

The pop() removes an element from the given position in the list, and return it. If no index specified, pop()
removes and return the last item in the list.

Example:

>>> a=[‘a’,’b’,’c’,’d’,’e’]

>>> x=a.pop (0)

>>> x

‘a’

>>>y=a.pop()

>>>y

‘e’

>>> a

[‘b’,’c’,’d’]

remove() method

 The remove() method removes the first occurrence of the given value in the list.

Syntax:

List.remove(<value>)

Example:

>>> a=[1,2,3,4,5,6,7,8]

>>>a.remove(2)

>>>a

[1,3,4,5,6,7,8]
Slicing the list

Slicing means extracting a sub part of a list.

Syntax:

Seq = list[start:stop:[step]]

Note: step is optional

Example:

Joining a Lists

 To join Lists,+ operator , is used which joins a list at the end of other list.
 With + operator, both the operands should be of list type otherwise error will be generated.

Example:

>>>l1=[1,2,3,4]

>>>l2=[5,6,7]

>>>l3=l1+l2

>>>l3

[1, 2, 3, 4, 5, 6, 7]

Replicating List

To replicate a list, * operator , is used. It repeats the elements of the list n number of times.
Traversing a List

 Traversal of a list means to access and process each and every element of that list.

 Traversal of a list is very simple with for loop

Syntax:

for <item> in <list>:

Example:

Output:

‘P’

‘Y’

‘T’

‘H’

‘O’

‘N’

3.1.3..List functions:

1.append(): Adds an item at the end of the list.


Syntax:
List.append(<item>)

Example:

2.insert() : Inserts an item at a given position in a list.


Syntax:
List.insert(<pos>,<item>)

Example:

3.extend() : Append the list of items at the end of the list


Syntax:
List. Extend(<list>)

Example:

4. index() : Returns the index of given item in the list.


Syntax:
List. index(<item>)

Example:

5. pop(): Delete and return the element of passed index. If the index is not passed
element from last will be deleted.
Syntax:
List.pop( [<index>] )

Example:

6. remove() : It will delete the first occurrence of passed value but does not return
the deleted value.

7. clear() : It will delete all values of the list and gives an empty list.
Syntax:
List.clear()
Example:
>>>lst = [13,18,11,16,18,14]
>>>lst.clear()
>>>lst
[]

8.sort() : It will sort the elements in ascending order. To sort the list indescending order we need to write
list.sort(reverse=True).
Syntax:
List.sort()

Example:

>>> cars = ['Ford', 'BMW', 'Volvo']


>>>cars.sort()
>>> cars
['BMW', 'Ford', 'Volvo']
>>>cars.sort(reverse=True)
>>> cars
['Volvo', 'Ford', 'BMW']

9. count() : It will count and return the number of occurrences of the given item.

Syntax:
List.count(<item>)

Example:
>>>lst = [13,18,11,16,18,14]
>>>lst.count(18)
2

10. reverse(): It will reverse the list but it does not create a new list.
Syntax:
List.reverse()
Example:

Using a While Loop

 You can loop through the list items by using a while loop.
 Use the len() function to determine the length of the list, then start at 0 and loop your way through the list
items by refering to their indexes.
 Remember to increase the index by 1 after each iteration.
Example:

thislist = ["apple", "banana", "cherry"]


i=0
while i< len(thislist):
print(thislist[i])
i=i+1
3.1.4: Nested Lists:
Nested list means a list can contain another list in it.
Example:
>>>x=['a',['bb',['ccc','ddd'],'ee','ff'],'g',['hh','ii'],'j']

>>>x

['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']

To access individual elements from sublist

>>> x [1][1]

['ccc', 'ddd']

>>> x [1][2]

'ee'

print(x[3][0],x[3][1])

hh ii

>>> x[1][1]

['ccc', 'ddd']

>>> print(x[1][1][0], x[1][1][1])

ccc ddd

3.2 : Tuple Structure:

 In Python, tuple is also a kind of container which can store list of any kind of values.
 Tuple is an immutable data type which means we cannot change any value of tuple.
 Tuple is a sequence like string and list but the difference is that list is mutable whereas string and tuple are
immutable.
 In Python, “()” parenthesis are used for tuple creation.

3.2.1 :Creating a TUPLE:

 T= ()
 T=tuple ()
 T=(value,)
 T=(value1,value2,value3…….)

CREATING FROM EXISTING SEQUENCE:

tuple() function is used to create a tuple from other sequences. See examples-
1) From STRING

2) From LIST

3) By input

>>> t2 = eval(input(“Enter tuple to be added :”))

Enter tuple to be added: (2,5,’x’, [1,2],”hello”)

>>>t2

(2, 5, ‘x’, [1,2], “hello”)

3.2.2: Tuple Operations

 Traversing
 Joining
 Deleting tuple
 Replicating
 Slicing
 Unpacking tuple

Traversing a Tuple:

Traversing means accessing each element of a tuple. The for loop makes it easy to traverse a tuple.

Syntax:

for <item> in <Tuple>

process each item

Example:
T = (1, 2, 3, 4, 5)

for a in T:

print (a)

Joining Tuples

The ‘+’ operator is used to join two tuples. It concatenates two tuples.

Example:

>>> T1= (1, 2, 3, 4)

>>> T2 = (‘a’,’b’,’c’,’d’)

>>> T3=T1+T2

>>> T3

(1, 2, 3, 4, ’a’, ’b’, ’c’,d’)

Deleting a Tuple:

Deleting individual elements is not possible in tuple, because it is an immutable. But we can delete the entire tuple using
del statement.

Example:

>>> T= (‘ram’, ‘raj’, ‘ravi’)

>>> del T

>>> T

It displays an error “name T not found”

Replicating Tuples:

Like list and strings ‘*’operator is used to replicate(repeat) a tuple specified number of times.

>>> t = ( 1,2,3)

>>> t*3 # it repeats the tuple elements 3 times

(1, 2, 3, 1, 2, 3, 1, 2, 3)

Slicing the Tuples:

Slicing mean extracting a sub part of the tuple.


Syntax:

Seq = tuple [start: stop [: step]]

Example:

>>> t = (10,20,30,40,50,60,70)

>>>x = t [2:5]

>>>x

(30,40,50)

>>> y=t [0:7:2]

>>> y

(10, 30, 50, 70)

Unpacking Tuples:

Creating a tuple from a set of values is called packing and its revers, i.e., creating individual values from a tuple’s
elements is called unpacking.

Syntax:

<variable1>,<variable2>,<variable3>,…. = t # t is tuple

Example:

t=(1,2,’hello’,’hai’)

a,b,c,d=t

print(a,b,c,d)

1 2 ‘hello’ ‘hai’

3.2.2: Tuple Functions(Methods)

1. len(): This method returns length of the tuple, i.e., the count of elements in the tuple.

Syntax:len(<tuple>)
Example:

>>> employee = (‘john’, 10000,23,’sales’)

>>len(employee)

2. max(): This method return the maximum value from the elements of the tuple.

Syntax: max(<tuple>)

Example:

>>>tp = (23,10,5,78,123,34)

>>>max(tp)

123

3. min(): This method returns the minimum value from the elements of the tuple.

Syntax: min(<tuple>)

Example:

>>>tp = (23,10,5,78,123,34)

>>>min(tp)

4. index() : This function returns index of an existing element of a tuple.


Syntax: <tuple>.index(<value>)

Example:

>>> t = (1,2,3,4,5)

>>>t.index(3)

5. count(): This method returns no.of times a value present in a tuple .

Syntax:<tuple>.count(<value>)

Example:

>>> t = (1,2,3,3,6,7,2,8,2,0)

>>>t.count(2)

6. tuple() : This method is used to create a tuple from sequence.

Syntax: tuple(<sequence>)

Example:

>>> t= (“hello”)

>>> t

(‘h’,’e’,’l’,’l’,’o’)

3.3: Dictionary Structure:


 A python dictionary is a collection of elements where each element is a combination of Key and Value is
called Key-Value Pair.
 Keys and it’s values are separated by colon(:)
 Different Key-Value pairs are separated by comma(,).
 Keys are unique for each Value.
 Keys of dictionary must be of immutable type like string, number etc.
Example of Dictionary:

A = {1 : “One”, 2 : “Two”, 3 : “Three”}


B = {“A” : “Apple”, “B” : “Ball”, “C” : “Cat”}
Dictionary A has numeric Keys (1, 2, 3)and Values(“One”, “Two”, “Three” ) are in String, while dictionary B has both
Keys(‘A’, ‘B’, ‘C’) and Values(“Apple”, “Ball”, “Cat”) are in string.

Create Empty Dictionary


There are two ways to create an empty dictionary which are as follows
1. A = { } # A is an empty dictionary
2. A = dict( ) # dict( ) method will create an empty dictionary.

To create a dictionary you need to include the key:value pairs in curly braces.

Syntax: <dictionary-name> = {<key>:<value>,{<key>:<value>,{<key>:<value>,…..}

Example:

>>>emp = {‘salary’: 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

Accessing elements of Dictionary:

The elements of the dictionary are accessed through the keys defined in the key:value pair.

<dictionary-name>[“key”]

Ex:

>>>emp = {‘salary’: 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>> emp[“age”]

24

To see all the keys or all the values from a dictonary

>>>emp.keys()

[‘salary’ ,’age’ ,’name’]

>>>emp.values()

[10000,24,’john’]

3.3.1: Dictionary Operations:


 Traversing a Dictionary
 Adding Elements
 Updating Elements
 Deleting Elements
 Membership operator
Traversing a Dictionary:

Traversal of a collection means accessing and processing each element of it. The for loop makes it easy to traverse.

For <item> in <Dictionary>:

Process each item.

Example:

D1={5: “number”,”a”:”string”,1.2:”float”}

for k in D1:

print(key,”:”,D1[key])

Output:

5 : number

a : string

1.2 : float

Adding Elements:

New element (key:value) can be add to a dictionary by using assignment operator. But the key being added must not
exist in dictionary and must be unique. If the key already exists, then this statement will change the value of existing
key and no new entry will be added to dictionary.

Syntax:

<dictionary>[key]=<value>

Example:

A = {1 : "One", 2 : "Two", 3 : "Three"}

A[4] = "Four"

print(A)

OUTPUT

{1 : "One", 2 : "Two", 3 : "Three", 4 : "Four"}

Updating elements:

We can change the value of an element using assignment operator.


Syntax:

<dictionary>[key]=<value>

B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

B[2] = 'Ram'

print(B)

OUTPUT:

{1: 'Amit', 2: 'Ram', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

Deleting elements:

1. By using del statement : To delete an element (key:value) from dictionary use del statement.

Syntax

del <dictionary-name>[key]

B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

del B[2] # It will remove the element of key 2

print(B)

OUTPUT:

{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

2. By Using pop() function : This function not only delete the element of required key but also return the deleted
value.

Example:

B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

a=B.pop(2) #It returns the element of Key - 2

print(a)

print(B)

OUTPUT

Sunil

{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

Checking existing of a key(Member ship operator)

To check the existence of a key use member ship operators in and not in operators with dictionaries.
<key> in <dictionary>

<key> not in <dictionary>

Examples:

>>>B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

>>> 1 in B

True

>>> 4 not in B

True

3.3.2: Dictionary Functions and Methods :

1. len() – This method returns length of the dictionary (the count


of elements)

.Ex:

>>> emp = {‘salary’: 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>>len(emp)

2. clear() – This method removes all items from the dictionary and the dictionary becomes empty.
>>> emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>>emp.clear()

{}

3. get() – With this method we can get the item with the given key.

>>> emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>>emp.get(‘age’)

24

4. items() – This method returns all of the items in the dictionary as a sequence of(key,value) tuples .
emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

mylist=emp.items()

for x in mylist :

print(x)

output:
(‘salary’ ,10000)

(‘age’ ,24)

(‘name’, ‘john’)

5. keys() – This method returns all of the keys in the dictionary as a sequence of keys.

>>> emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>>emp.keys()

[‘salary’ ,’age’ ,’name’]

6. values() - This method returns all of the values in the dictionary as a sequence (a list).

>>> emp = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>>emp.values()
[10000, 24, ‘john’]

7. update() – This method merges key:value pairs from the new dictionary into the original dictionary, adding or
replacing as needed . The items in the new dictionary are added to the old one and override any items
already there with the same keys. This method returns all of the keys in the dictionary as a sequence of keys.

>>> emp1 = {‘salary’ : 10000 , ‘age’ :24 , ‘name’ : ‘john’ }

>>> emp2 = {‘salary’ : 20000 , ‘age’ :25 , ‘name’ : ‘riya’ }

>>>emp1.update(emp2)

>>>emp1

{‘salary’ : 20000 , ‘age’ :25 , ‘name’ : ‘riya’ }

3.4: Set structure:


 Set is an unordered collection of data type that is mutable and has no duplicate elements.
 The order of elements in a set is undefined though it may consist of various elements.
 The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for
checking whether a specific element is contained in the set.
 A set cannot have mutable elements like a list, set or dictionary, as its elements.

3.4.1: Creating a Set

Sets can be created by using the built-in set () function with a sequence by placing the sequence inside curly
braces, separated by ‘comma’.
S= set() # creating a blank set
S1= set(“hello”)

>>> S1{'l', 'e', 'o', 'h'}

>>> x = {42, 'foo', 3.14159, None}


>>> x{None, 'foo', 42, 3.14159}

>>> b={1,2,3,4,1,4}

>>> b

{1, 2, 3, 4}
Adding an element:

We can add single element by using add() method. To add multiple elements use update() method.

Example:

>>>my_set = {1, 3}

>>>print(my_set)

{1,3}

>>>my_set.add(2)

print(my_set)

{1, 2, 3}

my_set.update([4, 5], {1, 6, 8}) # eliminates duplicates


print(my_set)

{1, 2, 3, 4, 5, 6, 8}
Removing an element:

A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the element is not
present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not
present in the set).
>>>my_set = {1, 3, 4, 5, 6}
>>>print(my_set)
{1,3,4,5,6}
# discard an element
>>>my_set.discard(4)
>>>print(my_set)
{1, 3, 5, 6}

# remove an element
>>>my_set.remove(6)
>>>print(my_set)
{1, 3, 5}

# discard an elementnot present in my_set


>>>my_set.discard(2)
>>>print(my_set)
{1, 3, 5}

3.4.2: Operations on Sets:


 Set operations in Python can be performed in two different ways: by operator or by method.

i.Union Operation:
 Set union can be performed with the | operator or union method. It eliminate duplicate values and return the
remaining values from the two sets.

Example:
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1 | x2
{'baz', 'quux', 'qux', 'bar', 'foo'}

>>> x1.union(x2)
{'baz', 'quux', 'qux', 'bar', 'foo'}

Union operation using multiple sets:


>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>>a.union(b, c, d)
{1, 2, 3, 4, 5, 6, 7}

>>> a | b | c | d
{1, 2, 3, 4, 5, 6, 7}

ii. Intersection operation :


 Set intersection can be performed with the & operator or intersection method. It returns common values from
two sets.

Example:

>>> x1 = {'foo', 'bar', 'baz'}


>>> x2 = {'baz', 'qux', 'quux'}

>>> x1.intersection(x2)
{'baz'}

>>> x1 & x2
{'baz'}

Intersection operation using multiple sets:


>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>>a.intersection(b, c, d)
{4}

>>> a & b & c & d


{4}

iii.Difference operation :

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

>>>A.difference(B)
{1, 2, 3}
iv. Symmetric Difference

 Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
print(A^B)

Output:
{1, 2, 3, 6,7,8}

2Marks

1. Define list structure.

2. How to create a dictionary in Python?

3. How to traverse list?

4. Define Tuple in Python.

5. Write any four methods of list structure.

6. How to delete an element from a tuple?

5Marks

1. Explain list structure with its operations.


2. Explain set structure and operations in Pythons

10Marks

1. Explain the following operations on Dictionaries

i. Create a dictionary

ii. Traversing

iii. Deleting element from dictionary

iv. Slicing a dictionary

2. Define Tuple and explain its methods with an examples.

3. Write a program to sort the given elements using list.

You might also like