0% found this document useful (0 votes)
7 views

Chapter-1

This document serves as an introduction to Python programming, covering its history, features, and basic programming concepts. It explains Python's syntax, variable types, data types, conditional statements, and loops, providing examples for clarity. Additionally, it compares Python with Java and discusses the handling of strings, lists, sets, tuples, and dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter-1

This document serves as an introduction to Python programming, covering its history, features, and basic programming concepts. It explains Python's syntax, variable types, data types, conditional statements, and loops, providing examples for clarity. Additionally, it compares Python with Java and discusses the handling of strings, lists, sets, tuples, and dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter-1

Part-1: Introduction to Python Programming:

Topic-1: Introduction to Python and basic programming concepts:

 Python is a popular high-level, general-purpose programming language.


 Guido van Rossum invented it in 1991, and the Python Software Foundation continued to refine
it.
 Its syntax enables programmers to convey their ideas in fewer lines of code, and it was created
with code readability in mind.
 Python is a programming language that facilitates faster work and more effective system
integration.
 Python 2 and Python 3 are the two main versions. They are really distinct from one another.

Features of Python:
 Interpretation: Unlike C and C++, there are no distinct compilation and execution steps. Launch
the application straight from the source code. In order to run the source code, Python internally
transforms it into bytecodes, which are then translated into the native language of the machine.
There is no need to be concerned with loading and linking libraries, etc.
 Independent of Platform: Python applications can be created and run on a variety of operating
systems. Linux, Windows, Macintosh, Solaris, and many other operating systems can all utilise
Python.
 Redistributable, Open Source, and Free
 Advanced Language: Low-level aspects like controlling the program's memory usage are not
necessary while using Python.
 Easy: Easy to learn and more similar to the English language. More focus on the problem-solving
approach rather than the syntax.
 Embedded: Python can be used in C/C++ programs to provide users with scripting capabilities.
 Strong: Outstanding handling characteristics. Built-in memory management strategies
 Comprehensive Library Assistance: The scope of the Python Standard Library is enormous.
Regular expressions, documentation creation, unit testing, threading, databases, web browsers,
CGI, email, XML, HTML, WAV files, cryptography, graphical user interfaces, and many more
tasks may be accomplished using Python, which is known for its "batteries included" concept.
In addition to the standard library, there are additional excellent libraries, such the Python
Imaging Library, which is a remarkably straightforward image processing toolkit.

Python vs JAVA
Python Java

Typed Dynamically Typed Statically


Nothing needs to be declared. An object Every variable name needs to be specified clearly, along
of any type can be bound to a name with its type. A type exception occurs when an item of the
using an assignment statement. incorrect type is attempted to be assigned to a variable
When employing container objects, type name.
casting is not necessary. When employing container objects, type casting is
necessary.
Python Java

Brief: Say a lot in a few words. Verbose: More words are included.

Compact Less Compact

Applications use indentation to organise


Use braces to organise code
code

Topic-2: Variables:
 Python variables are value-storing containers.
 "Statically typed" is not how Python works.
 It is not necessary to declare variables or their types before using them.
 As soon as we give a variable a value, it is created.
 A Python variable is a name assigned to a location in memory.
 It is a program's fundamental storage unit.
 A representational name that acts as a pointer to an object is an example of a variable in Python.
An object can be called by that name once it has been assigned to a variable.
 Python variable rules:
o A letter or the underscore character must appear at the beginning of a Python variable name.
o No number can appear at the beginning of the name of a Python variable.
o Alpha-numeric characters and underscores (A-z, 0-9, and _) are the only characters allowed in a
Python variable name.
o Python variable names are case-sensitive; for example, name, Name, and NAME are all distinct
variables.
o Python variables cannot be named using the reserved terms (keywords).

Examples of variable assignment:


a = 45
b = 1456.8
c = "John"

a = b = c = 10

a, b, c = 1, 20.2, "GeeksforGeeks"

a = 20
b = 30
print(a+b) #supported

a = "Parul"
b = "University"
print(a+b) #supported

a = 20
b = "Parul"
print(a+b) #unsupported

