0% found this document useful (0 votes)
19 views35 pages

Python Programming Basics for Beginners

The document introduces Python programming, highlighting its advantages such as ease of use, cross-platform compatibility, and being open-source. It covers fundamental concepts including data types, tokens, variables, and operators, along with examples of input and output operations. Additionally, it provides practical exercises for students to apply their knowledge of Python programming.

Uploaded by

Kadu
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)
19 views35 pages

Python Programming Basics for Beginners

The document introduces Python programming, highlighting its advantages such as ease of use, cross-platform compatibility, and being open-source. It covers fundamental concepts including data types, tokens, variables, and operators, along with examples of input and output operations. Additionally, it provides practical exercises for students to apply their knowledge of Python programming.

Uploaded by

Kadu
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

Class – XI

Informatics Practices (I.P.) – 065


Python Programming
Getting Started with Python
Python Programming Language was developed by Guido Van Rossum in 1991. Python is an
easy – to – learn yet powerful object oriented language. It is a very high level language.
Advantages of Python:
1. Easy to Use: Python is compact and easy to use with very simple syntax rule.
2. Interpreted Language: Python is an interpreted language, not a compiled language.
3. Cross Platform Language: Python can run equally well on variety of platforms – Windows,
Linux/UNIX, Macintosh, smart phones, etc.
4. Free and Open Source: Python language is freely available along with its source-code.
5. Variety of Usage: Python has evolved into a powerful, complete and useful language over
these years. These days Python is being used in many diverse fields/applications.
Working with Python:
There are two working mode in Python
(A) Interactive Mode:Interactive mode of working means we type the command – one
command at a time, and the Python executes the given command there and then gives you
output.
In Interactive mode, we type the command in front of Python command prompt >>>.
(B) Script Mode: If we want to save all the commands in the form of program file and want
to see all output lines together than we have to use script mode.
 Interactive mode does not save the commands entered by we in the form of a program.
 The output is sandwiched between the command line.
Understanding First Program / Script:
1. Start Python IDLE or any other editor of your choice.
2. Start new file (File > New File) or CTRL + N.
3. Write code in Script Mode, and run it using F5 or Run > Run Module.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Python Fundamentals
Python Character Set: Character set is a set of valid characters that a language can
recognize. A character represents any letter, digit or any other symbol.
Letters: A – Z, a – z
Digits: 0–9
Special Symbols: +, -, *, &, ^, %, $, #, @, !, etc.
White Spaces: Blank Spaces, tabs (→), new line, carriage return.
Tokens:
The smallest unit in a program is known as a Token or a lexical unit. Python has following
tokens:
(i) Keywords (ii) Identifiers (Names) (iii) Literals (iv) Operators
Keywords:
A keyword is a word having special meaning reserved by programming language. Keywords
convey a special meaning to the language to compiler / interpreter.
False, assert, del, for, in, or, while, None, break, elif, from, is, pass,
with, True, class, else, global, lambda, raise, yield, and, continue,
except, if, nonlocal, return, as, def, finally, import, not, try.

Identifiers (Names): Identifiers are fundamentals building blocks of a program, and are used
as the general terminology for the names given to different parts of the program such as
variables, objects, etc.
 An identifier is an arbitrarily long sequences of letters or digits.
 The first character must be a letter, the underscore( _ ) as a letter.
 Upper and Lower – Case letters are different. (Python is a case – sensitive language.)
 The digit 0 through 9 can be part of the identifier except for the first character.
 Identifiers are unlimited in length, and must not be a keyword of Python.
Valid Identifiers:
myvar, MYDATA, Date9_7_17, chk, Q2, h1, etc.
Literals / Values:
Literals are the data items that have a fixed value. Python allows several kinds of literals:
String Literals: A string literals is a sequence of characters surrounded by quotes, (single or
doubled quotes).
‘Astha’, “Ram”, “Hello World”, ‘123’, “A1”, etc.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Strings can be Single line (Basics) or Multiline Strings too.
Numeric Literals: The numeric literals in Python can be of following types:
int (signed integers), float (floating point real values), complex (complex numbers)
Boolean Literals: A Boolean literal in Python used to represent one of two Boolean values i.e.,
True or False.
Special Literal None: The None literal is used to indicate absence of value. It means, “There is
no useful information” or “There is nothing here.”
Operators:
Operators are tokens that triggers some computation when applied to variables and other objects
in an expression. Variables and objects to which the computation is applied, are called
operands.
Binary Operators:
Arithmetic Operators: + (Addition), - (Subtraction), * (Multiplication), / (Division), %
(Remainder / Modulus), ** (Exponent , raise to power), // (Floor
Division).
Bitwise Operators: & Bitwise AND, ^ Bitwise exclusive OR (XOR), | Bitwise OR.
Identity Operators: is (is the identity is same?), is not (is the identity not same?)
Relational Operators: < Less than, > Greater than, <= Less than or equals to,
>= Greater than or equals to, == Equal to, != Not equal to
Assignment Operator: = Assignment, += Assign sum, /= Assign quotient, -= Assign
difference, *= Assign product, %= Assign remainder,
**= Assign Exponent.
Logical Operator: and Logical AND, or Logical OR.
Membership Operator: in (Whether variable in sequence), not in (whether variable not in
sequence)
Comments:
Comments are the additional readable information, which is read by the programmers but
ignored by the interpreter, comments begin with a symbol #.

#This program is showing the implementation of print( ).

print(“Hello World!”) output: Hello World!

Multi – Line Comments: if we want to give multi line comments, we can simply add a #
symbol in the beginning of every line or we simply make it as multi – line string using triple –
quotes.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Variables and Assignments: A variable in Python represents named location that refers to a
value and whose values can be used and processed during program run.

For instance, to store name of a student and marks of a student during a program run, we require
some labels to refer to these marks.

marks = 70

