0% found this document useful (0 votes)
22 views113 pages

Unit - IV

Uploaded by

nuenarrativesque
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views113 pages

Unit - IV

Uploaded by

nuenarrativesque
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 113

Dr. B.

Dhiyanesh
Associate Professors / CSE – E Tech
SRM Institute of Science and Technology,
Vadapalani Campus, Chennai

21CSS101J - PROGRAMMING FOR PROBLEM SOLVING

21CSC203P - Advanced Programming Practice - SRMIST - VDP 1


COURSE LEARNING RATIONALE
CLR-1: Think and evolve with a logic to construct an algorithm and pseudocode that can be

converted into a program

CLR-2: Utilize the appropriate operators and control statements to solve engineering

problems

CLR-3: Store and retrieve data in a single and multidimensional array

CLR-4: Create custom designed functions to perform repetitive tasks in any application

CLR-5: Create basic Abstract Data Types with python

CLR-6: Create applications using suitable python library functions for solving data

science problems.
21CSC203P - Advanced Programming Practice - SRMIST - VDP 2
COURSE OUTCOME
CLO-1:To solve problems through computer programming. Express the basic data types and
variables in C
CLO-2:To use appropriate data types in simple data processing applications. To create programs
using the concept of arrays.
CLO-3:To create string processing applications with single and multi-dimensional arrays.
CLO-4:To create user defined functions with required operations. To implement pointers in
applications with dynamic memory requirements.
CLO-5:To create programs using the python data types, loops, control statements for problem
solving
CLO-6:To implement the suitable python library based solutions for solving statistical problems
in data science
21CSC203P - Advanced Programming Practice - SRMIST - VDP 3
CONTINUOUS LEARNING ASSESSMENT (CLA)

CLA-1: Formative - Average of unit test (50% weightage)

CLA-2: Project Based Learning (10% weightage)

Summative Final Examination (40% weightage)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 4


TEXT BOOK
• Programming in C, E.Balagurusamy,Mc Graw Hill, Eighth Edition.2019.
• Problem Solving & Programming Concepts, Maureen Sprankle, Jim Hubbard, Prentice
Hall, Ninth Edition.

• https://www.tutorialspoint.com/cprogramming/index.htm
• https://www.geeksforgeeks.org/c-programming-language/

21CSC203P - Advanced Programming Practice - SRMIST - VDP 5


Unit - IV
Python: Introduction to Python - Introduction to Google Colab - Basic Data Types: Integers,

Floating Points, Boolean types - Working with String functions - Working with Input, Output

functions - Python-Single and Multi line Comments/ Error Handling - Conditional & Looping

Statements : If, for, while statements - Working with List structures - Working with Tuples

data structures - Working with Sets - Working with Dictionaries - Introduction to Python

Libraries - Introduction to Numpy - High Dimensional Arrays

21CSC203P - Advanced Programming Practice - SRMIST - VDP 6


INTRODUCTION TO PYTHON
• Python is a popular, high-level programming language known for its simplicity and
readability, which makes it great for beginners and professionals alike.
• It was created by Guido van Rossum and first released in 1991. Python’s design philosophy
emphasizes code readability, using significant whitespace and an easy-to-understand syntax.
• Here’s a brief introduction to key aspects of Python:
• 1. Easy to Learn and Use
• Python’s simple syntax resembles the English language, allowing developers to focus on
solving problems rather than understanding the syntax itself.
• This makes it an ideal language for new programmers.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 7


• 2. Interpreted Language
• Python is an interpreted language, which means code is executed line by line, making
debugging easier.
• It also supports interactive sessions, making it ideal for experimentation and testing.
• 3. Object-Oriented Programming (OOP)
• Python supports object-oriented programming, which helps organize code by grouping it
into objects.
• OOP in Python includes principles like inheritance, encapsulation, and polymorphism.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 8


• 4. Extensive Libraries and Frameworks
• Python has a vast standard library and thousands of third-party libraries.
• Some popular libraries include:
• NumPy and Pandas for data analysis
• TensorFlow and PyTorch for machine learning
• Django and Flask for web development
• SciPy for scientific computing
• 5. Cross-Platform
• Python works on various platforms, including Windows, macOS, and Linux, making it
versatile for development.
21CSC203P - Advanced Programming Practice - SRMIST - VDP 9
• 6. Community Support
• Python has a large and active community.
• This means extensive documentation, tutorials, and support forums are available, which
is helpful for troubleshooting and advancing your skills.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 10


• 8. Applications of Python
• Python is used in various fields:
• Web Development
• Data Science and Machine Learning
• Automation and Scripting
• Software Development
• Cybersecurity

21CSC203P - Advanced Programming Practice - SRMIST - VDP 11


• # This is a single-line comment • # Conditional statements
• print("Hello, World!") • if x > 2:
• # Output: Hello, World! • print("x is greater than 2")
• # Variables • # Loops
• x=5 • for i in range(3):
• y = "Python“ • print(i)
• print(x, y) • #Output: 0, 1, 2
• # Output: 5 Python