Topic-3: Datatypes:

 Python data types are used to classify or group data elements.


 It stands for the type of value that indicates the operations that can be carried out on a specific
piece of data.
 Python data types are classes, and variables are instances (objects) of these classes, since
everything in Python programming is an object.
 The standard or built-in data types in Python are as follows:
o Numeric – int, float, complex
o Sequence Type – string, list, tuple
o Mapping Type – dict
o Boolean – bool
o Set Type – set, frozenset

1. Python Numerical Data Types:


 In Python, data with a numeric value is represented by the numeric data type.
 An integer, floating number, or even a complex number can all be considered numeric values.
 These values are defined by the Python complex, Python int, and Python float classes.
Integers: The int class represents this value. It includes complete numbers (without fractions or decimals)
that are either positive or negative. An integer value in Python can be as lengthy as it wants to be.
Float: The float class is used to represent this value. It has a floating-point representation and is a real
number. A decimal point is used to specify it. To specify scientific notation, a positive or negative number
may optionally be inserted after the character e or E.
Complex Numbers: A complex class is used to represent a complex number. (Real part) + (Imaginary
part)j is the specification. For instance, 2+3j
2. Python Sequence Data Types
An ordered grouping of related or dissimilar Python data types is called a sequence data type.
Sequences make it possible to efficiently and systematically store many values. Python has
multiple sequence data types, including:
 Python String
 Python List
 Python Tuple
3. Python Boolean Data Type:
 Boolean data types have two built-in values: True or False.
 Boolean objects that equal False are false (false), whereas those that equal True are truthy (true).
But it is also possible to evaluate non-Boolean items in a Boolean environment and determine
whether they are true or false.
 The class bool is used to represent it.

Note: Python will give an error if True and False are not capitalised "T" and "F."

4. Python Set Data Type


 Iterable, changeable, and devoid of duplicate components, a set is an unordered collection of data
types in Python data types.
 Although a set may contain a variety of components, its order is not specified.
 The built-in set() function can be used to generate sets with an iterable object or a sequence by
enclosing the sequence in curly braces and separating it with a "comma."
 Different mixed-up data type values can also be provided to the set; the elements in the set do not
have to be of the same type.
5. Python Dictionary Data Type
 In contrast to other Python data types that only store one value as an element, a dictionary
stores a key:value pair.
 A dictionary is an unordered collection of data values that is used to store data values like
a map.
 To make the dictionary more efficient, key-value is provided. In a dictionary, a colon (:)
separates each key-value pair, while a "comma" separates each key.
 A string of elements enclosed in curly {} braces and separated by a "comma" in Python
can be used to form a dictionary.
 While keys in a dictionary must be immutable and cannot be duplicated, values can be of
any datatype.
 The built-in function dict() can also be used to generate the dictionary.
 Simply putting it in curly braces{} will create an empty dictionary.
Note: Dictionary keys are case-sensitive; various key cases will be handled differently
even if they have the same name.
 Accessing an element from a dictionary can also be facilitated via the get() method.

Topic-4: Conditionals Statements:

Python statements that offer a control flow option based on a condition are known as conditional
statements. It indicates that the Python program's control flow will be determined by the condition's
result.

If Conditional Statement: The if statement is used if the condition is true and the block's simple code is
to be executed. When the aforementioned condition is met, the block's code executes; otherwise, it does
not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Example:
num = 10
if num > 5:
print("The number is greater than 5.")

Output:
The number is greater than 5.

If else Conditional Statement: When the if condition is false, the extra block of code is combined into
an else statement and executed in a conditional if statement.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Example:
num = 3
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

Output:
The number is odd.

Nested if..else Conditional Statement: An if-else expression inside another if statement is called nested
if..else. Or, to put it simply, a nested if statement is a statement that has an outer if statement and an inner
if-else statement. One if/else if statement can be used inside another if/else if statement.

Example:
num = 15
if num > 10:
if num % 5 == 0:
print("The number is greater than 10 and divisible by 5.")
else:
print("The number is greater than 10 but not divisible by 5.")
else:
print("The number is 10 or less.")

Output:
The number is greater than 10 and divisible by 5.

