Python Notes
Python Notes
Vertika Verma
Department of CSE (Cyber Security)
PIET, Parul University
Content
1. Introduction to python programming….…..……...……3
2. Features of Python…….……..………………………....4
3. Python Applications…..…………………………………6
4. Python Variables……………….………………………..7
5. Identifier Naming………………………………………...8
6. Declaring Variable and Assigning Values…………….9
7. Python Operators…………………..…………………..11
8. Basic Programming Concepts………………………...12
9. Python Loops…………………………………………...28
[Link] String…………………………………………...42
[Link] List……………………………………………...53
[Link] Tuples………………………………………….71
[Link] Set……………………………………………...83
[Link] Dictionary……………………………………...93
Introduction to python programming:
• Python is a high-level, versatile, and user-friendly programming language widely
used in various fields, including web development, data analysis, machine
learning, and automation.
• Its simple syntax and readability make it an excellent choice for beginners.
• In the late 1980s, Guido van Rossum dreamed of developing Python.
• The first version of Python 0.9.0 was released in 1991. Since its release, Python
started gaining popularity.
• According to reports, Python is now the most popular programming language
among developers because of its high demands in the tech realm..
Features of Python
Easy to use and Read - Python's syntax is clear and easy to read, making it an
ideal language for both beginners and experienced programmers. This simplicity
can lead to faster development and reduce the chances of errors.
Dynamically Typed - The data types of variables are determined during run-time.
We do not need to specify the data type of a variable during writing codes.
Compiled and Interpreted - Python code first gets compiled into bytecode, and
then interpreted line by line. When we download the Python in our system form
[Link] we download the default implement of Python known as CPython.
CPython is considered to be Complied and Interpreted both.
Features of Python
Garbage Collected - Memory allocation and de-allocation are automatically
managed. Programmers do not specifically need to manage the memory.
Rich Standard Library - Python comes with several standard libraries that provide
ready-to-use modules and functions for various tasks, ranging from web
development and data manipulation to machine learning and networking.
Open Source - Python is an open-source, cost-free programming language. It is
utilized in several sectors and disciplines as a result.
Python Applications
Python is known for its general-purpose
nature that makes it applicable in almost
every domain of software development.
• Since Python is an infer language that is smart enough to determine the type of a
variable, we do notneed to specify its type in Python.
• Variable names must begin with a letter or an underscore, but they can be a group
of both lettersand digits.
• White space and special characters (!, @, #, %, etc.) are not allowed in the
identifier name. ^, &, *).
• Identifier name should not be like any watchword characterized in the language.
• Names of identifiers are case-sensitive; for instance, my name, and My Name isn't
something very similar.
continu
and for lambda try
e
nonloca
as def from while
l
Multi-Line Comments
# it is a
# comment
# extending to multiple lines
Python If-else statements
Decision making is the most important aspect of almost all the
programming languages. As the name implies, decision making
allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of
decision making.
In python, decision making is performed by the following
statements.
Python If-else statements
Statement Description
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't
allow the use of parentheses for the block level code. In Python,
indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
The syntax of the if-statement is given below.
if expression:
statement
Indentation in Python
Example 1
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will
enter the block print("The Given number is an even number") Output:
enter the number: 10 The Given number is an even number
Python Loops
The following loops are available in Python to fulfil the looping needs.
Python offers 3 choices for running the loops. The basic functionality of all
the techniques is the same, although the syntax and the amount of time
required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop
command.
The following sorts of loops are available in the Python programming
language.
Cont..
[Link]. Name of the loop Loop Type & Description
Repeats a statement or group
of statements while a given
1 While loop condition is TRUE. It tests the
condition before executing the
loop body.
Cont..
[Link]. Name of the control Description
statement
For loop
The for Loop
Python's for loop is designed to repeatedly execute a code block while
iterating through a list, tuple, dictionary, or other iterable objects of
Python. The process of traversing a sequence is known as iteration.
Syntax of the for Loop for value in sequence: { code block }
In this case, the variable value is used to hold the value of every item
present in the sequence before the iteration begins until this particular
iteration is completed.
Loop iterates until the final item of the sequence are reached.
For loop example
# Python program to show how the for loop works
# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be
executed else: print(s) Output:
P y t h If block n L If block If block p
The range() Function
With the help of the range() function, we may produce a series of numbers.
range(10) will produce values between 0 and 9. (10 numbers). We can
give specific start, stop, and step size values in the manner range(start,
stop, step size). If the step size is not specified, it defaults to 1. Since it
doesn't create every value it "contains" after we construct it, the range
object can be characterized as being "slow." It does provide in, len, and
__getitem__ actions, but it is not an iterator.
The example that follows will make this clear.
Example
# Python program to show the working of range() function
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
print(list(range(5, 25,
4)))
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
Python While Loops
The Python while loop iteration of a code block is executed as long as the given
Condition, i.e., conditional_expression, is true.
If we don't know how many times we'll execute the iteration ahead of time, we can
write an indefinite loop.
Syntax of Python While
Loop Statement while
Condition:
The given condition, i.e., conditional_expression, is evaluated initially in the Python
while loop. Then, if the conditional expression gives a boolean value True, the while
loop statements are executed. The conditional expression is verified again when the
complete code block is executed. This procedure repeatedly occurs until the
conditional expression returns the boolean value False.
The statements of the Python while loop are dictated by indentation.
The code block begins when a statement is indented & ends with the very first
unindented statement. Any non-zero number in Python is interpreted as
boolean True. False is interpreted as None and 0.
Example
Program code 1:
Now we give code examples of while loops in Python for printing numbers
from 1 to 10. The code is given below i=1 while i<=10:
print(i, end=' ')
i+=1
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below 1 2 3 4
5 6 7 8 9 10
Loop Control Statements
Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.
Code
# Python program to show how to use continue loop control
Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means
that Python doesn't support the character data-type; instead, a single
character written as 'p' is treated as the string of length 1.
Example
Creating String in Python
We can create a string by enclosing the characters in single-quotes or
double- quotes. Python also provides triple-quotes to represent the string,
but it is generally used for multiline string or docstrings.
#Using single
quotes str1 = 'Hello
Python' print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline
or docstring''' print(str3)
Example
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For
example, The string "HELLO" is indexed as given in the below figure.
Example
Consider the following example:
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't
exist print(str[6]) Output:
H E L L O IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual
characters of the string. However, we can use the : (colon) operator in
Python to access the substring from the given string. Consider the
following example.
Example
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
It is used to specify the raw string. Raw strings are used in the cases where we need to print
r/R the actual meaning of escape characters such as "C://python". To define any string as a raw
string, the character r or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C
% programming like %d or %f to map their values in python. We will discuss how formatting is
done in python.
.
Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll print('w' in str) # prints false as w
is not present in str print('wo' not in str1) # prints false as
wo is present in str1. print(r'C://python37') # prints
C://python37 as it is written print("The string str :
%s"%(str)) # prints The string str : Hello Output:
HelloHelloHello
Hello world
O
ll False False C://python37 The string str : Hello
Python String functions
Method Description
It capitalizes the first character of the String. This function is
capitalize()
deprecated in python3
casefold() It returns a version of s suitable for case-less comparisons.
It returns a space padded string with the original string centred with
center(width ,fillchar) equal number of left and right spaces.
It counts the number of occurrences of a substring in a String
count(string,begin,end) between begin and end index.
decode(encoding = 'UTF8', errors =
Decodes the string using codec registered for encoding.
'strict')
Encode S using the codec registered for encoding. Default encoding
encode() is 'utf-8'.
endswith(suffix It returns a Boolean value if the string terminates with given suffix
,begin=0,end=len(string)) between begin and end.
It defines tabs in string to multiple spaces. The default space value is
expandtabs(tabsize = 8)
8.
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
Python List
In Python, the sequence of various data types is stored in a list. A list is a
collection of different kinds of values or items. Since Python lists are
mutable, we can change their elements after forming. The comma (,)
and the square brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most
common and reliable form. A list, a type of sequence data, is used to
store the collection of data.
A list is a collection of items separated by commas and denoted by the
symbol [].
Example
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9] ['Amy', 'Ryan', 'Henry', 'Emma'] < class '
list ' > < class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:
The lists are in order.
The list element can be accessed via the index.
The mutable type of List is
The rundowns are changeable sorts.
The number of various elements can be stored in a list.
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The
slice operator [] can be used to get to the List's components. The index
ranges from 0 to length -1. The 0th index is where the List's first element
is stored; the 1st index is where the second element is stored, and so on.
List Indexing and Splitting
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
The beginning indicates the beginning record position of the rundown.
The stop signifies the last record position of the rundown.
Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the
value of the end parameter is the number of elements that are "stepped"
through. The default value for the step is one without a specific value.
Inside the resultant Sub List, the same with record start would be available,
yet the one with the file finish will not. The first element in a list appears to
have an index of zero.
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way
as they were working with the strings. The different operations of list are
Repetition
Concatenation
Length
Iteration
Membership
1. Repetition
The redundancy administrator empowers the rundown components to be
rehashed on different occasions.
Code
# repetition of list #
declaring the list list1 =
[12, 14, 16, 18, 20] #
repetition operator * l =
list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
# concatenation of two
lists # declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86] #
concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length
It is used to get the length of the list
Code
# size of the list #
declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39,
40] # finding length of the list len(list1)
Output:
9
4. Iteration
The for loop is used to iterate over the list elements.
Code
# iteration of the list #
declaring the list list1 =
[12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
Output:
12 14 16 39 40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500] #
true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:
False False False True True True
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four
strings, which can be iterated as follows.
Code
# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each
element in each iteration. print(i) Output:
John David James Jonathan
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case,
the annex() capability can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of
the rundown from the client and print the rundown on the control center.
Code
#Declaring the empty list
l =[]
#Number of elements will be entered by the user n =
int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
[Link](input("Enter the item:"))
print("printing the list items..") #
traversal loop to print the list items
for i in l:
print(i, end = " ")
Example
Enter the number of elements in the list:10
Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18
Removing Elements from the List
The remove() function in Python can remove an element from the List.
To comprehend this idea, look at the example that follows. Code
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
[Link](2)
print("\nprinting the list after the removal of first element...")
for i in list: print(i,end=" ") Output:
printing original list: 0 1 2 3 4 printing the list after the removal of first
element... 0 1 3 4
Python List Built-in Functions
Python provides the following built-in functions, which can be used
with the lists. len() max() min() len( )
It is used to calculate the length of the list.
Code
# size of the list # declaring
the list list1 = [12, 16, 18,
20, 39, 40] # finding length
of the list len(list1) Output:
6
Python List Built-in Functions
Max( )
It returns the maximum element of the list
Code # maximum of the list
list1 = [103, 675, 321, 782,
200] # large element in the list
print(max(list1)) Output:
782
Python List Built-in Functions
Min( )
It returns the minimum element of the list
Code # minimum of the list
list1 = [103, 675, 321, 782,
200] # smallest element in the
list print(min(list1)) Output:
103
Python Tuples
A comma-separated group of items is called a Python triple. The ordering,
settled items, and reiterations of a tuple are to some degree like those of
a rundown, but in contrast to a rundown, a tuple is unchanging. The main
difference between the two is that we cannot alter the components of a
tuple once they have been assigned. On the other hand, we can edit the
contents of a list.
Example
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
Tuples are an immutable data type, meaning their elements cannot be
changed after they are generated.
Each element in a tuple has a specific order that will never change
because tuples are ordered sequences.
All the objects-also known as "elements"-must be separated by a comma,
enclosed in parenthesis (). Although parentheses are not required, they
are recommended.
Example
Code
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
Negative Indexing
Python's sequence objects support negative indexing.
The last thing of the assortment is addressed by - 1, the second last thing
by - 2, etc.
Code
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-
1]) Output:
Element at -1 index: Collection Elements between -4 and -1 are:
('Python', 'Tuple', 'Ordered')
Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to
access a variety of its elements. Using the colon as a straightforward slicing
operator (:) is one strategy.
To gain access to various tuple elements, we can use the slicing operator colon (:).
Code
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing print("Elements
between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
Output:
Elements between indices 1 and 3: ('Tuple', 'Ordered') Elements between indices 0
and -4: ('Python', 'Tuple') Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable',
Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or remove tuple
components as a result.
However, the keyword del can completely delete a tuple.
Code
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as
e: print(e) Output:
'tuple' object does not support item deletion name 'tuple_' is not defined
Repetition Tuples in Python
# Python program to show repetition in tuples
tuple_ = ('Python',"Tuples")
print("Original tuple is: ",
tuple_) # Repeting the tuple
elements tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are
a few ways to work with tuples in Python. With some examples, this essay
will go over these two approaches in detail.
The following are some examples of these methods.
Count () Method
The times the predetermined component happens in the Tuple is returned
by the count () capability of the Tuple.
Code
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = [Link](2) print('Count of 2
in T1 is:', res) # counting the
appearance of java res =
[Link]('java') print('Count of
Java in T2 is:', res) Output:
Count of 2 in T1 is: 5 Count of java in T2 is: 2
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
The thing that must be looked for.
Start: (Optional) the index that is used to begin the final (optional) search: The most recent index
from which the search is carried out
Index Method
Code
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3 res =
Tuple_data.index(3) print('First
occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4) print('First occurrence
of 1 after 4th index is:', res) Output:
First occurrence of 1 is 3 First occurrence of 1 after 4th index is: 6
FrozenSets
In Python, a frozen set is an immutable version of the built-in set data
type. It is similar to a set, but its contents cannot be changed once a
frozen set is created.
Frozen set objects are unordered collections of unique elements, just like
sets. They can be used the same way as sets, except they cannot be
modified. Because they are immutable, frozen set objects can be used as
elements of other sets or dictionary keys, while standard sets cannot.
One of the main advantages of using frozen set objects is that they are
hashable, meaning they can be used as keys in dictionaries or as
elements of other sets. Their contents cannot change, so their hash
values remain constant. Standard sets are not hashable because they can
be modified, so their hash values can change.
Example
Consider the following example to create the frozen set.
Frozenset = frozenset([1,2,3,4,5]) print(type(Frozenset))
print("\nprinting the content of frozen set...") for i in
Frozenset: print(i);
[Link](6) #gives an error since we cannot change the content of Fro
zenset after creation Output:
<class 'frozenset'> printing the content of frozen set... 1 2 3 4 5 Traceback
(most recent call last): File "[Link]", line 6, in <module> [Link](6)
#gives an error since we can change the content of Frozenset after
creation
AttributeError: 'frozenset' object has no attribute 'add'
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because
they are capable of imitating real-world data arrangements where a certain
value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
This data structure is mutable
The components of dictionary were made using keys and values.
Keys must only have one component.
Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the
values can be any Python object. The keys, in contrast, are immutable
Python objects, such as strings, tuples, or numbers. Dictionary entries are
ordered as of Python version 3.7. In Python 3.6 and before, dictionaries
are generally unordered.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary,
although there are other approaches as well. With many key-value pairs
surrounded in curly brackets and a colon separating each key from its
value, the dictionary can be built. (:). The following provides the syntax
for defining the dictionary.
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which
comes under the category of an immutable object.
Let's see an example to create a dictionary and print its content.
Example
Code
Employee = {"Name": "Johnny", "Age": 32,
"salary":26000,"Company":"^TC
S"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'> printing Employee data .... {'Name': 'Johnny', 'Age': 32,
'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to
create the dictionary.
Example
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict) Output
Empty Dictionary: {} Create Dictionary by using dict(): {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'} Dictionary
with each item as a pair: {4: 'Rinku', 2: 'Singh'}
Accessing the dictionary values
To access data contained in lists and tuples, indexing has been studied. The keys of
the dictionary can be used to obtain the values because they are unique from one
another. The following method can be used to access dictionary values. Code
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee)) print("printing Employee data .... ") print("Name : %s"
%Employee["Name"]) print("Age : %d" %Employee["Age"]) print("Salary : %d"
%Employee["salary"]) print("Company : %s" %Employee["Company"]) Output
ee["Company"]) Output <class 'dict'> printing Employee data .... Name : Dev Age :
20 Salary : 45000 Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] =
value and the value can both be modified. An existing value can also be updated using the update() method
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)