21CSC203P - Advanced Programming Practice - SRMIST - VDP 12


• # Function definition
• def greet(name):
• return f "Hello, {name}“
• print(greet("Alice"))
• # Output: Hello, Alice

21CSC203P - Advanced Programming Practice - SRMIST - VDP 13


INTRODUCTION TO GOOGLE COLAB
• Google Colab (short for "Colaboratory") is a free, cloud-based platform by Google that allows you
to write, run, and share Python code, especially for data science and machine learning projects.
• It is essentially a Jupyter notebook environment that runs in the cloud, making it easy for users to
develop and collaborate without needing a powerful local machine.
• Key Features of Google Colab
• Free Access to GPUs and TPUs
• Colab offers access to Graphics Processing Units (GPUs) and Tensor Processing Units (TPUs)
for free, which are essential for faster computation, especially in machine learning and deep
learning.
• You can switch to these high-performance resources with a single click.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 14


• Python Pre-Installed and Ready to Use
• Colab comes with Python and many popular libraries pre-installed, such as NumPy, Pandas,
TensorFlow, Keras, and more.
• This means you can start coding immediately without worrying about setup and installation.
• Interactive Jupyter Notebook Interface
• Colab uses the Jupyter Notebook format, which lets you write code and documentation in
the same environment.
• You can insert code, text (using Markdown), images, and more, making it easy to document
and explain your work step by step.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 15


• Easy Collaboration and Sharing
• Colab integrates seamlessly with Google Drive, making it easy to save and share notebooks.
• You can invite others to view or edit your notebooks, similar to Google Docs, which is ideal
for team projects or sharing work with others.
• Libraries and Tools for Data Science
• Colab supports popular libraries and frameworks for data science, such as TensorFlow,
PyTorch, OpenCV, and SciPy, among others.
• It also has tools for data visualization, including Matplotlib and Seaborn, enabling you to
analyze data and create charts directly in your notebook.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 16


• Code and Output Cells
• Each Colab notebook is composed of cells. Code cells are where you enter your Python code, and
you can run each cell independently.
• Output from the code cells, including tables, graphs, or other results, is displayed directly below the
cell, providing an interactive way to view and test results.
• Auto-Save and Version Control
• Notebooks are automatically saved in your Google Drive account, and you can revert to previous
versions if needed.
• Notebook Extensions
• Google Colab has many helpful extensions, such as a file manager, terminal access, and utilities for
managing long-running code.
21CSC203P - Advanced Programming Practice - SRMIST - VDP 17
GETTING STARTED WITH GOOGLE COLAB
• To start with Colab:
• Go to Google Colab and sign in with a Google account.
• You can create a new notebook, upload an existing Jupyter notebook, or open a notebook
from Google Drive or GitHub.
• Once in the notebook, you can add cells, write code, add Markdown text, and run each
cell independently.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 18


POPULAR USE CASES FOR GOOGLE COLAB
• Data Analysis and Visualization:
• Analyze large datasets, visualize data, and create insights directly in the cloud.
• Machine Learning:
• Run machine learning and deep learning experiments without needing a high-performance local
machine.
• Educational Tutorials and Demos:
• Colab is popular for creating and sharing educational content, tutorials, and hands-on examples.
• Prototyping and Experimenting:
• Quickly prototype ideas or run experiments and easily share them with others for feedback.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 19


PYTHON DATA TYPES
• Every value has a datatype, and variables can hold values.
• Python is a powerfully composed language; consequently, we don't have to characterize the sort
of variable while announcing it. The interpreter binds the value implicitly to its type.
• a=5
• We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.
• We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.
• Consider the following illustration when defining and verifying the values of various data
types.
21CSC203P - Advanced Programming Practice - SRMIST - VDP 20
• a=10
• b="Hi Python"
• c = 10.5
• print(type(a)) Output:
• print(type(b)) <type 'int'>
• print(type(c)) <type 'str'>
<type 'float'>

21CSC203P - Advanced Programming Practice - SRMIST - VDP 21


STANDARD DATA TYPES
• A variable can contain a variety of values. On the other hand, a person's id must be stored as
an integer, while their name must be stored as a string.
• The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary

21CSC203P - Advanced Programming Practice - SRMIST - VDP 22


• Numbers
• Numeric values are stored in numbers.
• The whole number, float, and complex qualities have a place with a Python Numbers
datatype.
• Python offers the type() function to determine a variable's data type.
• The instance () capability is utilized to check whether an item has a place with a specific
class.
• When a number is assigned to a variable, Python generates Number objects. For instance,

21CSC203P - Advanced Programming Practice - SRMIST - VDP 23


• a=5
• print("The type of a", type(a)) Output:

• b = 40.5 The type of a <class 'int'>