If-elif-else Conditional Statement: The top-down approach is used to execute the if statements. The
statement linked to that if is performed and the remainder of the ladder is omitted as soon as one of the
conditions governing the if is true. The last "else" phrase will be run if none of the conditions are met.

Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")

Output:
Grade: B

Ternary Expression Conditional Statement: After determining whether a condition is true or false, the
Python ternary expression returns the appropriate value based on the outcome. When we need to assign a
value to a variable based on a straightforward condition and wish to write more compact code, the ternary
expression comes in handy. It just requires one line of code.
Syntax:
[on_true] if [expression] else [on_false]
expression: conditional_expression | lambda_expr

Example:
age = 18
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)

Output:
Status: Adult

Topic-5: Loops:

While loop:
A while loop in Python is used to repeatedly run a block of statements until a specified condition is met.
The line that appears right after the program's loop is run when the condition is changed to false.
Syntax:
while expression:
statement(s)

Example:
count = 0
while count < 5:
print("Count is:", count)
count += 1

Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Else statement with While Loop: The else clause is only used when your while condition is false. It will
not be run if you exit the loop or raise an exception.
Syntax:
while condition:
# execute these statements
else:
# execute these statements

Example:
count = 0
while count < 3:
print("Count is:", count)
count += 1
else:
print("Condition is false, exiting loop.")

Output:
Count is: 0
Count is: 1
Count is: 2
Condition is false, exiting loop.

For Loop: For sequential traversal, for loops are employed. For instance, navigating through a list, text,
array, etc. The "for in" loop in Python is comparable to the foreach loop in other programming languages.
Syntax:
for iterator_var in sequence:
statements(s)

Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Fruit:", fruit)

Output:
Fruit: apple
Fruit: banana
Fruit: cherry

else Statement with for Loop: Like with a while loop, we can likewise combine an else statement with
a for loop. However, since the for loop lacks a condition that would cause the execution to end, the
otherwise block will be run as soon as the for loop is finished.

Example:
numbers = [1, 2, 3]
for num in numbers:
print("Number:", num)
else:
print("All numbers processed.")

Output:
Number: 1
Number: 2
Number: 3
All numbers processed.

Nested Loop: The Python programming language enables the usage of nested loops, which are loops
inside loops.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)

Example:
for i in range(1, 4): # Outer loop
for j in range(1, 3): # Inner loop
print(f"Outer: {i}, Inner: {j}")

Output:
Outer: 1, Inner: 1
Outer: 1, Inner: 2
Outer: 2, Inner: 1
Outer: 2, Inner: 2
Outer: 3, Inner: 1
Outer: 3, Inner: 2

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

Loop Control Statements: Loop control statements alter the order in which things are executed. All
automatic objects produced within a scope are deleted when execution exits it. The following control
statements are supported by Python.

1. Continue Statement: Python's continue statement puts the loop's control back at the start.

Example:
for i in range(5):
if i == 2:
continue
print("Number:", i)

Output:
Number: 0
Number: 1
Number: 3
Number: 4

2. Break Statement: break command removes control from the loop.

Example:
for i in range(5):
if i == 3:
break
print("Number:", i)

Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
3. Pass Statement: To create empty loops in Python, we utilise the pass statement. Empty control
statements, functions, and classes can also be passed.

Example:
for i in range(5):
if i == 2:
pass # Placeholder, does nothing
print("Number:", i)

Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

Part-2: Lists,Sets,Tuples,Dictionaries:

Topic-1: Working with strings:

 A series of characters is called a string.


 Anything enclosed in quotations is treated as a string in Python.
 Letters, numbers, and symbols are all included in this.
 A single character is a string of length 1 since Python lacks a character data type.
 Either single (‘) or double (“) quotes can be used to create strings.
 Triple quotes ("' or "") can be used if a string needs to span more than one line.

Accessing characters of the string:


Since Python strings are collections of characters, indexing can be used to retrieve individual characters.
From end to finish, strings are indexed from 0 to -1. As a result, we can extract particular characters from
the string.

P A R U L U N I V E R S I T Y
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Example:
s = "ParulUniversity"
# Accesses first character: 'P'
print(s[0])

# Accesses 5th character: 'l'


print(s[4])

Accessing characters of the string with negative indexing:

In Python, characters from the back of the string can be accessed using negative address references; for
example, -1 denotes the last character, -2 the second-to-last, and so forth.

Example:
s = "ParulUniversity"

# Accesses 6th character: 'U'


print(s[-10])

# Accesses 5th character from end: 'r'


print(s[-5])

String slicing:
By providing the start and end indexes, slicing allows you to retrieve a piece of a string. String[start:end]
is the syntax for slicing, where start is the starting index and end is the stopping index (excluded).

Example:
s = "ParulUniversity"

# Retrieves characters from index 1 to 3: 'aru'


print(s[1:4])

# Retrieves characters from beginning to index 2: 'Par'


print(s[:3])

# Retrieves characters from index 3 to the end: 'ulUniversity'


print(s[3:])

# Reverse a string
print(s[::-1])

Immutable nature:
Python strings cannot be changed. This implies that once they are produced, they cannot be altered. If
string manipulation is required, we can construct new strings based on the original by using techniques
like formatting, slicing, and concatenation.

Example:
s = "ParulUniversity"

# Trying to change the first character raises an error


# s[0] = 'I' # Uncommenting this line will cause a TypeError
# Instead, create a new string
s = "G" + s[1:]
print(s)

Delete string:
Since strings are immutable in Python, it is not feasible to remove individual characters from a string. On
the other hand, the del keyword allows us to remove a whole string variable.

Example:
s = "PU"

# Deletes entire string


del s

Update string:
Since strings are immutable, updating a portion of them requires creating a new string.

Example:
s = "ParulUniversity"

# Updating by creating a new string


s1 = "u" + s[1:]

# replacnig " Paruluniversity " with "ParulUniversity"


s2 = s.replace("Paruluniversity ", " ParulUniversity ")
print(s1)
print(s2)

Built-in string functions:


Python comes with a number of built-in string manipulation functions. Here are a few of the best
techniques.

1. len(): This function yields the string's total character count.

Example:
s = " ParulUniversity "
print(len(s))

2. upper() and lower(): The upper() methods change all characters to capital letters. All characters are
changed to lowercase using the lower() technique.

Example:
s = "Hello"
print(s.upper()) # output: HELLO
print(s.lower()) # output: hello

3.strip() and replace(): strip() eliminates the string's leading and trailing whitespace, while replace(old,
new) swaps out every instance of a given substring for another.

Example:
s = " Pu "
# Removes spaces from both ends
print(s.strip())
s = "Python is good"
# Replaces 'good' with 'awesome'
print(s.replace("good", "awesome"))

4.Concatenation and Repeatation:


Strings can be repeated using the * operator and concatenated with the + operator.
The + operator can be used to combine strings.

Example:
s1 = "Parul"
s2 = "University"
s3 = s1 + " " + s2
print(s3)

Output:
Parul University

s = "Parul "
print(s * 3)

Output:
Parul Parul Parul

String formatting:
There are multiple ways to add variables inside strings in Python.
1. f-strings: f-strings are the most popular and straightforward method for formatting strings.

Example:
name = "Aarti"
age = 21
print(f"Name: {name}, Age: {age}")

Output:
Name: Aarti, Age: 21

2. format(): The format() method is an additional method for formatting strings.

Example:
s = "My name is {} and I am {} years old.".format("Aarti", 21)
print(s)

Output:
My name is Aarti and I am 21 years old.

3. ‘in’ keyword: The in keyword determines if a specific substring is contained in a string.


Example:
s = "ParulUniversity"
print("Parul" in s)
print("Pu" in s)

Output:
True
False

Topic-2: Lists:

 An ordered collection of items can be stored in a list, a built-in data structure in Python.
 Lists can have their contents altered after they have been constructed because they are mutable.
 Numerous data kinds, such as texts, floats, integers, and even other lists, can be stored in them.
 In Python, we can use the list() constructor or square brackets [] to create a list.
 By providing the list() method with an iterable (such as a string, tuple, or another list), we can
also generate a list.
 The multiplication operator can be used to generate a list with repeated members.

Example:
# List of integers
a = [1, 2, 3, 4, 5]