we just assigned the value of numeric type to an identifier name and python created the
variable. Python will internally create labels referring to these values.

marks = 70 marks 70

Multiple Assignments:
1. Assigning same value to multiple variables: We can assign some value to multiple
variable x, y, z.
x = y = z = 50
2. Assigning multiple values to multiple variables: We can even assign multiple values to
multiple variables in single statement.
x, y, z = 20, 60, 90
if we want to swap values of x and y, we just need to write:
x, y = y, x

p, q = 3, 5
q, r = p – 2, p + 2
print(p,q,r) 3, 1, 5
Variable Definition: A variable is created when we first assign a value to it. It also means
that a variable is not created until some value is assigned to it.
print(x) #it will return an error, ‘name x is not defined.’
But if we write, x = 20, and then print it then it will show 20 as output.
Dynamic Typing: A variable pointing to a value of a certain type, can further report to value
or object to different type also.
x = 10 output:
print(x) 10
x = “Python”
print(x) Python

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
If we want to determine the type of a variable i.e., what type of value does it point to ? so we
can use type ( ) in the following manner:
type( <variable name> )
>>> a = 10
>>> type(a) <class ‘int’>
>>> a = 20.5
>>> type(a) <class ‘float’>
>>> a = ‘programming’
>>> type(a) <class ‘str’>
Simple Input and Output:
In python, to get input from user interactively, we can use built – in function input( ). The
function is used in the following manner:
Variable = input(<prompt to be displayed.>)
For example:
name = input(“What is your Name?”)
The input () function always returns a value of String type.
Reading Numbers: String values cannot be used for arithmetic or other numeric operations.
For those operations, we need to have values of numeric types (integers or float)
Read in the value using input( ) function.
And then use int( ) or float( ) function with the read value to change the type of input value.
age = int(input(“What is your age?”))
marks = float(input(“Enter Marks:”))
Output through print( ) function:
The output function of Python is a way to send output to standard output device, which is
normally a monitor.
print(“Hello”) Hello
print(21.10) 21.10
print(5+12) 17
Note: It inserts spaces between items automatically. Like:
print(“Python” , “Programming”, “is”, “a”, “fun.”)
Python Programming is a fun.
We can change the value of a separator with sep argument of print() as per this:
print(“Python” , “Programming”, “is”, “a”, “fun.”, sep= ‘. . .’)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Python…Programming…is…a…fun.
If we give argument end then the new line end it with the specified argument value.
print(“My name is Rahul.”, end = ‘#’)
print(“I study in class XI.”)
My name is Rahul.#
I study in class XI.
Practical Questions:
1. Write a program to input a welcome message and print it.
2. Program to obtain three numbers and print their sum.
3. Program to obtain length and breadth of a rectangle and calculate the area.
4. Program to calculate BMI (Body Mass Index) of a person. The formula is BMI = kg / m2
5. Write a program to input a number and print its cube.
6. Write a program to input a value in kilometers and convert it into miles (1 km = 0.621371
miles).
7. Write a program to input a value in tones and convert it into quintals and kilograms.
8. Write a program to input two numbers and swap them.
9. Write a program to input three numbers and swap them.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Data Handling
Data Types:
Data can be of any types e.g., characters, integers, real, string, etc. Anything enclosed in quotes
represents string data, numbers without fractions represent integer data, numbers with fractions
represent real data (float data), and True or False represent Boolean data.
Python offers following built in core data types:
(i) Numbers: The numbers in Python have following data types:
(a) Integers: a.1 Integers (signed) a.2 Booleans
(b) Floating Point Numbers (c) Complex numbers
Integers: Integers are whole numbers such as 5, 37, 2024, 0, etc. They have no fractional part.
Integers can be positive or negative.
Integers (signed): It is the normal integer representation of whole numbers. Integers can be of
any length.
Booleans: These represent the truth values True and False. The Boolean type is a subtype of
integer and it behave like 0 and 1.
Floating Point Numbers: A number having fractional part is a floating – point number. For
example, 3.14, 7.25. The 25 is an integer but 25.0 is a floating point number.
Floating point variables represent real numbers, which are used for measurable quantities like
distance, area, temperature, etc.
They represent machine level double precision floating point numbers (15 digits’ precision).
Strings:
It is a sequence of characters and each character can be individually accessed using the index.
For example, subject = ‘COMPUTERS’
There will be two types of indexing, forward indexing and backward indexing.
0, 1, 2, … is the forward indexing and -1, -2, -3, … is the backward indexing.
0 1 2 3 4 5 6 7 8
C O M P U T E R S
-9 -8 -7 -6 -5 -4 -3 -2 -1
We can access any character as <stringname>[<index>], to access the first character of string
subject we will write subject[0] because the index of first character is 0.
subject[0] = ‘C’ subject[-7] = ‘M’ subject[6] = ‘E’
We cannot change the individual letters of a string in place by assignment because strings are
immutable and hence item assignment is not supported.
name = ‘hello’

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
name[0] = ‘p’ #it will throw an error.
Immutable Type: The immutable types are those that can never change their value in place.
In python, the following types are immutable: integers, float, Booleans, strings and tuples.
For example: a = 5, b = 5, c = 5
print(id(a)) 140724949469752
print(id(b)) 140724949469752
print(id(c)) 140724949469752
Notice the id( ) is returning same memory address for value 5, which means all these are
referencing the same.
Mutable Types: The mutable types are those whose values can be changed in place. Only
three types are mutable type in Python, these are:
Lists, dictionaries, and sets.
Variable Internals:
Python calls every entity that stores any values or any type of data as an object.
An object is an entity that has certain properties and that exhibit a certain type of behavior. So
all the data or values are referred to as object in Python.
Every Python object has three key attributes associated to it:
(i) The type of an object: The type of an object determines the operations that can be performed
on the object. Function type( ) returns the type of the object.
>>> a = 4
>>> type(a)
<class ‘int’>
(ii) The value of an object: It is the data item contained in the object. using print statement can
display value of an object. for example:
a=4
print(a) 4
(iii) The id of an object: The id of an object is generally the memory location of the object. It
returns the memory location of the object.
Operators:
The symbols that trigger the operation / action on data, are called operators, and the data on
which operation is being carried out, are referred as operands.
Arithmetic Operators:
1. Addition Operator ( + ) : Adds values of its operands and the result is the sum of the values
of its two operands.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
2. Subtraction Operator ( - ) : Subtracts the second operand from the first.
3. Multiplication Operator ( * ) : Multiplies the values of its operands.
4. Division Operator ( / ) : Divides its first operand by the second operand and always return
the result as a float value.
5. Floor Division Operator ( // ) : The floor division is the division in which only the whole
part of the result is given in the output and the fractional part is truncated.
6. Modulus Operator ( % ) : Finds the modulus ( remainder ) of its first operand relative to the
second.
7. Exponentiation Operator ( ** ) : It performs exponentiation (power) calculation, it returns
the result of a number raised to the power.

Task1: What will be the output produced by the following code?


A, B, C, D = 9.2, 2.0, 4, 21
print((A/4), (A//4))
print(B ** C)
print(D / / B)
print(A % C)

Augmented Assignment Operators:


It is the combination of arithmetic operator and assignment operator.
a=a+b
we can write: a + = b
Operation Description
x += y x=x+y
x -= y x=x-y
x *= y x=x*y
x /= y x=x/y
x //= y x = x // y
x %= y x=x%y
x **= y x = x ** y

Relational Operators: It determine the relation among different operand. If the comparison
is true, the relational expression results into the Boolean Value True and to Boolean Value
False, if the comparison is False.
The six relational operators are:

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
< less than, <= less than or equal to, == equal to,
> greater than, >= greater than or equal to, != not equal to
P Q P<Q P <= Q P == Q P>Q P >= Q P != Q
3 3.0 False True True False True False
6 4 True False False True True True
‘A’ ‘A’ False True True False True False
‘a’ ‘A’ False False False True True True

Identity Operators:
There are two identity operators in Python is and is not. The identity operators are used to check
if both the operands reference the same object memory.
Operator Usage Description
is a is b Returns True if both its operands are pointing to same
object, returns False otherwise.
is not a is not b Returns True if both its operands are pointing to
different object, returns False otherwise.

Logical Operators:
The OR operator: It combines two expressions, which make its operands. The or operator
works in these ways:
x y x or y
False False False
False True True
True False True
True True True

The AND operator: It combines two expressions, which make its operands. The or operator
works in these ways:
x y x and y
False False False
False True False
True False False
True True True

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
The NOT operator: It works on single expression or operand. The logical not operator negates
or reverses the truth value of the expression.
Expressions:
An expression in Python is any valid combination of operators, literals and variables. An
expression is composed of one or more operations, with operators, literals, and variables as the
constituents of expressions.
Evaluating Expressions:
A = ( ( 5 + 2 ) / 5.0)

int int
int floating point
floating point
a, b = 3, 6 b // a
c = b // a int int

int
a, b, = 3, 6 b / a
c=b/a int int

floating point
Type Casting:
Python internally changes the data type of some operands so that all operands have the same
data type. This type of conversion is automatic, i.e., implicit and hence known as implicit type
conversion.
Explicit Type Conversion:
An explicit type conversion is user – defined conversion but forces an expression to be of
specific type.
Type casting in Python is performed by type( ) function of appropriate data type, in the
following manner:
<data type>(expression)
For example, we have a = 3 and b = 5.0, then:
int(b) will cast the data-type of the expression as int.
print(int(7.9) will give 7.
Working with math Module:

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Python’s standard library provides a module namely math for math related functions that work
with all number types except complex number.
In order to work with functions of math, we need to first import it.
import math
Then we can use math library’s functions as math.<function-name>.
Function General Form Description Example
ceil [Link](num)
The ceil( ) function returns the [Link](1.03) gives 2.0
smallest integer not less than
num.
sqrt [Link](num) The sqrt( ) function returns the [Link](81.0) gives 9.0
square root of num.
floor [Link](num) The floor( ) function returns the [Link](1.03) gives 1.0
largest integer not greater than
num.
pow [Link](num) The sqrt( ) function returns base [Link](4,2) gives 16
raised to exp power.
Some more math functions are available, like: log, log10, sin, cos, tan, degrees, radians.
Debugging:
Debugging refers to the process of locating the place of error, cause of error, and correcting the
code accordingly. Debugging involves rectifying the code so that the reason behind the bug.
Errors in a Program:
(A) Compile-Time Errors: Errors that occur during compile-time, are compile time errors.
When a program compiles, its source code is checked for whether it follows the programming
language’s rule or not.
A.1 Syntax Errors: Syntax refers to formal rules, Syntax errors occur when the rules of a
programming language are misused i.e., when a grammatical rule of Python is violated.
a < % = 15
print = (“Hello”)
A.2 Semantics Errors: Semantics refers to the set of rules which give the meaning of a
statement. It occurs when statements are not meaningful.
x*y=z
(B) Logical Errors: Logical errors in Python are mistakes in the code that make it do the wrong
thing, like adding when it should divide or forgetting a step in a process.
For example, imagine you write a program to calculate the average of two numbers but
accidentally use addition instead of division. So, instead of dividing the sum of the numbers by
2, you add them together and get an incorrect result.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Run – Time Errors:
Errors that occur during the execution of a program are run time errors. It's like when you're
following a recipe and suddenly realize you're out of a key ingredient halfway through cooking.
For example, in Python, if you try to divide a number by zero (0), it will cause a runtime error
because you can't divide by zero.
Exceptions:
An exception in Python is like a warning or an alarm that goes off when something unexpected
or wrong happens in your code. It's a way for Python to tell you that there's a problem that
needs attention.
# Exception example
num1 = 10
num2 = "abc"
result = num1 + num2 # Mistake: trying to add a number and a string
print("Result:", result) # This line will cause an exception because you can't add a number and
a string.
Some Exception Names:
NameError IndexError ImportError TypeError
ValueError ZeroDivisionError

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Flow of Control
Types of Statements in Python:
Statements are the instruction given to the computer to perform any kind of action. Python
statements can be the following types:
1. Empty Statements
2. Simple Statement
3. Compound Statement
1. Empty Statement (Null Statement): The simple statement is the empty statement i.e., a
statement which does nothing. In python, an empty statement is pass statement.
2. Simple Statement: Any single executable statement is a simple statement in Python. For
example:
name = input(“Enter Your Name:”)
x = 20 + 50
3. Compound Statement: A compound statement represents a group of statements executed
as a unit.
<compound statement header>:
<indented body>
a header file, which begins with a keyword and ends with a colon.
a body, consisting of one or more Python statements, each intended inside the header line.

Statement Flow Control:


In a program, statements may be executed sequentially, selectively or iteratively.

Sequence:
The sequence construct means that statements are being executed sequentially. Sequence refers
to the normal flow of control in a program and is the simplest one.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Selection:
The selection construct means the execution of statements depending upon a condition – test. If
a condition evaluates to True, a set of statements is followed otherwise different set of statement
if followed.
It is also called decision construct.

Repetition Iteration (Looping):


The iteration construct means repetition of a set of statements depending upon a condition test.
Till the time a condition is True (or False depending upon the loop), a set of statements are
repeated again and again.

The set of statements that are repeated again and again is called the body of the loop. The
condition on which the execution or exit of the loop depends is called the exit condition or test
condition.

The if Statement: The if statement are the conditional statements in Python and these
implement selection constructs (decision constructs).
An if statement test a particular condition; if the condition evaluates to true, a statement or set
of statements is executed. Otherwise if the condition is false, the statements are ignored.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Syntax:
if <conditional expression>:
statement(s)
a = 18 if grade = = ‘A’: if a > b:
if (a > 15): print(“You did well.”) print(“A is big.”)
print(“Yes”)
The if – else statement:
This form of if statement tests a condition and if the condition evaluated to true, it carries out
statements, and if in case condition evaluates to false, it carries out statements for else.
Syntax:
if <condition expression>:
statement(s)
else:
statement(s)
if a > = 0: if sales > = 10000:
print(“A is zero or a positive number.”) discount = sales * 0.10
else: else:
print(“It is a negative number.”) discount = sales * 0.05

The if – elif – else Statement:


Sometimes, we need to check another condition in case the test condition of if evaluates to
false. That is, we want to check a condition when control reaches else part, condition test in the
form of else if.
if <conditional expression>:
statement(s)
elif <conditional expression>:
statement(s)
else:
statement(s)
if runs > = 100: if sales > = 30000:
print(“Batsman scored a century.”) discount = sales * 0.18
elif runs> = 50: elif sales > = 20000:
print(“Batsman scored a fifty.”) discount = sales * 0.15
else: else:
print(“Batsman has neither scored a century nor fifty.”) discount = sales * 0.05

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
The nested if Statement:
Sometimes, we may need to test additional conditions. For such situations, Python also
supports nested-if form of if.
A nested if is an if that has another if in its if’s body or in elif’s body or in its else’s body.
Syntax:
if <conditional expression>:
if <conditional expression>:
statement(s)
else:
statement(s)
Example: Program to print whether a given character is an uppercase or a lowercase
character or a digit or any other character.
ch = input(“Enter a single character:”)
if ch > = ‘A’ and ch < = ‘Z’:
print(“You have entered an Upper case character.”)
elif ch > = ‘a’ and ch < = ‘z’:
print(“You entered a lower case character.”)
elif ch > = ‘0’ and ch < = ‘9’:
print(“You entered a digit.”)
else:
print(“You entered a special character.”)

The range( ) function:


The range( ) function of Python generates a list which is a special sequence type. A sequence in
Python is a succession of values bound together by a single name. Some Python sequence types
are: strings, lists, tuples, etc.
range(<lower limit>, <upper limit>) #both limits should be integers.
Please note that the lower limit is included in the list but upper limit is not included in the list.
range(0, 5) # default step value in values will be +1
[0, 1, 2, 3, 4]
range(5, 0) will return empty list [ ] as no number falls in the arithmetic progression with 5 and
ending at 0.
But if you want to produce a list with numbers having gap other than 1, e.g., we want to
produce a list like [2, 4, 6, 8] using range( ) function?

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
For such lists, we can use following form of range( ) function:
range(<lower limit>, <upper limit>, <step value>) #All values should be integers
range(0, 10, 2) will produce a list as [0, 2, 4, 6, 8]
range(5, 0, -1) will produce a list as [5, 4, 3, 2, 1]
range(5) will produce a list as [0, 1, 2, 3, 4]
Statement Values Generated
range(10) 0,1,2,3,4,5,6,7,8,9
range(5, 10) 5,6,7,8,9
range(3, 7) 3,4,5,6
range(5, 15, 3) 5,8,11,14
range(9, 3, -1) 9,8,7,6,5,4
range(10, 1, -2) 10,8,6,4,2
Operators in and not in:
To check whether a value is contained inside a list we can use in operator, e.g.,
3 in [1,2,3,4] True
5 in [1,2,3,4] False
5 not in [1,2,3,4] True
‘a’ in ‘trade’ True
‘ash’ in ‘trash’ True
‘cash’ in ‘trash’ False
Iteration / Looping Statements:
The iteration statements or repetition statements allow a set of instructions to be performed
repeatedly until a certain condition is fulfilled.
The iteration statements are also called loops or looping statements.
Counting Loop: the loop that repeat a certain number of times; Python’s for loop is a
counting loop.
Conditional Loop: the loops that repeat until a certain thing happens i.e./ they keep repeating as
long as some condition is true; Python’s while loop is conditional loop.
The For Loop:
The for loop of Python is designed to process the items of any sequence, such as a list or a
string, one by one. The general form of for loop is as follows:
for <variable> in <sequence>: for a in [1, 4, 7]:
statements to repeat print(a * 2)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Examples:
for ch in “calm”:
print(ch)
The above loop will produce output as:
c
a
l
m
(variable ch given values as ‘c’, ‘a’, ‘l’, ‘m’ – one at a time from string ‘calm’.)
#Program to print table of a number:
num = 5
for a in range(1, 11):
print(num * a) #It will return 5’s multiplication table.
#Program to print sum of natural number between 1 to 7.
sum = 0 Output:
for n in range(1, 8): 28
sum = sum + n
print(sum)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
List Manipulation
Lists: The Python lists are containers that are used to store a values of any type. Unlike other
variables Python lists are mutable i.e., we can change the elements of a list in place. Python
will not create a fresh list when we make changes to an element of a list.
Creating and Accessing Lists:
The lists are depicted through square brackets e.g., following are some lists in Python:
[] #list with no number, empty list
[1, 2, 3, 4, 5] #list of integers
[1, 2.5, 3.7, 9] #list of numbers (integers and floating numbers)
[‘a’, ‘b’, ‘c’] #list of characters
[‘a’, 1, 14, ‘b’, 3.5, ‘zebra’] #list of mixed value types
[‘apple’, ‘boy, ‘cat’] #list of strings
Individual elements of list say A = [1, 2, 3] will be accessed as A[0], which is 1; A[1], which is
2; A[2], which is 3.
Creating Lists:
To create a list, put a number of expressions in square brackets. That is, use square brackets to
indicate the start and end of the list, and separate the items by commas. For example:
[2, 4, 6, 8] [‘ox’, ‘cow’, ‘dog’] [ ]

1. The empty list: The empty list is [ ]. It is the list equivalent of 0 or ‘ ’ and like them it also
has truth value as false.
x = list( )
2. Long lists: If a list contains many elements, then to enter such long lists, we can split it
across several lines, like below:
num = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400,
441, 484, 529, 576, 625]
3. Nested Lists: A list can have an element in it, which itself is a list. Such a list is called nested
list, e.g., x = [3, 4, 5, [10, 20, 45], 8, 9]
x[1] means 4, x[3][1] means 20.

Using list( ) function:


We can also use the built – in list type object to create lists from sequences as per the syntax
given below:
l = list(<sequence>)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
where sequence can be any kind of sequence object including strings, tuples, and lists. Python
create the individual elements of the list from the individual elements of passed sequence.
>>> x = list(“hello”) >>> t = (‘w’, ‘o’, r’, ‘l’, ‘d’)#tuple
>>> x >>> x1 = list(t)
>>> [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] >>> x1 [‘w’, ‘o’, r’, ‘l’, ‘d’]
We can use this method of creating lists of single characters or single digits.
x = list(input(“Enter list elements”))
>>> Enter list elements: 14725
>>> x
>>> [‘1’, ‘4’, ‘7’, ‘2’, ‘5’]

The eval( ) function:


The eval( ) function of Python can be used to evaluate and return the result of an expression
given as string. For example:
eval(‘14 + 6’) 20
y = eval(“3 * 10”) 30
Since eval( ) can interpret an expression given as string, we can use it with input( ) too:
x1 = eval(input(“Enter Value:”))
print(x1)

Accessing Lists:
Similarity with Strings: Lists are sequences just like strings as they also index their individual
elements, just like strings do. In the same manner, list elements are also indexed, i.e., forward
indexing as 0, 1, 2, 3, … and backward indexing as -1, -2, -3, …
x1 = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
0 1 2 3 4 Forward Indexing
a e i o U
-5 -4 -3 -2 -1 Backward Indexing
x1[0] = ‘a’ x1[-5]
x1[1] = ‘e’ x1[-4]
x1[2] = ‘i’ x1[-3]
x1[3] = ‘0’ x1[-2]
x1[4] = ‘u’ x1[-1]

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Accessing Individual Elements:
The individual elements of a list are accessed through their indexes. Consider the following
examples:
>>> x = [‘a’, ‘e’, ‘i', ‘o’, ‘u’]
>>> x[0]
>>> ‘a’
>>> x[4]
>>> ‘u’
>>> x[-5]
>>> ‘a’
Traversing a List:
Traversal of a sequence means accessing and processing each element of it. Thus traversing a
list also means the same and same is the tool for it, i.e., the Python loops.
The for loop makes it easy to traverse or loop over the items in a list, as per the following
syntax:
for <item> in <list>:
process each item here
For example:
x = [‘P’, ‘y’ ‘t’ ‘h’ ‘o’, ‘n’] P
for a in x: y
prtint(a) t
h
o
n
Comparing Lists:
We can compare two lists using standard comparison operators of Python, i.e., <, >, = =, ! =,
etc. Python internally compares individual elements of lists (and tuples) in lexicographical
order.
This means that to compare equal, each corresponding element must compare equal and the two
sequences must be of the same type.
>>> l1, l2 = [1, 2, 3], [1, 2, 3]
>>> l3 = [1, [2, 3]]
>>> l1 == l2 True
>>> l1 == l3 False
>>> l1 < l2 False

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Non – Equality Comparison in List Sequences:
Comparison Result Reason
[1, 2, 8, 9] < [9, 1] True Gets the result with the comparison of
corresponding first elements of two lists 1 < 9 is
True
[1, 2, 8, 9] < [1, 2, 9, 1] True Gets the result with the comparison of
corresponding first elements of two lists 8 < 9 is
True
[1, 2, 8, 9] < [1, 2, 9, 10] True Gets the result with the comparison of
corresponding first elements of two lists 8 < 9 is
True
[1, 2, 8, 9] < [1, 2, 8, 4] False Gets the result with the comparison of
corresponding first elements of two lists 9 < 4 is
False

List Operations:
The most common operations that we perform with lists include joining lists, replicating lists
and slicing lists.
Joining Lists: Joining two lists is very easy just like we perform addition, literally, The
concatenation operator +, when used with two lists, joins two lists.
>>> x1 = [1, 3, 5]
>>> x2 = [6, 7, 8]
>>> x1 + x2
[1, 3, 5, 6, 7, 8]
>>> list1 = [10, 12, 14] >>> list1 = [10, 12, 14]
>>> list1 + 2 Error >>> list1 + ‘abc’ Error
Replicating Lists:
Like strings, we can use * operator to replicate a list specified of times, e.g.,
>>> list1 * 3
>>> [10, 12, 14, 10, 12, 14, 10, 12, 14]
Slicing the Lists:
Lists slices are the sub part of a list extracted out. We can use indexes of list elements to create
list slices as per following syntax:
seq = list[start : stop]
The above statement will create a list slice namely seq having elements of list on indexes start,
start+1, start+2, …, stop-1. The index on last limit is not included in the list slice.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
>>> a = [10, 12, 14, 20, 22, 24, 30, 34]
>>> a[3 : 5] [20, 22]
>>> a[3 : 30] [20, 22, 24, 30, 32, 34]
>>> a[-15 : 7] [10, 12, 14, 20, 22, 24, 30]

>>> p = [2, 3, 4, 5, 6, 7, 8]
>>> p[2 : 5] [4, 5, 6]
>>> p[6 : 10] [8]
>>> p[10 : 20] []

Lists also support slice steps. That is, if we want to extract, not consecutive but every other
element of the list, we can do this using slice steps.
seq = list[start : stop : step]
>>> a = [10, 12, 14, 20, 22, 24, 30, 32, 34]
>>> a[0 : 10 : 2] [10, 14, 22, 30, 34]
>>> a[2 : 10 : 3] [14, 24, 34]
>>> a[: : 3] [10, 20, 30]
>>> a[: : -1] [34, 32, 30, 22, 20, 14, 12, 10]

Using Slices for List Modification:


We can use slices to overwrite one or more list elements with one or more other elements.
Following example:
>>> L = [‘one’, ‘two’, ‘three’] >>> L1 = [1, 2, 3]
>>> L[0 : 2] = [5, 10] >>> L1[2 :] = ‘604’
>>> L >>> L1
[5, 10, ‘three’] [1, 2, ‘6’, 0’, ‘4’]

Lists Functions and Methods:


The list manipulation methods can be applied to lists as per following syntax:
<listobject>.<methodname>( )
1. The len( ) Function: It returns the length of its argument list, i.e., it returns the number of
elements in the passed list.
len(<list>)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
>>>len([10, 20, 56, 78]) >>> len([10, 56, [14, 28, 42], 90, 120])
>>> 4 >>> 5
2. The list( ) method:
It returns a list crated from the passed argument, which should be a sequence type (string, list,
tuple, etc.). If no argument is passed, it will create an empty list.
list([sequence])
>>> list(‘hello’)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
3. The index( ) method:
It returns the index of first matched item form the list. It is used as per following format:
[Link](<item>)
for example, for a list x = [13, 18, 11, 16, 18, 14]
>>> [Link](18)
1
4. The append( ) method:
The append( ) method adds an item to the end of the list. It works as per the following syntax:
[Link](<item>) #takes exactly one element
>>> colors = [“red”, “green”, “blue”]
>>> [Link](‘yellow’)
>>> colors
[“red”, “green”, “blue”, “yellow”]
5. The extend( ) method:
The extend( ) method is also used for adding multiple elements (given in the form of a list) to a
list.
Syntax:
[Link](<list>)
>>> t1 = [‘a’, ‘b’, ‘c’]
>>> t2 = [‘d’, ‘e’]
>>> [Link](t2)
>>> t1
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
6. The insert( ) method:
The insert( ) method is also an insertion method for lists, like append and extend methods. Both
append( ) and extend( ) insert the elements at the end of the list. If you want to insert an element
somewhere in between or any position of our choice, we can use insert( ) method, as follows:
[Link](<index>, <item>)
The first argument <index> is the index of the element before which the second argument
<item> is to be added.
>>> t1 = [‘a’, ‘e’, ‘u’]
>>> t1. insert(2, ‘i’)
>>> t1
[‘a’, ‘e’, ‘i’, ‘u’]
7. The pop( ) method:
The pop( ) is used to remove the item from the list. It is used as per the following syntax:
[Link](<index>)
pop( ) removes an element from the given position in the list, and return it. If no index is
specified, pop( ) removes and returns the last item in the list.
>>> t1 = [‘k’, ‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘u’]
>>> x = [Link](2) >>> y = [Link]( )
>>> x >>> x
‘e’ ‘u’
8. The remove( ) method:
While pop( ) removes an element whose position is given, and the remove( ) method removes
the first occurrence of given item from the list. Syntax:
[Link](<value>) #Takes one essential argument and does not return anything
>>> t1 = [‘k’, ‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘u’]
>>> [Link](‘a’)
>>> t1
[‘k’, ‘e’, ‘i’, ‘p’, ‘q’, ‘u’]
9. The clear( ) method:
This method removes all the items from the list and the list becomes empty list after this
function. This function returns nothing.
[Link]( )
>>> t1 = [‘k’, ‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘u’]
>>> [Link]( )
>>> t1 []

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
10. The count( ) method:
This function returns the count of the item that we passed as argument. If the given item is not
in the list, it returns zero.
[Link](<item>)
>>> L1 = [13, 18, 20, 18, 10, 23]
>>> [Link](18) 2
>>> [Link](25) 0
11. The reverse( ) method:
The reverse( ) reverses the items of the list.
[Link]( )
>>> t1 = [‘e’, ‘I’, ‘q’, ‘a’, ‘a’, ‘p’]
>>> [Link]( )
>>> t1
[‘p’, ‘q’, ‘a’, ‘q’, ‘I’, ‘e’]
12. The sort( ) method:
The sort( ) function sorts the items of the list, by default in increasing order. It does not create a
new list.
[Link]([<reverse = False/True>])
>>> t1 = [‘e’, ‘I’, ‘q’, ‘a’, ‘q’, ‘p’]
>>> [Link]( ) >>> [Link](reverse = True)
>>> t1 >>> t1
[‘a’, ‘e’, ‘I’, ‘p’, ‘q’, ‘q’] [‘q’, ‘q’, ‘p’, ‘I’, ‘e’, ‘a’]
13. The min( ), max( ), sum( ) functions:
The min( ), max( ) and sum( ) functions take the list sequence and return the minimum element,
maximum element and sum of the elements of the list respectively. val = [17, 24, 15, 30]
Syntax: Example: Output:
min(<list>) min(val) 15
max(<list>) max(val) 30
sum(<list>) sum(val) 86
del Statement: The del statement in Python is used to remove an element from a list at a
specified index, a slice of elements, or the entire list.
numbers = [1, 2, 3, 4, 5]
del numbers[2] del numbers
print(numbers) # Output: [1, 2, 4, 5] print(del) #Error (as numbers list is deleted)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Dictionaries
Dictionaries are mutable, unordered collections with elements in the form of a key : value pairs
that associate keys to values.
Dictionaries are simply another type of collection in Python, but with a twist. Rather than
having an index associated with each data item (just like strings or lists), dictionaries in Python
have a “key” and a “value of that key”.

Creating a Dictionary:
To create a dictionary, we need to include the Key : Value pairs in curly braces as per following
syntax:
<dictionary-name> = {<key> : <value>, <key> : <value>… }
student = {101 : ‘Rahul’, 102 : ‘Sanchita’, 103 : ‘Raghav’}
Note: Internally, dictionaries are indexed on the basis of keys.

d={} #It is an empty dictionary.


birdcount = {“Finch” : 10, “Myna” : 13, “Parakeet” : 16, “Hornbill” : 15, “Peacock” : 15}
Keys of a dictionary must be of immutable types, such as:
A Python String,
A number,
A tuple.

Accessing Elements of a Dictionary:


While accessing elements from a dictionary, we need the key. While in lists, the elements are
accessed through their index; in dictionaries, the elements are accessed through the keys
defined.
Syntax:
<dictionary-name> [<key>]
>>> birdcount[“Hornbill”] will return 15.
Attempting to access a key that doesn’t exist, causes an error.
>>> birdcount[‘Sparrow’] will return KeyError

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Traversing a Dictionary:
Traversal of a collection means accessing and processing each element of it. Thus traversing a
dictionary also means the same and same is the tool for it, i.e., the Python Loops.
The for loop makes it easy to traverse or loop over the items in a dictionary, as per following
syntax:
for <item> in <Dictionary>:
process each element
The loop variable <item> will be assigned the keys of <Dictionary> one by one, which we can
use inside the body of the for loop.
d = {‘v1’ : ‘a’, ‘v2’ “ ‘e’, ‘v3’ : ‘i’, ‘v4’ : ‘o’, ‘v5’ : ‘u’}
To traverse the above dictionary, we can write for loop as:
for k in d:
print(k)
a
e
i
o
u
Accessing Keys or Values Simultaneously:
To see all the keys in a dictionary in one go, we may write <dictionary>.keys( ) and to see all
values in one go, we may write <dictionary>.values( )
>>> [Link]()
[‘v1’, ‘v2’, ‘v3’, ‘v4’, ‘v5’]
>>> [Link]( )
[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

Characteristics of a Dictionary:
1. Unordered Set:
A dictionary is a unordered set of key : value pairs. Its values can contain references to
any type of object. We cannot tell the order or position of key : value pairs in a dictionary
as there is no index is associated.
2. Not a Sequence:
Unlike a string, list and tuple, a dictionary is not a sequence because it is an unordered
set of elements. The sequences are indexed by a range of ordinal numbers.

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
3. Indexed by Keys, Not Numbers:
Dictionaries are indexed by keys. According to Python, a key can be “any non-mutable
type.” Since strings and numbers are not mutable, we can use them as a key in a
dictionary.
4. Keys must be Unique:
Each of the keys within a dictionary must be unique. Since keys are used to identify
values in a dictionary, there cannot be duplicate keys in a dictionary.
However, two unique keys can have same values.
>>> birdcount = {“Finch” : 10, “Myna” : 13, “Parakeet” : 16, “Hornbill” : 15, “Peacock” : 15}
5. Dictionaries are Mutable:
Like lists, dictionaries are also mutable. We can change the value of a certain key “in
place” using the assignment statement as per syntax:
<dictionary-name> [key] = <value>
>>> birdcount[“Myna”] = 20
birdcount = {“Finch” : 10, “Myna” : 20, “Parakeet” : 16, “Hornbill” : 15, “Peacock” : 15}
We can even add a new key : value pair to a dictionary using a simple assignment
statement.
>>> birdcount[‘Parrot’] = 45
birdcount = {“Finch” : 10, “Myna” : 13, “Parakeet” : 16, “Hornbill” : 15, “Peacock” :
15,“Parrot” : 45}

Working with Dictionaries:


We can perform on dictionaries, such as adding elements to dictionaries, updating and deleting
elements of dictionaries.
1. Initializing a Dictionary:
In this method all the key : value pairs of a dictionary are written collectively, separately by
commas and enclosed in curly braces.
emp={‘name’: ‘John’, ‘salary’: 10000, ‘age’:24}
2. Adding Key : Value pairs to an Empty Dictionary:
In this method, firstly an empty dictionary is created and then keys and values are added to it
one pair at a time.
emp = { } OR emp = dict( )
emp[‘name’] = ‘John’
emp[‘salary’] = 10000

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
Adding Elements to Dictionary:
We can add new elements (key : value pair) to a dictionary using assignment as per following
syntax. 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.
<dictionary> [<key>] = <value>
>>> emp={‘name’: ‘John’, ‘salary’: 10000, ‘age’:24}
>>> emp[‘dept’] = ‘Sales’
>>> emp
emp={‘name’: ‘John’, ‘salary’: 10000, ‘age’:24, ‘dept’: ‘Sales’}

Nesting Dictionary:
We can even add dictionaries as Values inside a dictionary. Storing a dictionary inside another
dictionary is called nesting of dictionary. Noting that we can only store a dictionary as a value
only, inside a dictionary. We cannot have a key of dictionary type; as it is immutable type.
emp = {‘Ramesh’ : {‘ID’ : ‘A121’, ‘Salary’ : 18000}, ‘Suresh’ : {‘ID’ : ‘A122’, ‘Salary’ :
22000}, ‘Madhav’ : {‘ID’ : ‘A123’, ‘Salary’ : 11900} }

Updating / Modifying Existing Elements in a Dictionary:


Updating an element is easy task. We can change value of an existing key using assignment as
per following syntax:
dictionary[<key>] = <value>
>>> emp = {‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> emp[‘salary’0 = 20000
>>> emp
 But make sure that the key must exist in the dictionary otherwise new entry will be added to
the dictionary.
 Using this method, we can create dictionaries interactively at runtime by accepting input
from user.
Creating User Input dictionary:
n= int(input(“How many students?”))
d1= { }
for a in range(n):
key = input(“Name of the Student:”)

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
d1[key] = value
print(d1)

Deleting Elements from a Dictionary:


For deleting elements from a dictionary we can use the del statement. To delete a dictionary
element or a dictionary entry, i.e., key-value pair, we can use del statement.
del <dictionary>[<key>]
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> del emp[‘age’]
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000}
But, with del statement, the key that we are giving to delete must exist in the dictionary,
otherwise Python raises exception (KeyError).

Checking for Existence of a Key:


Usual membership operators in and not in work with dictionaries as well. But they can check
for the existence of keys only. To check for whether a value is present in a dictionary (called
reverse lookup).
To use a membership operator for a key’s presence in a dictionary, we may write statement as
per syntax given below:
<key> in <dictionary>
<key> not in <dictionary>
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> ‘age’ in emp
True
>>> ‘ID’ not in emp
True
Remember we cannot look for the values directly; it will show False as output.
>>> ‘John’ in emp
False

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
However, if we need to search for a value in a dictionary, then we can use the in operator with
<dictioanary>.values( )
>>> ‘John’ in [Link]( )
True

Dictionary Functions and Methods:


1. The len( ) Function:
To get the length of the dictionary, i.e., the count of the key : value pair, we can use the len( )
function. This function returns length of the dictionary.
len (<dictionary>)
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> len(emp)
3
Creating new Dictionary = the dict( ) function:
the dict( ) function is used to create a new dictionary from iterables and other dictionaries.
dict(iterable)
Q. Create a dictionary where key, value pairs’(rollno, marks) values are available in 3
different lists as: [1,67.8], [2,75.5], [3,72.5]
Ans. data = [[1,67.8], [2,75.5], [3,72.5]]
d1=dict(data)
print(d1)
{1 : 67.8, 2 : 75.5, 3 : 72.5}

Accessing Items, Keys and Values:


1. The get( ) method:
With this method, we can get the item with the given key, similar to dictionary[key] if the key
is not present, Python by default gives error.
[Link](key)
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> [Link](‘age’) 24

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
2. The items( ) method:
This method returns all of the items in the dictionary as a sequence of (Key, Value) tuples.
[Link]( )
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> [Link]( )
[('name', 'John'), ('salary', 10000), ('age', 24)]

3. The keys( ) method:


This method returns all of the keys in the dictionary as a sequence of keys (in form of a list).
[Link]( )
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> [Link]()
dict_keys(['name', 'salary', 'age'])

4. The values( ) method:


This method returns all the values from the dictionary as a sequence (a list).
[Link]( )
>>> emp
{‘name’ : ‘John’, ‘salary’ : 10000, ‘age’ : 24}
>>> [Link]()
dict_values(['John', 10000, 24])

Extend / Update Dictionary with update( ) method:


The update( ) 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.
[Link](<other-dictionary>)
>>> emp1={'name':'John', 'salary':10000, 'age':24}
>>> emp2={'name':'Diya', 'salary':54000, 'dept':'sales'}
>>> [Link](emp2)
>>> emp1

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301
{'name': 'Diya', 'salary': 54000, 'age': 24, 'dept': 'sales'}
Deleting Elements from Dictionary – clear( ) and del
To delete a key from a dictionary, we can use del statement.
del dictionary[key] #to delete a key from the dictionary.
del dictionary #to delete the whole dictionary.

The clear( ) method:


This method removes all items from the dictionary and the dictionary becomes empty
dictionary post this method.
[Link]( )
>>> emp1={'name':'John', 'salary':10000, 'age':24}
>>> [Link]()
>>> emp1
{}

X, XI, XII (IP / CS / AI / IT) Praveen Tripathi Sir (Gold Medalist, [Link]. (Comp. Sci.)) 9351980301

You might also like