• print("The type of b", type(b)) The type of b <class 'float'>
The type of c <class 'complex'>
• c = 1+3j c is complex number: True
• print("The type of c", type(c))
• print(" c is a complex number", isinstance(1+3j,complex))

21CSC203P - Advanced Programming Practice - SRMIST - VDP 24


• Python supports three kinds of numerical data.
• Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on.
An integer can be any length you want in Python. Its worth has a place with int.
• Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
• Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify
the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 25


SEQUENCE TYPE
• String
• The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.
• String dealing with Python is a direct undertaking since Python gives worked-in capabilities
and administrators to perform tasks in the string.
• When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
• Because the operation "Python" *2 returns "Python," the operator * is referred to as a
repetition operator.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 26


• The Python string is demonstrated in the following example.
• str = "string using double quotes"
• print(str)
Output:
• s = '''''A multiline
• string''' string using double quotes
A multiline
• print(s) string

21CSC203P - Advanced Programming Practice - SRMIST - VDP 27


• str1 = 'hello javatpoint' #string str1
• str2 = ' how are you' #string str2
• print (str1[0:2]) #printing first two character using slice operator
• print (str1[4]) #printing 4th character of the string
• print (str1*2) #printing the string twice
• print (str1 + str2) #printing the concatenation of str1 and str2
Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you
21CSC203P - Advanced Programming Practice - SRMIST - VDP 28
LIST
• Lists in Python are like arrays in C, but lists can contain data of different types.
• The things put away in the rundown are isolated with a comma (,) and encased inside square
sections [].
• To gain access to the list's data, we can use slice [:] operators.
• Like how they worked with strings, the list is handled by the concatenation operator (+) and
the repetition operator (*).
• Look at the following example.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 29


• list1 = [1, "hi", "Python", 2]
• #Checking type of given list
• print(type(list1)) Output:
• #Printing the list1
• print (list1)
[1, 'hi', 'Python', 2]
[2]
• # List slicing
[1, 'hi']
• print (list1[3:])
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
• # List slicing [1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
• print (list1[0:2])
• # List Concatenation using + operator
• print (list1 + list1)
• # List repetation using * operator
• print (list1 * 3)
21CSC203P - Advanced Programming Practice - SRMIST - VDP 30
TUPLE
• In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types.
• A parenthetical space () separates the tuple's components from one another.
• Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
• Let's look at a straightforward tuple in action.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 31


• tup = ("hi", "Python", 2)
• # Checking type of tup Output:
• print (type(tup))
<class 'tuple'>
• #Printing the tuple ('hi', 'Python', 2)
• print (tup) ('Python', 2)
• # Tuple slicing ('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
• print (tup[1:])
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
• print (tup[0:1])
• # Tuple concatenation using + operator Traceback (most recent call last):
• print (tup + tup) File "main.py", line 14, in <module>
t[2] = "hi";
• # Tuple repatation using * operator
TypeError: 'tuple' object does not support item assignment
• print (tup * 3)
• # Adding value to tup. It will throw an error.
• t[2] = "hi"

21CSC203P - Advanced Programming Practice - SRMIST - VDP 32


DICTIONARY
• A dictionary is a key-value pair set arranged in any order.
• It stores a specific value for each key, like an associative array or a hash table.
• Value is any Python object, while the key can hold any primitive data type.
• The comma (,) and the curly braces are used to separate the items in the dictionary.
• Look at the following example.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 33