# List of strings
b = ['apple', 'banana', 'mango']

# Mixed data types


c = [9, 'hi', 5.52, True]

# From a tuple
d = list((1, 2, 3, 'apple', 5.5))

# Create a list [9, 9, 9, 9, 9]


a = [9] * 5

print(a)
print(b)
print(c)
print(d)

Adding elements:
The following techniques allow us to add items to a list:
 append(): Appends an element to the list's end.
 extend(): Appends a number of items to the list's end.
 insert(): Inserts a component at a given location.

Example:
# Initialize an empty list
a = []

# Adding 9 to end of list


a.append(10)
print("After append(9):", a)

# Inserting 3 at index 0
a.insert(0, 3)
print("After insert(0, 3):", a)

# Adding multiple elements [3, 2, 9] at the end


a.extend([3, 2, 9])
print("After extend([3, 2, 9]):", a)

Update elements:
By utilising its index to access an element, we can modify its value.

Example:
a = [1, 2, 3, 4, 5]
# Change the second element
a[1] = 15
print(a)

Remove elements:
We can use the following to eliminate items from a list:
 remove(): Eliminates an element's initial occurrence.
 pop(): Eliminates the element at a given index, or the final element in the absence of an index.
 An element at a certain index is deleted using the del command.
Example:
a = [1, 2, 3, 4, 5]
# Removes the first occurrence of 3
a.remove(3)
print("After remove(3):", a)
# Removes the element at index 1 (2)
popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)
# Deletes the first element (10)
del a[0]
print("After del a[0]:", a)

Output:
After remove(3): [1, 2, 4, 5]
Popped element: 2
After pop(1): [1, 4, 5]
After del a[0]: [4, 5]

Iteration:
 Using a for loop or other iteration techniques, we can quickly iterate the lists.
 When we want to perform an operation on each item or retrieve particular items based on
predetermined criteria, iterating across lists is helpful.

Example:
a = ['apple', 'banana', 'mango']
# Iterating over the list
for item in a:
print(item)

Nested lists and multi-dimensional lists:


A nested list, which is helpful for describing matrices or tables, is a list inside another list. Chaining
indexes allows us to access nested elements.

Example:
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
# Access element at row 2, column 3
print(matrix[1][2])

Topic-3: Sets:
 In Python programming, an unordered collection data type with no duplicate elements that is
iterable is called a set.
 Individual items within a set must be immutable and cannot be altered directly, even if sets are
changeable, meaning you can add or delete elements after they are created.
 { } is used to represent sets, which are values enclosed in curly braces.
 Using a set instead of a list offers the main benefit of having a highly optimised way to determine
whether a particular piece is part of the set.
 This is predicated on a hash table, a type of data structure.
 We cannot use indexes to access items in sets as we do in lists because sets are not ordered.

Example:
# typecasting list to set
myset = set(["A", "B", "C"])
print(myset)
# Adding element to the set
myset.add("D")
print(myset)

Output:
{'C', 'B', 'A'}
{'D', 'C', 'B', 'A'}

Frozen sets:
 In Python, frozen sets are immutable objects that only allow operators and methods that yield a
result without changing the frozen set or sets they are applied to.
 Python's frozenset() method can be used for this.
 Although a set's components can be changed at any moment, the frozen set's components don't
change once it is created.
 It returns an empty frozenset if no parameters are supplied.
Example:
# Same as {"A", "B","C"}
normal_set = set(["A", "B","C"])

print("Normal Set")
print(normal_set)

# A frozen set
frozen_set = frozenset(["E", "F", "G"])

print("\nFrozen Set")
print(frozen_set)

# Uncommenting below line would cause error as


# we are trying to add element to a frozen set
# frozen_set.add("H")

 This is predicated on a hash table, a type of data structure.


 A linked list is created when multiple values are present at the same index point and are appended
to that index position.
 The key being the members set with higher optimisations to the time complexity, Python sets are
constructed using a dictionary with dummy variables.

Topic-4: Tuples:

 A Python tuple is a group of items with commas between them.


 In terms of indexing, nested objects, and repetition, a tuple and a Python list are comparable;
