PythonByBhupi (1)
PythonByBhupi (1)
What is Programming
• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
JAVA C PYTHON
Syntax
JAVA C PYTHON
Pre Requisites
PRE
• There are no prerequisites to learn Python but a little bit of REQUISISTES
knowledge of any programming language like what is a loop, what
if and else does, how operators are used. If you know the basics of
any programming language, it would be easy to learn Python.
7 PLATFORM INDEPENDENT
EASY
Python
Python is a simple programming language. When we read Python
program, we can feel like reading English statements.
The syntaxes are very simple and only 30+ keywords are available.
When compared with other languages, we can write programs with very
less number of lines. Hence more readability and simplicity.
We can reduce development and cost of the project.
Python is an expressive language. Expressive in this
context means that a single line of Python code can do more than a
Open
single line of code in most other languages. The advantages of a more Source
expressive language are obvious – the fewer lines of code you write, the
faster you can complete the project
It is very rarely used for mobile development. Python is not a very good
language which means it is a weak language for mobile development.
Dynamically Typed- In Python we are not required to declare type for
variables. Whenever we are assigning the value, based on value, type
will be allocated automatically. Hence Python is considered
as dynamically typed language.
But Java, C etc are Statically Typed Languages b'z we have to provide
type at the beginning only.
Step 1 : - Go to https://www.python.org/downloads/
Step 2 : - There you will see the Latest version of Python as of now it is
3.10.4
Step 3 : - Click on Download Now
Now the Python Executable Controller is downloaded simply install it
An integrated development environment (IDE) is a software application
that provides comprehensive facilities to computer programmers for
software development. An IDE normally consists of at least a source
code editor, build automation tools and a debugger.
An IDE (or Integrated Development Environment) is a program
dedicated to software development. As the name implies, IDEs integrate
several tools specifically designed for software development. These tools
usually include:
Netbeans
Pycharm
Eclipse
Integrated
Jupiter Development
Spyder Environment
Dev
IntelliJ
Here, We are using Pycharm and inbuilt IDLE throughout our course but
you can choose any IDE of your choice.
Steps to install -
The keywords are some predefined and reserved words in python that
have special meanings. The keyword cannot be used as an identifier,
function, and variable name. All the keywords in python are written in
lower case except
True
False
None
There are 35 keywords in Python as of Now
Keywords
PYTHON
you can use help() again by passing in the specific keyword that you
need more information about. You can do this, for example, with the
pass keyword:
Keywords in a
Way
• kwlist provides a list of all the Python keywords for the version of
Python you’re running.
_9lives lives9
9lives
1 Alphabet Symbols (Either Upper case OR Lower case)
3 Identifier should not start with Digits and are case sensitive.
KeyPoints
4 We cannot use reserved words as identifiers. Eg: def=10
5 There is no length limit for Python identifiers. But not recommended to use too
lengthy identifiers.
6 Dollar ($) Symbol is not allowed in Python.
IDENTIFIERS
For ex
A = 10
type(A) Print()
id()
to get address of object
For ex
A = 10 id()
id(A)
print()
print in Python is the standard function used to print the output to the
console. Simply to print the value
One of the most basic and popular functions in Python – the print()
statement. We all might have started learning Python programming
with the evergreen example of printing ‘Hello World’. The Python
print() method is used to obtain output i.e. display anything on the
screen as well as to debug code. This function outputs the supplied
message or a value to the console
Suppose I Need to print this Statement in a single line with same Scenario
Sometimes your brain will not remember what you have written and
it might forget it.
For these purposes, good code will hold comments in the right
places.
Run this Program and analyze
If you are thinking like that, this meme is perfectly match for you
1 Single Line
Multi Line 2
3 Doc strings
To Provide a Single Line comment we use (#)
If you want to provide multi line comments use (#) again in every
line there is no other way to declare multi line string
Multiline Python Comment
To have multiline python comment in your code, you must use a hash at
the beginning of every line of your comment in python.
Docstrings Python Comment
Exponentiation
Subtraction(-) Division (/)
(**)
Multiplication
Modulus (%)
(*)
1 / operator always performs floating point arithmetic. Hence it will always returns float
value.
2 But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If atleast one argument is float type
then result is float type.
3 We can use +,* operators for str type also.
4 If we want to use + operator for str type then compulsory both arguments should
be str type only otherwise we will get error.
a
b
c
d
a
b
c
d
Less than (<) Equal to (==)
Greater than
Greater than(>) or equal to
(>=)
or 2
3 not
Logical operator are typically used with Boolean (logical) values.
They allow a program to make a decision based on multiple condition
a
b
c
d
a
b
c
d
IN NOT
IN
In – membership operator
IN
• This checks if a value is a member of a sequence.
• In our next slide example, we see that the string ‘katrina’ does not
belong to the list cricketers. But the string ‘virat kohli’ belongs to it,
so it returns true.
• Also, the string ‘ali’ is a substring to the string ‘alia bhatt’. Therefore,
it returns true.
IN
Not In – Membership Operator
NOT IN
• This checks if a value is not a member of a sequence.
• In our next slide example, we see that the string ‘Katrina’ does not
belong to the list Cricketers. But the string ‘Virat Kohli’ belongs to it,
so it returns False.
• Also, the string ‘Ali’ is a substring to the string ‘Alia Bhatt’. Therefore,
it returns False.
NOT IN
a
b
c
d
a
b
c
d
Is
is not
Let us proceed towards identity Python Operator. is
These operators test if the two operands share an identity. We have two
identity operators- ‘is’ and ‘is not’.
Integer
Frozen Set
Float
Complex
We can use int data type to represent whole numbers (integral values)
Eg: a=10
type(a) #int
In Python 3, there is effectively no limit to how long an integer value can INT
be. Of course, it is constrained by the amount of memory your system
has, as are all things, but beyond that an integer can be as long as you
need it to be:
We can use float data type to represent floating point values (decimal
values)
Eg: f=1.234
type(f) float
We can also represent floating point values by using exponential form
(scientific notation)
Eg: f=1.2e3
print(f) 1200.0
The main advantage of exponential form is we can represent big values
in less memory.
A complex number is of the form
Well in Python also, we say the same definition for String data type.
String is array of sequenced characters and is written inside single
quotes, double quotes or triple quotes. Also, Python doesn’t have
character data type, so when we write ‘a’, it is taken as a string with
length 1.
S T R I N G
s1= ‘World'
s1= “World“
In Python , we can represent char values also by using str type and
explicitly char type is not available.
S T R I N G
We can also use triple quotes to use single quote or double quote in
our String.
S T R I N G
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
How to get substring in Python?
🤔 🤔
PREDICT THE OUTPUT
🤔 🤔
PREDICT THE OUTPUT
🤔 🤔
We can apply the following mathematical operators for Strings.
print(“Vicky"+“Katrina") #VickyKatrina
print(“Kat"*3) #KatKatKat
Note:
Python
f’ F STRING
How to format
Formatting a string is something you'll do all the time when you're
coding in Python.
a String in
Python
Sometimes, you may want to print variables along with a string. You
can either use commas, or use string formatters for the same.
Name = “Alia”
str = “ Hello” , Name, “How are you. “
% OLD STYLE
1. Format a String the Old Way: print ‘Hello %s ’ % name
This approach was more often used in Python2, when the language
was still young and evolving. It's a technique that is easy to
understand for veteran coders who come from a C programming
background.
%d – for integers
%s – for strings
%f – for floating-point numbers
% OLD STYLE
Example to Understand
{} .FORMAT
2. Format a String using Format: ‘’.format()
Python Format()
Function
“ { } ”.format(value)
Example to Understand
f’ F STRING
3. Format a String using F Strings
Also short for format string, f strings are the most recent technique
that Python3 now supports so they're being adopted rapidly.
Example to Understand
String
LEN()
LEN() –
a
b
c
d
Counting
COUNT()
a
b
c
d
a
b
c
d
Python
replace() is an inbuilt function in the Python programming language String
that returns a copy of the string where all occurrences of a substring
Replace
are replaced with another substring.
String.replace(old,new,count)
Syntax :
Optional
string.replace(old, new, count)
old – old substring you want to replace.
new – new substring which would replace the old substring.
count – the number of times you want to replace the old substring with
the new substring. (Optional )
Python String
• If count is not specified then all the occurrences of the old
substring are replaced with the new substring. Replace
• This method returns the copy of the string i.e. it does not change
the original string.
Example to Understand
We can split the given string according to specified seperator by
using split() method.
“Hello World”
l=s.split(seperator)
String split()
The default seperator is space.
The return type of split() method is List
[“Hello”,”World”]
String = “I am a string.”
split()
[ “Hello” , “World” ]
Join()
“Hello World”
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
KeyPoints
• In Python , we can represent char values also by using str type and 2 float
explicitly char type is not available.
3 complex
5 str
AC T i Vi T Y Ti M E
Practice as much as you can as Strings are the most important topic in
any programming language and also for the Interview Room
1. if 1. break
2. if-else 2. continue 1. for
3. if-elif-else 3. pass 2. while
4. Nested if-else
In Python, condition statements act depending on whether a given
condition is true or false. You can execute different blocks of codes
depending on the outcome of a condition. Condition statements always
evaluate to either True or False.
Sometimes, in a program, we may want to make a decision based on a
condition. We know that an expression’s value can be True or False. We
may want to do something only when a certain condition is true.
If If else If - elif -
Nested if
statement statement else
statement
statement
01
if statement is the most simple form of decision-making statement. It
takes an expression and checks if the expression evaluates to True then If
the block of code in if statement will be executed. statement
False
True
AC T i Vi T Y Ti M E
AC T i Vi T Y Ti M E
02
From the name itself, we get the clue that the if-else statement checks the
If else
expression and executes the if block when the expression is True statement
otherwise it will execute the else block of code. The else block should be
right after if block and it is executed when the expression is False.
SYNTAX
True
False
AC T i Vi T Y Ti M E
AC T i Vi T Y Ti M E
If you are thinking that the output is you are eligible to vote then python
interpreter to you be like
CONCLUSION
Nested if
statement
Programming Lab - 04
Think of when you want to print numbers 1 to 99. Or that you want
to say Hello to 99 friends.
Today, we are going to learn about the loops that are available in
Python.
1. For Loop
2. While Loop
3. Nested Loop
LOOPS
That is, for(int i=0;i<n;i++) won’t work here. In Python, we use the
keyword.
Lets see a Python for loop Example
SYNTAX
FOR
LOOP
The range() function Iterating on indices of
1 with For Loop 3 a list or a similar construct
You aren’t bound to use the range() function, though. You can use the
loop to iterate on a list or a similar construct.
Iterating on indices of
3
a list or a similar construct
The len() function returns the length of the list. When you apply the
range() function on that, it returns the indices of the list on a range
object. You can iterate on that.
The else statement
4
for for-loop
When the loop is exhausted, the block under the else statement
executes.
The else statement
4
for for-loop
In such a case, the loop will run infinitely , and the conditions after the
loop will starve. To stop execution, press Ctrl+C.
Write a Simple Program to Ask name from user and greet them
With the message that you want to add more name
Observe Carefully
A while loop may have an else statement after it. When the condition
becomes false, the block under the else statement is executed.
FOR WHILE
LOOP LOOP
An unknown number of times:
For example, Ask the user to guess the lucky number. You don’t know FOR WHILE
how many attempts the user will need to guess correctly. It can be 1, LOOP LOOP
A nested loop has one loop inside of another. It is mainly used with
two-dimensional arrays. For example, printing numbers or star
patterns. Here outer loop is nothing but a row, and the inner loop is
columns.
SYNTAX
AC T i Vi T Y Ti M E
Example to Understand
AC T i Vi T Y Ti M E
Note: If the break statement is used inside a nested loop (loop inside
another loop), it will terminate the innermost loop.
Python allows us to control the flow of the execution of the program in
a certain manner. For this we use the continue, break and pass
keywords.
The break statement inside a loop is used to exit out of the loop.
Sometimes in a program, we need to exit the loop when a certain
condition is fulfilled.
When you put a break statement in the body of a loop, the loop
stops executing, and control shifts to the first statement outside it.
The continue statement skip the current iteration and move to the next
iteration. In Python, when the continue statement is encountered inside
the loop, it skips all the statements below it and immediately jumps to
the next iteration.
Moved to the
next iteration
Skipped for
particular
iteration
PROGRAM TO UNDERSTAND CONTINUE
BREAK
CONTINUE
PASS
SUMMARY
BREAK
19. WAP to print EVEN and Odd to Nth Number With their Sum
Python’s if-else statements are very easy to write and read. But they
come with a downside. That is, if you want to print something based
on some condition, you need 4 lines to do that.
That’s an awful lot of lines for such a simple operation. What’s the
solution, you ask? Ternary operators in Python!
The ternary operator in Python is nothing but a of the
if-else statement. It provides a way to write conditional statements in
a single line, replacing the multi-line if-else syntax.
24. WAP to Calculate the income tax as per the given Slab
TYPE CASTING
Type Casting is the method to convert the variable data type into a
certain data type in order to the operation required to be performed
Python
by users. Type
Casting
We can convert one type value to another type.
1. int()
2. float()
3. bool()
4. str()
TYPE CASTING
Python
There can be two types of Type Casting in Python –
Type
Casting
Implicit Type Casting
Implicit
ImplicitType
TypeConversion
Casting
In this, methods, Python converts data type into another data type
automatically. In this process, users don’t have to involve in this process.
Implicit Type Casting
TYPE CASTING
Explicit Type
Explicit Type Casting
Casting
Mainly in type casting can be done with these data type function:
Int() - Int() function take float or string as an argument and return int
type object.
str() - str() function take float or int as an argument and return string
type object.
EXPLICIT TYPE CASTING
EXPLICIT TYPE CASTING
EXPLICIT TYPE CASTING
TYPE CASTING
🧐
a
b
c
d
TYPE CASTING
a
b
c
d
TYPE CASTING
a
b
c
d
TYPE CASTING
a
b
c
d
TYPE CASTING
🧐 🧐
TYPE CASTING
a
b
c
d
Programming Lab - 08
30. WAP to print Prime Number 1 to Nth Number with their sum.
Programming Lab - 10
But the problem in this approach is , several references pointing to the same object , by
using one reference if we are allowed to change the content in the existing object then the
remaining references will be effected. To prevent this immutability concept is required.
According to this once creates an object we are not allowed to change content. If we are
trying to change with those changes a new object will be created.
PROGRAM TO EXPLAIN IMMUTABILITY
10 Python Object
b
CONCLUSION
Now you might be thinking that we can change the value of a and b
CONCLUSION
b 10 Python Object
New Python
a 20 Object Created
PATTERNS
PATTERN PROGRAMS
Programming Lab - 11
*
* *
* * * 33
* * * *
* * * * *
* * * * * *
Programming Lab - 12
1 1 1
2 2 1 2 2 3
3 3 3 34 1 2 3 35 4 5 6 36
4 4 4 4 1 2 3 4 7 8 9 10
5 5 5 5 5 1 2 3 4 5 11 12 13 14 15
5 5
4 4 5 4
3 3 3 37 5 4 3 38
2 2 2 2 5 4 3 2
1 1 1 1 1 5 4 3 2 1
Programming Lab - 13
* * * * * *
* * * * *
* * * * 39
* * *
* *
*
Programming Lab - 14
5 5 5 5 5 5 4 3 2 1 1 2 3 4 5
4 4 4 4 5 4 3 2 6 7 8 9
3 3 3 40 5 4 3 41 10 11 12 42
2 2 5 4 13 14
1 5 15
1 2 3 4 5 1 1 1 1 1
1 2 3 4 2 2 2 2
1 2 3 43 3 3 3 44
1 2 4 4
1 5
Programming Lab - 15
45
Programming Lab - 16
46 47 48
49 50
Programming Lab - 17
51
Programming Lab - 18
52 53 54
55 56
Programming Lab - 19
bytes data type represents a group of byte numbers just like an array
i.e. it is immutable
Python Bytes()
BYTES
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if Python Bytes()
we are trying to provide any other values then we will get value error.
Conclusion 2:
Once we creates bytes data type value, we cannot change its values ,
otherwise we will get TypeError
BYTES ARRAY
bytearray is exactly same as bytes data type except that its elements
can be modified i.e. it is mutable
BytesArray()
BE ATTENTIVE
LEVEL UP
LISTS
IMPORTANT
Python Lists
LISTS
Lists are one of 4 built-in data types in Python used to store collections Python Lists
of data, the other 3 are Tuple, Set, and Dictionary, all with different
qualities and usage.
[]
EMPTY
LIST
CREATION OF LISTS
1. By using index:
(-) -5 -4 -3 -2 -1
1. By using index:
-4 -3 -2 -1
List = 10 20 30 40
0 1 2 3
ACCESSING ELEMENTS OF LISTS
Traversing a
2. By using for loop: List
using For Loop
DISPLAY ONLY EVEN NUMBERS
AC T i Vi T Y Ti M E
len() count()
Python List Python List
INDEX()
Note: If the specified element not present in the list then we will get index()
ValueError. Hence before index() method we have to check whether
Python List
item present in the list or not by using in operator.
BUILT IN FUNCTIONS FOR LIST
We can use append() function to add item at the end of the list.
Append
()
List = 10 20 30 40
RUN
To add all elements to list upto 100 which are divisible by 10
To insert item at specified index position insert()
Python List
If the specified index is greater than max index then element will be
inserted at last position. If the specified index is smaller than min
index then element will be inserted at first position.
insert()
List = 10 20 30 40
Python List
List = 10 20 500 30 40
RUN
To add all items of one list to another list extend()
l1.extend(l2)
all items present in l2 will be added to l1 Python List
We can use this function to remove specified item from the list. If the remove()
item present multiple times then only first occurrence will be removed.
Python List
If the specified item not present in list then we will get ValueError remove()
Python List
List = 10 20 30 40 POP
List = 10 20 30 POP
List = 10 20
POP()
Note: pop()
1. If the list is empty then pop() function raises IndexError Python List
2. pop() is the only function which manipulates the list and returns
some value
3. In general we can use pop() function to remove last element
of the list. But we can use to remove elements based on index.
POP()
Python List
REVERSE()
Revers
List = 10 20 30 40 e
List =
SORT()
n= 40 10 20 30 n.sort()
n=
CLEAR()
Python List
APPEND() INSERT()
REMOVE() POP()
Aliasing AND Cloning of List
PYTHON
The process of giving another reference variable to the existing list
is called Aliasing.
Aliasing List
Aliasing of List
10 20 30 40
x PYTHON
Y
Aliasing List
10 20777 30 40
x
Y
Python
The process of creating exactly duplicate independent object is called
cloning. Copying and
Cloning [ ]
We can implement cloning by
Python
Copying and
Cloning [ ]
Cloning of List
10 20 30 40
x
10 20 777 30 40
Y
Cloning of List
=
Q. Difference between = operator and copy() function
Copy
1. Concatenation operator(+)
2. Repetition Operator(*)
MATHMATICAL OPERATORS
FOR LIST
1. Concatenation operator(+)
2. Repetition Operator(*)
We can use repetition operator * to repeat elements of list specified
number of times
Comparing Lists
in operator
not in operator
MEMBERSHIP OPERATORS
FOR LIST
NOT
IN
IN
AC T i Vi T Y Ti M E
Nested
• Lists are useful data structures commonly used in Python
programming. A nested list is a list of lists, or any list that has
Lists
another list as an element (a sublist). PYTHON
• Sometimes we can take one list inside another list. Such type of lists
are called nested lists.
Nested LIST
list 1 2 3
List[2] ‘a’ 1
It is very easy and compact way of creating list objects from any
iterable objects ( like list, tuple, dictionary, range etc ) based on some
condition.
SYNTAX
63. WAP to Input values through user in list and print their sum.
64. WAP to print Odd & Even Numbers to in a list to Nth Number.
Programming Lab - 24
65. WAP to Input values through user in list and print it.
66. WAP to Input values through user in list and Update it.
67. WAP to Input values through user in list and Insert value in it.
68. WAP to Input values through user in list and perform search
operation.
Programming Lab - 25
69. WAP to Input values through user in list and Delete an Element
by Index.
70. WAP to Input values through user in list and Delete an Element
by Value.
TUPLES
IMPORTANT
Python Tuples
TUPLES
, ,
TUPLES
2. If our data is fixed and never changes then we should go for Tuple
a
b
c
d
CREATION OF TUPLES
a
b
c
d
CONCLUSION
Most of you are saying it’s a tuple 😂 But my friend it’s not a Tuple
CONCLUSION
Write down the answers in you notebook then run the one by one and
analyze as per your answers
Accessing Elements of TUPLES
1. By using index:
1. By using index:
Tuple follows zero based index. ie index of first element is zero. Python Tuples
Tuple supports both +ve and -ve indexes.
Tuple[0]
Tuple[1]
Tuple[2]
Tuple[3]
Tuple[4]
Accessing Elements of TUPLES
In the previous slides we have seen how to use positive and negative
indexes to access the items in a tuple.
Let’s see what happens if we use indexes that fall outside the boundaries
of the tuple.
For this tuple the maximum valid positive index is 4 and it refers to the
last item. Here is what happens if we use the index 5…
“ index out of range “
TUPLES
Traversing a
1. By using while loop:
Tuple
using While Loop
Traversing the Elements of TUPLES
Traversing a
2. By using for loop:
Tuple
using For Loop
AC T i Vi T Y Ti M E
If you are coming from C or Java Background then you must predicted
something but the answer is Syntax error
TUPLE
A tuple is immutable, this means that once created you cannot add more
elements to a tuple i.e, we cannot change its content.
When you do that you get back a TypeError exception that says that an
object of type tuple does not support item assignment. IMMUTABLE
IMMUTABLE
MATHMATICAL OPERATORS
FOR TUPLES
1. Concatenation operator(+)
2. Repetition Operator(*)
MATHMATICAL OPERATORS
FOR TUPLES
1. Concatenation operator(+)
2. Repetition Operator(*)
LEN()
COUNT()
COUNT()
INDEX()
INDEX ()
SORTED()
TUPLE PACKING
Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
TUPLE UNPACKING
TUPLE UNPACKING
List and Tuple are exactly same except small difference: List objects are
mutable where as Tuple objects are immutable.
LIST VS TUPLE
LIST TUPLE
When to use a Tuple instead of List
Sometimes you don’t want data to be modified. If the values in the collection
are meant to remain constant for the life of the program, using a tuple LIST VS TUPLE
instead of a list guards against accidental modification.
There is another Python data type that you will encounter shortly called a
dictionary, which requires as one of its components a key that is of an
immutable type. A tuple can be used for this purpose, whereas a list can’t be.
Tuple Space / Size
Some of you are thinking that how tuples are efficient in space or how it
is faster than list then here is the proof we are doing programmatically
to show this .
Tuple Space / Size
Tuple Execution Time
Programming Lab - 26
a
b
c
d
DICTIONARY
KEYS VALUES
{}
DICTIONARY
Dictionary = {
Like a real-life dictionary has words and meanings, Python Key : value,
Key : value,
dictionaries have keys and values. They are an important data Key : value
structure in Python and we will learn how to create, access, }
Key-value pairs are separated by commas and keys and values are
separated by colons. Keys in dictionaries are unique and immutable.
Think of a phone book. You have names of people and the phone
numbers associated to those people. A dictionary is exactly the data
structure you need if you want to implement a phone book. Dictionary
follows
CREATION OF DICTIONARY
Keys Values
‘A’ apple
When working with a python dictionary, it is sometimes necessary to
‘B’ Ball
access dictionary data such as keys, values and items (key-value
‘C’ Cat
pairs). Access to this data can take place in various ways.
Keys Values
Using Square brackets ‘A’ apple
‘B’ Ball
To access dictionary elements, you can use square brackets along ‘C’ Cat
Keys Values
Using Square brackets ‘A’ apple
‘B’ Ball
If the given key does not exist in the dictionary, Python raises a Key ‘C’ Cat
Error exception.
AC T i Vi T Y Ti M E
dict[key] = value
If the key is not available then a new entry will be added to the
dictionary with the specified key-value pair
If the key is already available then old value will be replaced with
new value.
TO UPDATE DICTIONARY
DELETE IN DICTIONARY
‘Name’ Tapsee
1. Deleting an entire Python dictionary
‘Gender’ Female
To delete the whole Python dict, simply use its name after the
keyword ‘del’.
DELETE IN DICTIONARY
Keys Values
‘Name’ Tapsee
2. Deleting a single key-value pair ‘Gender’ Female
To delete just one key-value pair, use the keyword ‘del’ with the key
of the pair to delete.
DICTIONARY METHODS
clear() 1 6 keys()
copy() 2 7 update()
get() 3 8 pop()
Items() 4 9 values()
fromkeys() 5 10 popitem()
1. CLEAR()
1 clear()
clear() removes all the key-value pairs of a dictionary.
2. COPY()
2 copy()
To create exactly duplicate dictionary(cloned copy)
3. GET()
d.get(key)
If the key is available then returns the corresponding value otherwise
returns None . It wont raise any error.
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise
returns default value.
3. GET()
4. ITEMS()
This method takes keys from an iterable and creates a new dictionary
5 fromkeys()
from it.
6. KEYS()
7 update()
All items present in the dictionary d2 will be added to dictionary d1
8. POP()
d1.pop(key) 8 pop()
It removes the entry associated with the specified key and returns the
corresponding value
9 values()
It returns all values associated with the dictionary
10. POPITEM()
This removes the last added key-value pair from a dictionary and 10 popitem()
returns it.
a
b
c
d
Programming Lab - 27
77. WAP to Input keys and values from the keyboard and print the
sum of values ?
Sets
Sets are used to store multiple items in a single variable.
PYTHON
Note: Set items are unchangeable, but you can remove items and
add new items.
SET
Set
{1,2,3,4}
SETS
1 Duplicates are not allowed.
5 Set objects are mutable i.e once we creates set object we can perform any changes in that
object based on our requirement.
6 We can represent set elements within curly braces and with comma separation
7 We can apply mathematical operations like union, intersection, difference etc on set objects.
CREATION OF SET
a
b
c
d
CONCLUSION
If your answer is Set then your situation may be like Rajpal Yadav
CONCLUSION
CREATION OF SET
1 add()
Adds item to the set
2. UPDATE()
It removes and returns some random element from the set. 4 pop()
5. REMOVE()
add VS update
We can use add() to add individual item to the Set
where as we can use update() function to add multiple items to Set.
a
b
c
d
MATHMATICAL OPERATIONS
FOR SETS
UNION
s1.union(s2) ==>We can use this function to return all elements
present in both sets
s1.union(s2) or s1|s2
MATHMATICAL OPERATIONS
FOR SETS
INTERSECTION
s1.intersection(s2) or s1&s2
Returns common elements present in both s1 and s2
MATHMATICAL OPERATIONS
FOR SETS
DIFFERENCE
x.difference(y) or x-y
returns the elements present in x but not in y
Programming Lab - 29
FROZEN SET
IN
PYTHON
FROZEN SET
frozenset( [1,2,3,4] )
iterable
FROZEN SET
s = {10,20,30,40}
fs = frozenset(s)
This fs is freezed
HOW TO CREATE FROZEN SET
Programming Lab - 30
Now Based on Previous 3 Programs you can able to do the Next one
Which is
153
13 53 33 153
Programming Lab - 33
Now as the next step we are going to build Multistory Building to that
foundation
PYTHON
PYTHON