• d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
• # Printing dictionary
Output:
• print (d)
• # Accesing value using keys 1st name is Jimmy
2nd name is mike
• print("1st name is "+d[1]) {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
• print("2nd name is "+ d[4]) dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
• print (d.keys())
• print (d.values())

21CSC203P - Advanced Programming Practice - SRMIST - VDP 34


BOOLEAN
• True and False are the two default values for the Boolean type.
• These qualities are utilized to decide the given assertion valid or misleading.
• The class book indicates this. False can be represented by the 0 or the letter "F," while true
can be represented by any value that is not zero.
• Look at the following example.
• # Python program to check the boolean type
• print(type(True)) Output:

• print(type(False)) <class 'bool'>


<class 'bool'>
• print(false) NameError: name 'false' is not defined

21CSC203P - Advanced Programming Practice - SRMIST - VDP 35


SET
• The data type's unordered collection is Python Set.
• It is iterable, mutable(can change after creation), and has remarkable components.
• The elements of a set have no set order; It might return the element's altered sequence.
• Either a sequence of elements is passed through the curly braces and separated by a comma
to create the set or the built-in function set() is used to create the set.
• It can contain different kinds of values.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 36


• # Creating Empty set
• set1 = set()
• set2 = {'James', 2, 3,'Python'}
• #Printing Set value Output:
• print(set2)
{3, 'Python', 'James', 2}
• # Adding element to the set {'Python', 'James', 3, 2, 10}
• set2.add(10) {'Python', 'James', 3, 10}
• print(set2)
• #Removing element from the set
• set2.remove(2)
• print(set2)
21CSC203P - Advanced Programming Practice - SRMIST - VDP 37
PYTHON STRING METHODS
• Python string methods is a collection of in-built Python functions that operates on lists.
• Note: Every string method in Python does not change the original string instead returns a new
string with the changed attributes.
• Python string is a sequence of Unicode characters that is enclosed in quotation marks.
• In this article, we will discuss the in-built string functions i.e. the functions provided by
Python to operate on strings.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 38


CASE CHANGING OF PYTHON STRING METHODS
• The below Python functions are used to change the case of the strings.
• Let’s look at some Python string methods with examples:
• lower(): Converts all uppercase characters in a string into lowercase
• upper(): Converts all lowercase characters in a string into uppercase
• title(): Convert string to title case
• swapcase(): Swap the cases of all characters in a string
• capitalize(): Convert the first character of a string to uppercase

21CSC203P - Advanced Programming Practice - SRMIST - VDP 39


• text = 'geeKs For geEkS'
Output
• print("\nConverted String:") Converted String:
• print(text.upper()) GEEKS FOR GEEKS
• print("\nConverted String:")
Converted String:
• print(text.lower()) geeks for geeks
• print("\nConverted String:")
Converted String:
• print(text.title())
Geeks For Geeks
• print("\nConverted String:")
• print(text.swapcase()) Converted String:
GEEkS fOR GEeKs
• print("\nConverted String:")
• print(text.capitalize()) Original String
geeKs For geEkS
• print("\nOriginal String")
• print(text)
21CSC203P - Advanced Programming Practice - SRMIST - VDP 40
LIST OF STRING METHODS IN PYTHON
Function Name Description
capitalize() Converts the first character of the string to a capital (uppercase) letter
casefold() Implements caseless string matching
center() Pad the string with the specified character.
count() Returns the number of occurrences of a substring in the string.
encode() Encodes strings with the specified encoded scheme
endswith() Returns “True” if a string ends with the given suffix
Specifies the amount of space to be substituted with the “\t” symbol in the
expandtabs()
string
find() Returns the lowest index of the substring if it is found
format() Formats the string for printing it to console
format_map() Formats specified values in a string using a dictionary

21CSC203P - Advanced Programming Practice - SRMIST - VDP 41


Function Name Description
index() Returns the position of the first occurrence of a substring in a string
isalnum() Checks whether all the characters in a given string is alphanumeric or not
isalpha() Returns “True” if all characters in the string are alphabets
isdecimal() Returns true if all characters in a string are decimal
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
islower() Checks if all characters in the string are lowercase
isnumeric() Returns “True” if all characters in the string are numeric characters
Returns “True” if all characters in the string are printable or the string is
isprintable()
empty
isspace() Returns “True” if all characters in the string are whitespace characters
istitle() Returns “True” if the string is a title cased string

21CSC203P - Advanced Programming Practice - SRMIST - VDP 42


Function Name Description
isupper() Checks if all characters in the string are uppercase
join() Returns a concatenated String
ljust() Left aligns the string according to the width specified
lower() Converts all uppercase characters in a string into lowercase
lstrip() Returns the string with leading characters removed
maketrans() Returns a translation table
partition() Splits the string at the first occurrence of the separator
replace() Replaces all occurrences of a substring with another substring
rfind() Returns the highest index of the substring
rindex() Returns the highest index of the substring inside the string
rjust() Right aligns the string according to the width specified
rpartition() Split the given string into three parts

21CSC203P - Advanced Programming Practice - SRMIST - VDP 43


Function Name Description
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
startswith() Returns “True” if a string starts with the given prefix
strip() Returns the string with both leading and trailing characters
swapcase() Converts all uppercase characters to lowercase and vice versa
title() Convert string to title case
translate() Modify string according to given translation mappings
upper() Converts all lowercase characters in a string into uppercase
Returns a copy of the string with ‘0’ characters padded to the left side of the
zfill()
string
rsplit() Split the string from the right by the specified separator

21CSC203P - Advanced Programming Practice - SRMIST - VDP 44


WORKING WITH INPUT, OUTPUT FUNCTIONS
• Python input() function is used to get input from the user. It prompts for the user input and
reads a line.
• After reading data, it converts it into a string and returns that.
• It throws an error EOFError if EOF is read.
• input ([prompt])
• Parameters
• Prompt: It is a string message which prompts for the user input.
• Return
• It returns user input after converting into a string.
• Let's see some examples of input() function to understand it's functionality.
21CSC203P - Advanced Programming Practice - SRMIST - VDP 45
PYTHON INPUT() FUNCTION EXAMPLE 1
• # Python input() function example
• # Calling function
• val = input("Enter a value: ")
• # Displaying result
• print("You entered:",val)

• Output:
• Enter a value: 45
• You entered: 45

21CSC203P - Advanced Programming Practice - SRMIST - VDP 46


PYTHON INPUT() FUNCTION EXAMPLE 2
• The input() method returns string value. So, if we want to perform arithmetic operations, we
need to cast the value first.
• See the example below.

Output:
• val = input("Enter an integer: ") Enter an integer: 12
Square of the value: 144
• val = int(val) # casting into string
• sqr = (val*val) # getting square
• print("Square of the value:",sqr)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 47


PRINT OUTPUT IN PYTHON
• This function allows us to display text, variables, and expressions on the console. Let’s begin
with the basic usage of the print() function:
• How to Print Output in Python
• In this example, “Hello, World!” is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.
Output
• print("Hello, World!") Hello, World!

• name = "Alice" Output


• age = 30 Name: Alice Age: 30
• print("Name:", name, "Age:", age)
21CSC203P - Advanced Programming Practice - SRMIST - VDP 48
MULTILINE COMMENTS IN PYTHON
• Multiline comments in Python refer to a block of text or statements that are used for
explanatory or documentation purposes within the code.
• Unlike single-line comments denoted by the hash symbol (#), multiline comments are
enclosed by triple double quotes (`”””`) or triple single quotes (`”’`).
• These comments are often utilized to provide detailed explanations, documentation, or notes
about the code, and they can span multiple lines.
• While Python doesn’t have a specific syntax for multiline comments, using triple quotes
achieves a similar effect, as the interpreter ignores the enclosed text.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 49


CONDITIONAL STATEMENTS IN PYTHON
• 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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 50


Statement Description
The if statement is used to test a specific condition. If the condition
If Statement
is true, a block of code (if-block) will be executed.
The if-else statement is similar to if statement except the fact that, it
also provides the block of the code for the false case of the
If - else Statement
condition to be checked. If the condition provided in the if statement
is false, then the else statement will be executed.
Nested if statements enable us to use if ? else statement inside an
Nested if Statement
outer if statement.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 51


THE IF STATEMENT
• The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block.
• The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
• The syntax of the if-statement is given below.
• if expression:
• statement

21CSC203P - Advanced Programming Practice - SRMIST - VDP 52


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

21CSC203P - Advanced Programming Practice - SRMIST - VDP 53


THE IF-ELSE STATEMENT
• The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
• The syntax of the if-else statement is given below.
• if condition:
• #block of statements
• else:
• #another block of statements (else-block)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 54


EXAMPLE 1 : PROGRAM TO CHECK WHETHER A PERSON IS ELIGIBLE TO VOTE
OR NOT.

• # Simple Python Program to check whether a person is eligible to vote or not.


• age = int (input("Enter your age: "))
• # Here, we are taking an integer num and taking input dynamically
• if age>=18:
• # Here, we are checking the condition. If the condition is true, we will enter the block
• print("You are eligible to vote !!");
• else:
Output:
• print("Sorry! you have to wait !!"); Enter your age: 90
You are eligible to vote !!

21CSC203P - Advanced Programming Practice - SRMIST - VDP 55


THE ELIF STATEMENT
• The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them.
• We can have any number of elif statements in our program depending upon our need.
However, using elif is optional.
• The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 56


• The syntax of the elif statement is given below.
• if expression 1:
• # block of statements
• elif expression 2:
• # block of statements
• elif expression 3:
• # block of statements
• else:
• # block of statements

21CSC203P - Advanced Programming Practice - SRMIST - VDP 57


EXAMPLE 1
• number = int(input("Enter the number?"))
• if number==10:
• print("The given number is equals to 10")
• elif number==50:
Output:
• print("The given number is equal to 50"); Enter the number?15
• elif number==100: The given number is not equal to 10, 50 or
100
• print("The given number is equal to 100");
• else:
• print("The given number is not equal to 10, 50 or 100");

21CSC203P - Advanced Programming Practice - SRMIST - VDP 58


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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 59


Sr.No. 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.
This type of loop executes a code block multiple times and
2 For loop
abbreviates the code that manages the loop variable.
3 Nested loops We can iterate a loop inside another loop.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 60


Sr.No. Name of the control statement Description
This command terminates the loop's execution and
1 Break statement transfers the program's control to the statement next
to the loop.
This command skips the current iteration of the
loop. The statements following the continue
2 Continue statement
statement are not executed once the Python
interpreter reaches the continue statement.
The pass statement is used when a statement is
3 Pass statement syntactically necessary, but no code is to be
executed.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 61


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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 62


• numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
• square = 0
• squares = []
• for value in numbers:
• square = value ** 2
• squares.append(square)
• print("The list of squares is", squares)

Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

21CSC203P - Advanced Programming Practice - SRMIST - VDP 63


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).
• range(start, stop, step size)
• # Python program to show the working of range() function
• print(range(15))
Output:
• print(list(range(15))) range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
• print(list(range(4, 9)))
[4, 5, 6, 7, 8]
• print(list(range(5, 25, 4))) [5, 9, 13, 17, 21]

21CSC203P - Advanced Programming Practice - SRMIST - VDP 64


WHILE LOOP
• While loops are used in Python to iterate until a specified condition is met.
• However, the statement in the program that follows the while loop is executed once the
condition changes to false.
• Syntax of the while loop is:
• while <condition>:
• { code block }

21CSC203P - Advanced Programming Practice - SRMIST - VDP 65


• # Python program to show how to use a while loop
• counter = 0
• # Initiating the loop
• while counter < 10: # giving the condition
• counter = counter + 3 Output:
• print("Python Loops") Python Loops
Python Loops
Python Loops
Python Loops

21CSC203P - Advanced Programming Practice - SRMIST - VDP 66


LOOP CONTROL STATEMENTS
• Continue Statement
• It returns the control to the beginning of the loop.
• Code
• # Python program to show how the continue statement works
Output:
• # Initiating the loop
• for string in "Python Loops": Current Letter: P
Current Letter: y
• if string == "o" or string == "p" or string == "t": Current Letter: h
• continue Current Letter: n
Current Letter:
• print('Current Letter:', string) Current Letter: L
Current Letter: s
21CSC203P - Advanced Programming Practice - SRMIST - VDP 67
• Break Statement
• It stops the execution of the loop when the break statement is reached.
• Code
• # Python program to show how the break statement works
Output:
• # Initiating the loop
• for string in "Python Loops": Current Letter: P
Current Letter: y
• if string == 'L': Current Letter: t
• break Current Letter: h
Current Letter: o
• print('Current Letter: ', string) Current Letter: n
Current Letter:
21CSC203P - Advanced Programming Practice - SRMIST - VDP 68
• Pass Statement
• Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.
• Code
• # Python program to show how the pass statement works
• for a string in "Python Loops":
Output:
• pass
• print( 'Last Letter:', string) Last Letter: s

21CSC203P - Advanced Programming Practice - SRMIST - VDP 69


WORKING WITH LIST STRUCTURES
• In Python, a list is a built-in data structure that is used to store an ordered collection of items.
• Lists are mutable, meaning that their contents can be changed after the list has been created.
• They can hold a various of data types, including integers, floats, strings, and even other lists.
• Let’s take a quick example for Python list:

• a = [1, 'apple', 3.14, [5, 6]]


Output
• print(a) [1, 'apple', 3.14, [5, 6]]

21CSC203P - Advanced Programming Practice - SRMIST - VDP 70


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 number of various elements can be stored in a list

21CSC203P - Advanced Programming Practice - SRMIST - VDP 71


ORDERED LIST CHECKING
• # example Output:
• a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
False
• b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
• a == b

• # example Output:
• a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
True
• b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
• a == b

21CSC203P - Advanced Programming Practice - SRMIST - VDP 72


• 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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 73


• list = [1,2,3,4,5,6,7]
• print(list[0])
• print(list[1]) Output:

• print(list[2]) 1
• print(list[3]) 2
3
• print(list[0:6]) # Slicing the elements 4
• print(list[:]) [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
• print(list[2:5]) [3, 4, 5]
• print(list[1:6:2]) [2, 4, 6]

21CSC203P - Advanced Programming Practice - SRMIST - VDP 74


• # negative indexing example
• list = [1,2,3,4,5]
• print(list[-1]) Output:
• print(list[-3:]) 5
• print(list[:-1]) [3, 4, 5]
[1, 2, 3, 4]
• print(list[-3:-1]) [3, 4]

21CSC203P - Advanced Programming Practice - SRMIST - VDP 75


UPDATING LIST VALUES
• list = [1, 2, 3, 4, 5, 6]
• print(list)
• list[2] = 10 # It will assign value to the value to the second index
• print(list)
• list[1:3] = [89, 78] # Adding multiple-element Output:
• print(list)
[1, 2, 3, 4, 5, 6]
• list[-1] = 25 # It will add value at the end of the list [1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
• print(list)
[1, 89, 78, 4, 5, 25]

21CSC203P - Advanced Programming Practice - SRMIST - VDP 76


• The list elements can also be deleted by using the del keyword.
• Python also provides us the remove() method if we do not know which element is to be
deleted from the list.
• list = [1, 2, 3, 4, 5, 6]
• print(list) Output:
• # It will assign value to the value to second index
[1, 2, 3, 4, 5, 6]
• list.remove(6) [1, 2, 3, 4, 5]
• print(list)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 77


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

21CSC203P - Advanced Programming Practice - SRMIST - VDP 78


1. REPETITION
• The redundancy administrator empowers the rundown components to be rehashed on
different occasions.
• # repetition of list
• # declaring the list
• list1 = [12, 14, 16, 18, 20] Output:

• # repetition operator * [12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
• l = list1 * 2
• print(l)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 79


2. CONCATENATION
• It concatenates the list mentioned on either side of the operator.
• # concatenation of two lists
• # declaring the lists
• list1 = [12, 14, 16, 18, 20]
Output:
• list2 = [9, 10, 32, 54, 86]
• # concatenation operator + [12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

• l = list1 + list2
• print(l)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 80


3. LENGTH
• It is used to get the length of the list
• # size of the list
• # declaring the list
• list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
• # finding length of the list
Output:
• len(list1)
9

21CSC203P - Advanced Programming Practice - SRMIST - VDP 81


4. ITERATION
• The for loop is used to iterate over the list elements.
• # iteration of the list
• # declaring the list
Output:
• list1 = [12, 14, 16, 39, 40]
• # iterating 12
14
• for i in list1:
16
• print(i) 39
40

21CSC203P - Advanced Programming Practice - SRMIST - VDP 82


5. MEMBERSHIP
• It returns true if a particular item exists in a particular list otherwise false.
• list1 = [100, 200, 300, 400, 500]
• print(600 in list1)
• print(700 in list1) Output:
• print(1040 in list1)
False
• print(300 in list1) False
• print(100 in list1) False
True
• print(500 in list1) True
True

21CSC203P - Advanced Programming Practice - SRMIST - VDP 83


PYTHON LIST BUILT-IN FUNCTIONS
• Python provides the following built-in functions, which can be used with the lists.
• len()
• max()
• min() Output:

6
• list1 = [12, 16, 18, 20, 39, 40] 40
• print(len(list1)) 12

• print(max(list1))
• print(min(list1))

21CSC203P - Advanced Programming Practice - SRMIST - VDP 84


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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 85


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.
• Forming a Tuple:
• All the objects-also known as "elements"-must be separated by a comma, enclosed in
parenthesis (). Although parentheses are not required, they are recommended.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 86


• empty_tuple = () Output:

• print("Empty tuple: ", empty_tuple) Empty tuple: ()


• int_tuple = (4, 6, 8, 10, 12, 14) Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
• print("Tuple with integers: ", int_tuple) A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
• mixed_tuple = (4, "Python", 9.3)
• print("Tuple with different data types: ", mixed_tuple)
• nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
• print("A nested tuple: ", nested_tuple)

21CSC203P - Advanced Programming Practice - SRMIST - VDP 87


ACCESSING TUPLE ELEMENTS
• A tuple's objects can be accessed in a variety of ways.
• Indexing
• Indexing We can use the index operator [] to access an object in a tuple, where the index
starts at 0.
• tuple = ("Python", "Tuple", "Ordered", "Collection")
• print(tuple[0]) Output:
• print(tuple[1])
Python
Tuple

21CSC203P - Advanced Programming Practice - SRMIST - VDP 88


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 (:).

21CSC203P - Advanced Programming Practice - SRMIST - VDP 89


• tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
• print("Elements between indices 1 and 3: ", tuple_[1:3])
• print("Elements between indices 0 and -4: ", tuple_[:-4])
• 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', 'Collection', 'Objects')

21CSC203P - Advanced Programming Practice - SRMIST - VDP 90


PYTHON SET
• A Python set is the collection of the unordered items.
• Each element in the set must be unique, immutable, and the sets remove the duplicate elements.
• Sets are mutable which means we can modify it after its creation.
• Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index.
• However, we can print them all together, or we can get the list of elements by looping through the set.
• Creating a set
• The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
• Python also provides the set() method, which can be used to create the set by the passed sequence.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 91


• Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

• print(Days)
Output:
• print("looping through the set elements ... ")
• for i in Days: {'Wednesday', 'Sunday', 'Monday', 'Tuesday', 'Thursday', 'Friday', 'Saturday'}
looping through the set elements ...
• print(i) Wednesday
Sunday
Monday
Tuesday
Thursday
Friday
Saturday

21CSC203P - Advanced Programming Practice - SRMIST - VDP 92


ADDING ITEMS TO THE SET
• Python provides the add() method and update() method which can be used to add some
particular item to the set.
• The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set.
• Consider the following example.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 93


• Months = set(["January","February", "March", "April", "May", "June"])
• print("\nprinting the original set ... ")
• print(months)
• print("\nAdding other months to the set...");
Output:
• Months.add("July");
printing the original set ...
• Months.add ("August"); {'February', 'May', 'April', 'March', 'June', 'January'}
• print("\nPrinting the modified set...");
Adding other months to the set...
• print(Months)
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June',
'January'}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 94


PYTHON SET OPERATIONS
• Set can be performed mathematical operation such as union, intersection, difference, and
symmetric difference.
• Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 95


• Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
• Days2 = {"Friday","Saturday","Sunday"}
• print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 96


• Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
• Days2 = {"Friday","Saturday","Sunday"}
• print(Days1.union(Days2)) #printing the union of the sets

Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 97


THE INTERSECTION OF TWO SETS
• To discover what is common between two or more sets in Python, apply the intersection()
function.
• Only the items in all sets being compared are included in the final set. One or more sets can
also be used as the intersection() function parameters.
• The function returns a copy of the set supplied as the lone parameter if there is just one set.
• The method returns a new set that only contains the elements in all the compared sets if
multiple sets are supplied as arguments.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 98


• Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
• Days2 = {"Monday","Tuesday","Sunday", "Friday"}
• print(Days1&Days2) #prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 99


THE INTERSECTION_UPDATE() METHOD
• The intersection_update() method removes the items from the original set that are not present
in both the sets (all the sets if more than one are specified).
• The intersection_update() method is different from the intersection() method since it
modifies the original set by removing the unwanted items, on the other hand, the
intersection() method returns a new set.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 100


• a = {"Devansh", "bob", "castle"}
• b = {"castle", "dude", "emyway"}
• c = {"fuson", "gaurav", "castle"}
• a.intersection_update(b, c)
• print(a)
Output:

{'castle'}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 101


DIFFERENCE BETWEEN THE TWO SETS
• The difference of two sets can be calculated by using the subtraction (-) operator or
intersection() method. Suppose there are two sets A and B, and the difference is A-B that
denotes the resulting set will be obtained that element of A, which is not present in the set B.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 102


• Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
• Days2 = {"Monday", "Tuesday", "Sunday"}
• print(Days1-Days2)

Output:

{'Thursday', 'Wednesday'}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 103


SYMMETRIC DIFFERENCE OF TWO SETS
• In Python, the symmetric Difference between set1 and set2 is the set of elements present in
one set or the other but not in both sets.
• In other words, the set of elements is in set1 or set2 but not in their intersection.
• The Symmetric Difference of two sets can be computed using Python's
symmetric_difference() method.
• This method returns a new set containing all the elements in either but not in both.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 104


• a = {1,2,3,4,5,6}
• b = {1,2,9,8,10}
• c = a^b
• print(c)

• Output:
• {3, 4, 5, 6, 8, 9, 10}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 105


SET COMPARISON
• In Python, you can compare sets to check if they are equal, if one set is a subset or superset of another, or if
two sets have elements in common.
• Here are the set comparison operators available in Python:
• ==: checks if two sets have the same elements, regardless of their order.
• !=: checks if two sets are not equal.
• <: checks if the left set is a proper subset of the right set (i.e., all elements in the left set are also in the right
set, but the right set has additional elements).
• <=: checks if the left set is a subset of the right set (i.e., all elements in the left set are also in the right set).
• >: checks if the left set is a proper superset of the right set (i.e., all elements in the right set are also in the
left set, but the left set has additional elements).
• >=: checks if the left set is a superset of the right set (i.e., all elements in the right set are also in the left).

21CSC203P - Advanced Programming Practice - SRMIST - VDP 106


• Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
• Days2 = {"Monday", "Tuesday"}
• Days3 = {"Monday", "Tuesday", "Friday"}
• print (Days1>Days2)
• print (Days1<Days2)
Output:
• print (Days2 == Days3)
• print (Days1!=Days2) True
False
False
True

21CSC203P - Advanced Programming Practice - SRMIST - VDP 107


PYTHON BUILT-IN SET METHODS
SN Method Description
1 add(item) It adds an item to the set. It has no effect if the item is already present in the set.
2 clear() It deletes all the items from the set.
3 copy() It returns a shallow copy of the set.
4 difference_update(....) It modifies this set by removing all the items that are also present in the specified sets.
5 discard(item) It removes the specified item from the set.
It returns a new set that contains only the common elements of both the sets. (all the sets if more than two are
6 intersection()
specified).
It removes the items from the original set that are not present in both the sets (all the sets if more than one are
7 intersection_update(....)
specified).
8 Isdisjoint(....) Return True if two sets have a null intersection.
9 Issubset(....) Report whether another set contains this set.
10 Issuperset(....) Report whether this set contains another set.
11 pop() Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty.
12 remove(item) Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
13 symmetric_difference(....) Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and another.
Return the union of sets as a new set.
15 union(....)
(i.e. all elements that are in either set.)
16 update() Update a set with the union of itself and others.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 108


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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 109


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.

21CSC203P - Advanced Programming Practice - SRMIST - VDP 110


• Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
• print(type(Employee))
• print("printing Employee data .... ")
• print(Employee)

• Output
• <class 'dict'>
• printing Employee data ....
• {'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}

21CSC203P - Advanced Programming Practice - SRMIST - VDP 111


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.

• Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


• print(type(Employee)) Output
• print("printing Employee data .... ")
<class 'dict'>
printing Employee data ....
• print("Name : %s" %Employee["Name"]) Name : Dev
• print("Age : %d" %Employee["Age"]) Age : 20
Salary : 45000
• print("Salary : %d" %Employee["salary"])
Company : WIPRO
• print("Company : %s" %Employee["Company"])
21CSC203P - Advanced Programming Practice - SRMIST - VDP 112
21CSC203P - Advanced Programming Practice - SRMIST - VDP 113

You might also like