nevertheless, the primary distinction between the two is that a Python tuple is immutable, whereas
a Python list is mutable.
 Tuples cannot be changed, in contrast to Python lists.
 A Few Features of Python's Tuples.
 Similar to lists, tuples are ordered, and their index values allow us to retrieve their elements.
 Once a tuple is constructed, we are unable to update its contents.
 It is not possible to append or extend tuples.
 Once a tuple is generated, we are unable to delete things from it.

Accessing values in tuples:


 Python tuples offer two methods for accessing a tuple's elements.
 In Python, we can retrieve values from tuples by enclosing them in square brackets.

Example:
t = (5, 50, 500)
print("Value in t[0] = ", t[0])
print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])

Here, we will use the negative index inside [], whereas in the previous approaches, we used the positive
index to access the value in Python.

Example:
t = (5, 50, 500)
print("Value in t[-1] = ", t[-1])
print("Value in t[-2] = ", t[-2])
print("Value in t[-3] = ", t[-3])

Topic-5: Dictionaries:

 A data structure that holds values in key: value pairs is called a Python dictionary.
 While keys in a dictionary must be immutable and cannot be duplicated, values can be any data
type.
 For instance, the information is kept in dictionaries as key-value pairs, which facilitates value
discovery.
Syntax:
dict_var = {key1 : value1, key2 : value2, …..}

Note: Dictionary keys are case-sensitive; various key cases will be handled differently even if they have
the same name.

Example:
d1 = {}
print("Empty Dictionary: ")
print(d1)

d2 = dict({1: 'Parul University', 2: 'University'})


print("\nDictionary with the use of dict(): ")
print(d2)

d3 = dict([(1, 'Parul'), (2, 'University')])


print("\nDictionary with each item as a pair: ")
print(d3)

Adding elements:
 There are several methods for adding items.
 By defining the value and the key together, such as Dict[Key] = "Value," one value at a time can
be added to a dictionary.
 Example: Include Items of Various DataTypes in a Python Dictionary
 Layering dictionaries inside the main dictionary, adding components with different data types,
and changing the value of a key.
 The program demonstrates how to work with dictionaries in Python.

Example:
d = {}
print("Empty Dictionary: ")
print(d)

d[0] = 'Parul'
d[2] = 'University'
d[3] = 1
print("\nDictionary after adding 3 elements: ")
print(d)
d['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(d)

d[2] = 'Welcome'
print("\nUpdated key value: ")
print(d)
d[5] = {'Nested': {'1': 'Life', '2': 'Journey'}}
print("\nAdding a Nested Key: ")
print(d)

Output:
Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Parul', 2: 'University', 3: 1}

Dictionary after adding 3 elements:


{0: 'Parul', 2: 'University', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:


{0: ‘Parul', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'Parul', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Journey'}}}

Note: If the key-value pair already exists, the value is changed when a value is added; if not, a new key
with the value is added to the dictionary.

Accessing elements:
Use a dictionary's key name to access its contents. Inside square brackets, the key can be utilised.

Example:
d = {1: 'University', 'name': ' Parul ', 3: ‘PU'}
print("Accessing a element using key:")
print(d['name'])
print("Accessing a element using key:")
print(d[1])

Accessing an element from a dictionary can also be facilitated via the get() method. This function returns
the value after accepting the key as an input.

Example:
d = {1: 'University', 'name': ' Parul ', 3: ‘PU'}
print("Accessing a element using get:")
print(d.get(3))

Accessing elements of nested dictionary:


Use the indexing [] technique to retrieve the value of any key in the nested dictionary.

Example:
d = {'Dict1': {1: 'University'},
'Dict2': {'Name': 'Parul'}}

print(d['Dict1'])
print(d['Dict1'][1])
print(d['Dict2']['Name'])

Deleting elements:
The del keyword, as shown below, can be used to remove dictionary elements.

Example:
d = {1: 'Parul', 'name': 'University'}

print("Dictionary =")
print(d)
del(d[1])
print("Data after deletion Dictionary=")
print(d)

Output:
Dictionary =
{1: 'Parul', 'name': 'University'}
Data after deletion Dictionary=
{'name': 'University'}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy