• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
: String, List, Tuple, Dictionary
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Python data handling
1. Prof. K. Adisesha 1
Python Strings
Learning objective:
In this chapter, student will learn to create, format, modify and delete strings in Python. In
addition, we will be introduced to various string operations and functions.
Learn how Python inputs strings
Understand how Python stores and uses strings
Perform slicing operations on strings
Traverse strings with a loop
Compare strings and substrings
Understand the concept of immutable strings
Understanding string functions.
Understanding string constants
String: A String is a sequence of characters, which is enclosed between either single (' ') or
double quotes (" "), python treats both single and double quotes same.
Example:
Single line String: 'Narayana College' is the same as "Narayana College"
Multiline string: '''Narayana College''' is the same as """Narayana College"""
String Assigning:
Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:
Example: a="Narayana College"
Strings are Arrays
Python does not have a character data type
Strings in Python are arrays of bytes representing unicode characters
Single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Indexing Operator [ ]
The individual characters of a string can be accessed using the indexing operator [].
The index of a character in a string is the character's offset (i.e., position in the string) with
respect to the first character.
Types of indexing:
Index: The first character has index 0, the second has index 1 (because it is one away from
the first character), the third character has index 2, and so on.
Negative index: Use negative indexes to start the slice from the end of the string.
String N A R A Y A N A
Index 0 1 2 3 4 5 6 7
Negative Index -8 -7 -6 -5 -4 -3 -2 -1
2. Prof. K. Adisesha 2
String operators. Commonly used string operators are shown:
Operator Usage Explanation
in x in s True if string x is a substring of string s, and false otherwise
not in x not in s False if string x is a substring of string s, and true otherwise
+ s + t Concatenation of string s and string t
* s * n, n * s Concatenation of n copies of s
[ ] s[i] Character of string s at index i
[ : ] s[2:5] select characters in a specified index range
Slicing
Specify the start index and the end index, separated by a colon, to return a part of the string.
You can return a range of characters by using the slice syntax.
Example1: Get the characters from position 2 to position 7 (not included):
>>>Stringb = “narayana college "
>>>print(Stringb[2:7])
String Methods: Python has a set of built-in methods that you can use on strings.
Method Description
Len() Finds the Length of string
capitalize() Converts the first character to upper case
title() Change all first letters to uppercase
swapcase( ) Swaps cases, lower case becomes upper case and vice versa
upper( ) Converts a string into upper case
lower( ) Converts a string into lower case
lstrip( )
rstrip ( )
strip( )
Remove leading whitespace, trailing
whitespace, or both leading and trailing
whitespace respectively
center( w , c ) Pad string each side to total column width w with character c (default is space)
count( sub ) Return the number of occurrences of sub
find( sub ) Return the index number of the first occurrence of sub or return -1 if not found
replace( old ,
new )
Replace all occurrences of old with new
3. Prof. K. Adisesha 3
isalpha( )
isnumeric( )
isalnum( )
Return True if all characters are letters Returns True if all numbers only, or are
letters otherwise return False
islower( )
isupper( )
istitle( )
Return True if string characters are lowercase, uppercase, or all first letters are
uppercase only – otherwise return False
isspace( ) Return True if string contains only whitespace – otherwise return False
isdigit( )
isdecimal( )
Return True if string contains only digits or
decimals – otherwise return False
Most commonly used built-in methods on strings are.
capitalize() Method: Converts the first character to upper case
String=” narayana college”
print( ‘nCapitalized:t’ , string.capitalize() )
Output: Narayana college
title() Method: Change all first letters to uppercase
String=” narayana college”
print( ‘nTitled:tt’ , string.title() )
Output: Narayana College
swapcase( ) Method: Swaps cases, lower case becomes upper case and vice versa
print( ‘nCentered:t’ , string.center( 30 , ‘*’ ) )
Output: Narayana College
upper() method: The upper() method returns the string in upper case:
Example:
String= “narayana college”
print(String.upper())
Output: NARAYANA COLLEGE
lower() method: The lower() method returns the string in lower case:
Example:
String = " NARAYANA COLLEGE"
print(String.lower())
Output: narayana college
strip() method: The strip() method removes any whitespace from the beginning or the end.
Python strings have the strip(), lstrip(), rstrip() methods for removing any character from both
ends of a string.
If the characters to be removed are not specified then white space will be removed
o strip() #removes from both ends
o lstrip() #removes leading characters (Left-strip)
o rstrip() #removes trailing characters (Right-strip)
4. Prof. K. Adisesha 4
>>> A = " XYZ "
>>> print A >>> print A.strip() >>> print A.lstrip() >>> print A.rstrip()
XYZ XYZ XYZ XYZ
replace() method: The replace() method replaces a string with another string:
Example:
a = "Hello, World!"
print(a.replace("H", "J"))
Output: Jello, world!
split() method: The split() method splits the string into substrings if it finds instances of the
separator.
Example:
a = " NARAYANA COLLEGE"
print(a.split(","))
Output: [' NARAYANA', ' COLLEGE ']
Count() Method: Return the number of occurrences of substring in the given string.
Example:
a = "Hello"
print(a.count())
Output: 5
Find() method: returns the index of first occurrence of the sub string if found otherwise returns
-1 if not found
format() method is used to combine strings and numbers. The format() method takes the
passed arguments, formats them, and places them in the string where the placeholders {} are:
Example 1:
age = 16
txt = "My name is Sunny, and I am {}"
print(txt.format(age))
Output: My name is Sunny, and I am 16"
What is Escape Sequence?
An escape sequence is used to format the text. It starts with a backslash and is interpreted
differently. If we use single quote to represent a string, all the single quotes inside the string must
be escaped. Similar is the case with double quotes. Here is how it can be done to represent the
above text.
Example:
# escaping double quotes
print("He said, "What's there?"")
5. Prof. K. Adisesha 5
Output: He said, "What's there?"
Here is a list of all the escape sequence supported by Python.
Escape
Sequence Description
newline Backslash and newline ignored
Backslash
' Single quote
" Double quote
a ASCII Bell
b ASCII Backspace
f ASCII Formfeed
n ASCII Linefeed
r ASCII Carriage Return
t ASCII Horizontal Tab
v ASCII Vertical Tab
ooo Character with octal value ooo
xHH Character with hexadecimal value HH
6. Prof. K. Adisesha 6
Very Short Questions [1 Mark]
What is a String?
Ans: A String is a sequence of characters, which is enclosed between either single (' ') or double
quotes (" "), python treats both single and double quotes same.
Example: (‘COMPUTER ‘) or double quotes (“COMPUTER “).
my_string = 'Hello'
print(my_string)
my_string = 'Hello'
print(my_string)
Output: Hello Output: Hello
What is the function used to read a Strings?
Ans: Function input() is used to read a string.
Syntax: input(str)
What is Multiline Strings?
Ans: Multiline string to a variable by using three quotes (‘’’ ‘’’):
my_string = ‘’’Hello, welcome to
the world of Python’’’
print(my_string)
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
Output: Hello, welcome to
the world of Python
Output: Hello, welcome to
the world of Python
How to access characters in a string?
Ans: We can access individual characters using indexing and a range of characters using slicing.
Index starts from 0. The index must be an integer.
Name the method, which counts the number of characters in a string.
Ans: len() method is used to count the number of characters in string.
Syntax print(len(str))
Define the term whitespace.
Ans: The term whitespace refers to invisible characters like new line(ln), tab(lt), space or other
control characters.
What is the to delete the spaces in a string?
Ans: Strip() command is used to delete the spaces in a string:
o strip() #removes from both ends
o lstrip() #removes leading characters (Left-strip)
o rstrip() #removes trailing characters (Right-strip)
How to create an empty string?
Ans: An empty string can be created by using either single quote (‘ ‘) or single quote (“ “).
7. Prof. K. Adisesha 7
Explain capitalize( ) method in Python.
Ans: The method capitalize( ) returns a copy of the string with only its first character capitalized.
Write the syntax for capitalize( ) method.
Ans: Following is the syntax for capitalize( ) method : str.capitalize( )
What value will be returned by center (width, fillchar) method in Python
Ans: width — This is the total width of the string, fillchar — This is the filler character
4: Describe the count(str, beg=0,end= len(string))
Answer: The method count( ) returns the number of occurrences of substring sub in the range
[start, end].
5: What do you mean by endswith(suffix, beg=0, end=len(string))
Ans: The method endswith( ) returns True if the string ends with the specified suffix, otherwise
return False
Write the syntax for find( ) method
Ans: Following is the syntax for find( ) method : str.find(str, beg=0 end=len(string))
Write the syntax for isalnum( ) method.
Ans: Following is the syntax for isalnum( ) method : str.isalnum( )
Write the syntax for isalpha( ) method.
Ans: Following is the syntax for isalpha( ) method : str.isalpha( )
Why we use islower( ) method in python?
Ans: The method islower( ) checks whether all the case-based characters (letters) of the string are
lowercase
Describe the isspace( ) method
Ans: The method isspace( ) checks whether the string consists of whitespace.
Give the output of the following statements:
>>>str = ‘Narayana College” >>>str.replace (‘a’.’*’)
Ans: N*r*y*n* College
8. Prof. K. Adisesha 8
Short Answer type questions [2/ 3 Marks]
What is Strings Arrays?
Ans: Strings in Python are arrays of bytes representing unicode characters. However, Python does
not have a character data type, a single character is simply a string with a length of 1. Square
brackets can be used to access elements of the string.
Example: Get the character at position 1 (remember that the first character has the position 0):
>>>a = "NARAYANA COLLEGE"
>>>print(a[1])
Output: A
What is string Slicing?
Ans: String Slicing returns a range of characters by using the slice syntax by specifying the start
index and the end index, separated by a colon, to return a part of the string.
Example1: Get the characters from position 2 to position 7 (not included):
>>>b = “NARAYANA COLLEGE "
>>>print(b[2:7])
Output: RAYAN
Omitting the second index, directs the python interpreter to extract the substring till the end of the
string
Example2:
>>>print A[3:]
Output: RAYANA COLLEGE
Omitting the first three index, extracts the substring before the second index starting from the
beginning.
Example3:
>>>print A[:3]
Output: NAR
What is Negative Indexing?
Ans: Python allows negative indexing for its sequences. Use negative indexes to start the slice
from the end of the string. The index of -1 refers to the last item, -2 to the second last item and so
on. We can access a range of items in a string by using the slicing operator (colon).
String N A R A Y A N A
Negative Index -8 -7 -6 -5 -4 -3 -2 -1
9. Prof. K. Adisesha 9
Example: Get the characters from position 5 to position 2, starting the count from the end of the
string:
>>>b = "NARAYANA"
>>>print(b[-5:-2])
Output: AYA
Important points about accessing elements in the strings using subscripts
Positive subscript helps in accessing the string from the beginning
Negative subscript helps in accessing the string from the end.
Subscript 0 or –ve n(where n is length of the string) displays the first element.
How to change or delete a string?
Ans: Strings are immutable. This means that elements of a string cannot be changed once it has
been assigned. We can simply reassign different strings to the same name.
We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the keyword “del”
Example: # del Command
>>> b = "NARAYANA COLLEGE"
>>> del b
List the various String Operators used in Python?
Concatenation operator “+”
Repetitive Operator “*”
Membership Operator “in” and “not in” Operator
How to concatenate of two or More Strings?
Ans: Joining of two or more strings into a single one is called concatenation. The + operator does
this in Python. Simply writing two string literals together also concatenates them.
Example:
>>>str1 = 'NARAYANA '
>>>str2 ='COLLEGE'
>>>print('str1 + str2 = ', str1 + str2)
Output: str1 + str2 =NARAYANA COLLEGE
How to print same string of two or more times?
Ans: By using * (Repetition ): The * operator can be used to repeat the string for a given number
of times.
Example:
str1 = 'Hello… '
>>>print(3*str)
Output: Hello… Hello… Hello…
10. Prof. K. Adisesha 10
How to perform Sub-String Test?
Ans: To check if a certain phrase or character is present in a string, keywords in or not in are used.
Example 1:
string = "Narayana College"
x = "ray" in String
print(x)
Output: True
Example 2:
string = "Narayana College"
x = "ate" in String
Output: False
Differentiate between upper() and isupper() Method.
upper() method: The upper() method returns the string in upper case:
Example:
String= “narayana college”
print(String.upper())
Output: NARAYANA COLLEGE
The isupper() method return True if string characters are uppercase, or all first letters are
uppercase only – otherwise return False
String= “narayana college”
print(String.upper())
Output: False
What will be the output of the following program code?
String= “NARAYANA COLLEGE”
X=len(String)
print(String)
print(String[1:5])
Output: 16
NARAYANA COLLEGE
RAY
How you can “update” an existing string?
Ans: You can “update” an existing string by (re) assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether. Following
is a simple example:
var1 = ‘Hello World!’
print Updated String:-“,var i[:6] + ‘Python’
11. Prof. K. Adisesha 11
Explain Unicode String with example.
Ans: Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are
stored as 16- bit Unicode. This allows for a more varied set of characters, including special
characters from most languages in the world.
example : >>>print u ‘Hello World!’
Describe isdecimal( ) with example.
Ans: The method isdecimal( ) checks whether the string consists of only decimal characters. The
isdecimal() returns:
True if all characters in the string are decimal characters.
False if at least one character is not decimal character.
Example:
s = "28212"
print(s.isdecimal())
Output: True
Give an example of swapcase( ) in Python
Ans: The swapcase() method returns a string where all the upper case letters are lower case and vice
versa.
The following example shows the usage of swapcase( ) method.
>>>str = “Narayana PU College!”;
>>>print str.swapcase( );
This will produce the following result: Narayana pu cOLLEGE!
12. Prof. K. Adisesha 12
Long Answer type questions [4/6 Marks]
1: Write a program to calculate the length of a String without using a library function.
String=”Welcome to Python”
Count=0
For i in string:
If (i != ‘n’):
Count=count + 1
Print(“length of string is”, count)
Or
String=input(“enter the string”
count=0
For i in string:
count=count + 1
print(“length of string is”, count)
2: Write a program to calculate the number of words and characters present in a String
String=”Welcome to Narayana College”
Count=0
Word=1
For i in string:
If (i == ‘ ’):
Word=Word+1
Count=Count + 1
Print(“The Number of Characters are”, Count, “and words are:”, Word)
3. Write a program to count no of ‘p’ in the string pineapple.
word = 'pineapple'
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print(count)
4. Write a program to reverse a string
String=input(“enter the string”)
Print(Original string is:”, String)
Str1=string[::-1]
Print(“Reversed string is :”, str1)
13. Prof. K. Adisesha 13
5. Write a script to determine if the given substring is present in the string.
string=input("Enter the String")
sub=input(“Enter the Sub-String”)
if String.find(sub):
print ("matched substring: ”,sub, “found at position", String.find(sub)
else:
print "No match found"
6. Program to check whether the string is a palindrome or not.
str=input("Enter the String")
l=len(str)
p=l-1
index=0
while (index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
print "String is not a palidrome"
break
else:
print "String is a Palidrome"
7. Write a program to determine if the given word is present in the string.
Answer: Using search() member function
The search() member function fastest method to check for a substring
def wsearch ( ) :
imprt re word = ‘good’
search1 = re.search (word, ‘I am a good person’)
if search1 :
position = search1.start ( )
print “matched”, word, “at position”, position
else : print “No match found”
8: Write a program to print the pyramid?
Answer:
num = eval (raw_input (“Enter an integer from 1 to 5:”))
if num < 6 :
for i in range (1, num + 1):
for j in range (num-i, 0,-1):
print (” “)
for j in range (i, 0, -1):
print (j)
14. Prof. K. Adisesha 14
Output :
1
212
32123
4321234
543212345
9. Write a program that reads a string and then prints a string that capitalizes every other
letter in the string.
Answer:
string = raw_input (“Enter a string:”)
length = len (string) string2 = ” ” for a in range (0, length, 2):
string 2 + – string [a] if a < (length-1):
string 2+ = string [a+1],upper()
print “Original string is”, string print “Converted string is”, string2
10: Write a script to determine if the given substring is present in the string.
def search_string():
import re
substring='water'
search1=re.search(substring,'Water water everywhere but not a drop to drink')
if search1:
position=search1.start()
print "matched", substring, "at position", position
else:
print "No match found"
15. Prof. K. Adisesha 15
EXERCISE
1. Input a string “Green Revolution”. Write a script to print the string in reverse.
2. Input the string “Success”. Write a script of check if the string is a palindrome or not
3. Input the string “Successor”. Write a script to split the string at every occurrence of the letter s.
4. Input the string “Successor”. Write a script to partition the string at the occurrence of the letter s.
Also Explain the difference between the function split( ) and partition().
5. Write a program to print the pyramid.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6. What will be the output of the following statement? Also justify for answer.
>>> print 'I like Gita's pink colour dress'.
7. Give the output of the following statements
>>> str='Honesty is the best policy'
>>> str.replace('o','*')
8. Give the output of the following statements
>>> str='Hello World'
>>>str.istiltle()
9. Give the output of the following statements.
>>> str="Group Discussion"
>>> print str.lstrip("Gro")
10. Write a program to print alternate characters in a string. Input a string of your own choice.
11. Input a string „Python‟. Write a program to print all the letters except the letter ‟y‟.
16. Prof. K. Adisesha 16
Debugging Program
Debugging:
Debugging is the process of identifying and correcting or removing the Bugs (errors) in a software
code that cause it to behave unexpectedly or crash. Debugging checks, detects and corrects errors
or bugs to allow proper program operation according to set specifications.
Types of errors: There are three types of errors that must contend with when weiting computer
program.
Syntax errors
Runtime errors
Logical errors
Syntax errors represent grammar errors in the use of the programming language.
Common examples are:
Misspelled variable and function names
Missing colons
Improperly matched parentheses, square brackets, and curly braces
Incorrect format in selection and loop statements
Runtime errors occur when a program has no syntax errors and occurs during the execution of a
program.
Common examples are:
Trying to divide by a variable that contains a value of zero
Trying to open a file that doesn't exist
Logic errors occur when there is a design flaw in your program, ie. The logic of the program is
wrong
Common examples are
Multiplying when you should lbe dividing
Adding when you should be subtracting
Opening and using data from the wrong file
Displaying the wrong message
Semantic errors indicate an improper use of Python statements. ex: x*y=z
Exception
An Exception is an event, which occurs during the execution of a program that disrupts the flow of
the program’s instructions. When a Python program encounters a situation that it cannot handle, it
raises an exception. It must either handle the exception immediately else program terminates.
Handling an exception
Exceptions can be handled using a try statement. A critical operation, which can raise exception,
which is placed inside the try clause and the code that handles exception is written in except
clause.
try:
# statements
pass
except ValueError
# handle ValueError exception
17. Prof. K. Adisesha 17
except (TypeError, ZeroDivisionError)
# handle multiple exceptions
# TypeError and ZeroDivisionError
else:
If there is no exception then execute this block
Built in exception
Exception Name Description
Arithmetic Error This class is the base class for those built-in exceptions that are raised for
various arithmetic errors such as:
OverflowError
ZeroDivisionError
FloatingPointError
Overflow Error Raised when result of an arithmetic operation is too large to be represented
ZeroDivisionError Raised when second operand of division or modulus operation is zero
FloatingPointError Raised when a floating-point operation fails.
EOFError Raised when there is no input from either the (raw input) or (input) function
and the end of file is reached.
IOError Raised when an input/ output operation fails, such as the print statement or
the open) function when trying to open a file that does not exist.
NameError Raised when an identifier is not found in the local or global namespace.
IndexError Raised when index of a sequence is out of range
ImportError Raised when the imported module is not found.
ТурeЕror Raised when a function or operation is applied to an object of incorrect type.
ValueError Raised when a function gets argument of correct type but improper value.
KeyError Raised when a key is not found in a dictionary.
Implementation of Exceptions
Zero Division Error
Try:
a=20/0
Print(a)
except ZeroDivisionError:
Print (“Zero Division Error’)
else:
Print(“No error”)
Output: Zero Division Error
18. Prof. K. Adisesha 18
FloatingPointError
Try:
a=3.1234567890
Print(a*a)
except FloatingPointError:
Print (“Floating Point Error”)
else:
Print(“No error”)
Output: Floating Point Error
OverFlowError
import math
Try:
Print(math.expr(1000))
except OverFlowError:
print (“Over flow point Error”)
else:
print(“No error”)
Output: OverflowError
IndexError
try:
a [1, 2, 3]
print (a[3])
except IndexError:
print ("Index out of bound error. ")
else:
print ("Success")
Output: Index out of bound error.
KeyError
try
D1 = {‘a’:1, 'b':2}
print (D1['c'l)
except KeyError:
print ("Key error.")
else:
print ("Success")
Output: Key error
ImportError
try:
a 3.145
19. Prof. K. Adisesha 19
print (sqrt(a))
except ImportError:
print ("Import error.")
else:
print ("Success")
Output: Import error
Python Debugger (pdb)
The module pdp defines an interactive source code debugger for Python programs. It supports
setting breakpoint and single stepping at the source line level, inspection of stack frames, source
code listing, and evaluation of arbitrary Python code in the context of any stack frame.
Basic Python Debugger (pdb) Commands
COMMAND MEANING
P Print variable value
n Next
s Step inside a function
c Continue
<center> Repeat previous command
I Print nearby code
q Quit
h Help
b 50 Set breakpoint on line 50
b List current break points
cl Clear all break points
cl 42 Clear break point # 42
20. Prof. K. Adisesha 20
Very Short Answer type Questions [1 Mark]
What is Debugging?
Ans: Debugging is the process of identifying and correcting or removing the Bugs (errors) or
abnormalities, which is methodically handled by software programmers
via debugging tools. Debugging checks, detects and corrects errors or bugs to allow proper
program operation according to set specifications.
What are Debugging Techniques?
Ans: Debugging a program is a skill it involves following steps.
1. Carefully sport the origin of error.
2. Print Variables intermediate values
3. Code tracking and stepping
What is an error?
Ans: An error is defined as an issue that arises unexpectedly and stops or interrupts normal
execution of computer/programs. It is sometimes called 'a bug'.
Explain are different types of errors?
Ans: On the bases of error occurring in computer or programs, errors are divided into various
categories:
o Syntax errors
o Run-time errors
o Semantic errors
What is a Run-time error?
Ans: Run-time Error: During execution of the program, some errors may occur. Such errors are
called run-time errors.
Example: Divide by zero.
What is a Logical error?
Ans: Logical Error: Logical errors occur when there are mistakes in the logic of the program.
Unlike other errors, logical errors are not displayed while compiling because the compiler does not
understand the logic of the program.
What are the categories of error?
Errors are broadly divided into two categories:
Compilation error
Runtime error
21. Prof. K. Adisesha 21
What is debugging tool?
Ans: It is a tool specially designed in computer software program to test and find bugs (errors) in
other programs. It is also called as debugger or debugging tool.
Is AssignmentError a standard exception in Python?
Ans: No
Is exception an object or a special function or a standard module?
Ans: an object
// An exception is an object that is raised by a function signaling that an unexpected situation has
occurred, that the function itself cannot handle.
What type of exception is raised as a result of an error in opening a particular file?
Ans: IO Error
Short Answer Type Questions [2/ 3 Marks]
1. What is Compile time errors? Mention its types.
Ans: Compile time errors: syntax errors and static semantic errors indicated by the compiler.
1. Syntax Error: Syntax is the set of rules which should followed while creating the
statements of the program. The grammatical mistakes in the statements of the program are
called syntax errors.
2. Semantic Error: An error, which occurs due to improper use of statements in
programming language.
3. Logical errors: errors due to the fact that the specification is not respected.
2. What is Runtime time errors? Mention its types.
Ans: Runtime errors: dynamic semantic errors, and logical errors, that cannot be detected by the
compiler (debugging).
Examples of some illegal operations that may produce runtime errors are:
Dividing a number by zero
Trying to open a file which is not created
Lack of free memory space
3. What are different techniques used for debugging?
Ans: There are various techniques used for debugging:
22. Prof. K. Adisesha 22
Interactive debugging
Print debugging (or tracing)
Remote debugging
Post-mortem debugging
4. What are exceptions?
Ans: Exceptions are unexpected events that occurs during the execution of a program. An
exception might result from a logical error or an unanticipated situation. In Python, exceptions
(also known as errors) are objects that are raised (or thrown) by code that encounters an
unexpected circumstance.
5. Identify the type of error in the codes shown below.
print("Good night)
Ans: Output: Syntax error
How does the try...except block executes?
Ans: When Python encounters a try statement, it attempts to execute the statements inside the
body. If these statements executes without any error, then control passes to the next statement after
the try...except statement. If an error occurs somewhere in the body of try block then, Python looks
for an except clause with a matching error type. If a suitable except is found then, the handler code
is executed.
6. What is the importance of else clause in try...except block?
The try...except statement has an optional else clause, which present, must follow all except
clauses. It is useful for code that must be executed if the try clause does not raise an exception.
Syntax:
try:
a=20/0
print(a)
except ZeroDivisionError:
print (“Zero Division Error’)
else:
print(“No error”)
Ans: Output: Zero Division Error
7. What is the output of the code shown below if the input entered is 6?
S=False
while not s:
try
n=int(input("Enter a number"))
23. Prof. K. Adisesha 23
while n%2= =0
print("Hello")
except ValueError:
print("Invalid")
Ans: Output: Hello (printed infinite number of times)
Long Answer Type Questions [4 Marks]
1. What will be the output of the following code?
x, y=5, 10
Print(‘A’)
try:
print(‘B’)
a=x/y
print(“C”)
except:
print (“D”)
print (“E”)
print (a)
Ans: Output: A
B
C
E
0.5
2. What is an Exception?
Ans: An exception is an unusual error or Situation that occurs during execution of a program.
When that error occurs, Python generate an exception that can be handled, which avoids your
program to crash.
List some Built in Exception Errors in Python Programming?
IOError: If the file cannot be opened.
NameError: Raised when an identifier is not found in the local or global namespace.
IndexError: Raised when an index is not found in a sequence.
TypeError: Raised when an operation or function is attempted that is invalid for the
specified data type.
SystemExit: Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.
ImportError: If python cannot find the module
24. Prof. K. Adisesha 24
ValueError: Raised when a built-in operation or function receives an argument that has
the right type but an inappropriate value
KeyboardInterrupt: Raised when the user hits the interrupt key (normally Control-C or
Delete)
EOFError: Raised when one of the built-in functions (input() or raw_input()) hits an end-
of-file condition (EOF) without reading any data
3.What is exceptions Handling?
Ans: Python has many built-in exceptions, which forces your program to output an error when
something in it goes wrong. Exception handling in python involves the use of try, except and
finally clause in the following format
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Syntax:
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
4. Explain Python Debugger: pdb
Ans: The module pdb defines an interactive source code debugger for Python programs. It
supports setting (conditional) breakpoints and single stepping at the source line level, inspection of
stack frames, source code listing, and evaluation of arbitrary Python code in the context of any
stack frame.
Basic pdb Commands used in python are:
l(ist) list 11 lines surrounding the current line
w(here) display the file and line number of the current line
n(ext) execute the current line
s(tep) step into functions called at the current line
r(eturn) execute until the current function’s return is encountered
b list breakpoints and their indices
c(ontinue) execute until a breakpoint is encountered
clear[#] clear breakpoint of index [#]
p <name> print value of the variable <name>
!<expr> execute the expression <expr>
26. Prof. K. Adisesha 26
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List is a collection, which is ordered and changeable. Allows duplicate members.
Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
Set is a collection, which is unordered and unindexed. No duplicate members.
Dictionary is a collection, which is unordered, changeable and indexed. No duplicate
members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.
List: A list is a collection, which is ordered and changeable. In Python, lists are written with
square brackets.
Example
Create a List:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(StuList)
Output: ['Prajwal', 'Sunny', 'Rekha']
Access Items: You access the list items by referring to the index number:
Example
Print the second item of the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(StuList[1])
Output: Sunny
Negative Indexing: Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
Print the last item of the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(StuList[-1])
Output: Rekha
Range of Indexes: You can specify a range of indexes by specifying start and end position of the
range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
StuList = ["Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu"]
print(StuList[2:5])
Output: ["Rekha", "Sam", "Adi"]
Note: The search will start at index 2 (included) and end at index 5 (not included).
27. Prof. K. Adisesha 27
Range of Negative Indexes: Specify negative indexes if you want to start the search from the end
of the list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
StuList = ["Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu"]
print(StuList[-4:-1])
Output: ["Sam", "Adi", "Ram"]
Change Item Value: To change the value of a specific item, refer to the index number:
Example
Change the second item:
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList[1] = "Adi"
print(StuList)
Output: ["Prajwal", "Adi", "Rekha"]
Loop through a List: You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
StuList = ["Prajwal", "Sunny", "Rekha"]
for x in StuList:
print(x)
Output: Prajwal
Sunny
Rekha
Check if Item Exists: To determine if a specified item is present in a list use the in keyword:
Example
Check if “Sunny” is present in the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
if "Prajwal" in StuList:
print("Yes, 'Sunny' is in the Student list")
Output: Yes, 'Sunny' is in the Student list
List Length
len() method: To determine how many items a list has use the:
Example
Print the number of items in the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(len(StuList))
Output: 3
Add Items: To add an item to the end of the list, use the append), insert(), method:
Using the append() method to append an item:
Example
28. Prof. K. Adisesha 28
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.append("Sam")
print(StuList)
Output: ['Prajwal', 'Sunny', 'Rekha', 'Sam']
To add an item at the specified index, use the insert() method:
Example
Insert an item as the second position:
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.insert(1, "Sam")
print(StuList)
Output: ['Prajwal', 'Sam', 'Sunny', 'Rekha']
Remove Item: There are several methods to remove items from a list using: remove(), pop(), del,
clear()
The remove() method removes the specified item:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.remove("Sunny")
print(StuList)
Output: ['Prajwal', 'Rekha']
The pop() method removes the specified index, (or the last item if index is not specified):
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.pop()
print(StuList)
Output: ['Prajwal', 'Sunny']
The del keyword removes the specified index:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
del StuList[0]
print(StuList)
Output: ['Sunny', 'Rekha']
The del keyword can also delete the list completely:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
del StuList
The clear() method empties the list:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.clear()
print(StuList)
29. Prof. K. Adisesha 29
Copy a List: You cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one-way is to use the built-in copy(), list() method.
copy() method: Make a copy of a list:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
mylist = StuList.copy()
print(mylist)
Output: ['Prajwal', 'Sunny', 'Rekha']
list() method: Make a copy of a list:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
mylist = list(StuList)
print(mylist)
Output: ['Prajwal', 'Sunny', 'Rekha']
Join Two Lists: There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output: ['a', 'b', 'c', 1, 2, 3]
Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b”, "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output: ['a', 'b', 'c', 1, 2, 3]
Use the extend() method, which purpose is to add elements from one list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b”, "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output: ['a', 'b', 'c', 1, 2, 3]
30. Prof. K. Adisesha 30
The list() Constructor: It is also possible to use the list() constructor to make a new list.
Example
Using the list() constructor to make a List:
StuList = list(("Prajwal", "Sunny", "Rekha")) # note the double round-brackets
print(StuList)
Output: ['Prajwal', 'Sunny', 'Rekha']
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
31. Prof. K. Adisesha 31
Python Tuples
A tuple is a collection, which is ordered and unchangeable. In Python, tuples are written with
round brackets.
Example
Create a Tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple)
Output: ('Prajwal', 'Sunny', 'Rekha')
Access Tuple Items: Tuple items access by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple[1])
Output: Sunny
Negative Indexing: Negative indexing means beginning from the end, -1 refers to the last item,
and -2 refers to the second last item etc.
Example
Print the last item of the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple[-1])
Output: Rekha
Range of Indexes: You can specify a range of indexes by specifying start and end of the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
Stu_tuple = ("Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu")
print(Stu_tuple[2:5])
Output: (“Rekha", "Sam", "Adi”)
Note: The search will start at index 2 (included) and end at index 5 (not included).
Range of Negative Indexes: Specify negative indexes if you want to start the search from the end
of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
Stu_tuple = ("Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu")
print(Stu_tuple[-4:-1])
Output: ("Sam", "Adi", "Ram")
32. Prof. K. Adisesha 32
Change Tuple Values: Once a tuple is created, you cannot change its values. Tuples are
unchangeable or immutable as it also is called. However, by converting the tuple into a list,
change the list, and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = (“Prajwal”, “Sunny”, “Rekha”)
y = list(x)
y[1] = "Adi"
x = tuple(y)
print(x)
Output: (“Prajwal”, “Adi”, “Rekha”)
Loop through a Tuple: You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
for x in Stu_tuple:
print(x,”t”)
Output: Prajwal Sunny Rekha
Check if Item Exists: To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "Prajwal" is present in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
if "Prajwal" in Stu_tuple:
print("Yes, 'Prajwal' is in the Student tuple")
Output: Yes, 'Prajwal' is in the Student tuple
Tuple Length: To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(len(Stu_tuple))
Output: 3
Adding Items: Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
Stu_tuple[3] = "Adi" # This will raise an error
print(Stu_tuple) Output: TypeError: 'tuple' object does not support item assignment
Create Tuple With One Item: To create a tuple with only one item, you have add a comma
after the item, unless Python will not recognize the variable as a tuple.
Example
One item tuple, remember the comma:
33. Prof. K. Adisesha 33
Stu_tuple = ("Prajwal",)
print(type(Stu_tuple))
Stu_tuple = ("Prajwal") #NOT a tuple
print(type(Stu_tuple))
Output: <class 'tuple'>
<class 'str'>
Remove Items: Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:
Example
The del keyword can delete the tuple completely:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
del Stu_tuple
print(Stu_tuple) #this will raise an error because the tuple no longer exists
Join Two Tuples: To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output: ('a', 'b', 'c', 1, 2, 3)
The tuple() Constructor: It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
Stu_tuple = tuple((“Prajwal”, “Sunny”, “Rekha”)) # note the double round-brackets
print(Stu_tuple)
Output: ('Prajwal', 'Sunny', 'Rekha')
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it
was found
34. Prof. K. Adisesha 34
Dictionaries
Introduction
Dictionaries are mutable unordered collections of data values in the form of key: value pairs.
Dictionaries are also called associative arrays or mappings or hashes
The keys of the dictionary must be of immutable type like strings and numbers. Tuples can also
be used as keys if they contain only immutable objects. Giving a mutable key like a list will
give you a TypeError:unhashable type" error
Values in the dictionaries can be of any type.
The curly brackets mark the beginning and end of the dictionary.
Each entry (Key: Value) consists of a pair separated by a colon (:) between them.
The key-value pairs are separated by commas (,)
Dictionary-name = {<key1> :< value1>, <key2> :< value2>...}
e.g Day 0f The Week "Sunday":1, "Monday" 2, "Tuesday":3, "Wednesday":4,
"Thursday":5, "Friday":6,"Saturday":7)
As the elements (key, value pairs) in a dictionary are unordered, we cannot access elements as
per any specific order. Dictionaries are not a sequence like string, list and tuple.
The key value pairs are held in a dictionary as references.
Keys in a dictionary have to be unique.
Definitions:
Dictionary is listed in curly brackets { }, inside these curly brackets, keys and values are declared.
Each key is separated from its value by a colon (:) while commas separate each element.
To create a dictionary, you need to include the key: value pairs in a curly braces as per following
syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
Example:
dictr = {'Name': Sunny', 'Age': 18, 'Place': 'Bangalore'}
Properties of Dictionary Keys?
There are two important points while using dictionary keys
More than one entry per key is not allowed ( no duplicate key is allowed)
The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
Dictionary keys are case sensitive- Same key name but with the different case are treated as
different keys in Python dictionaries.
35. Prof. K. Adisesha 35
Creation, initializing and accessing the elements in a Dictionary
The function dict ( ) is used to create a new dictionary with no items. This function is
called built-in function. We can also create dictionary using {}.
Example:
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
{'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be done by
using ‘for-loop’.
Example
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print i,":", H[i]," ",
Output
>>> Four: scanner one: keyboard three: printer two: Mouse
Creating, initializing values during run time (Dynamic allocation)
We can create a dictionary during run time also by using dict () function. This way of creation is
called dynamic allocation. Because, during the run time, memory keys and values are added to the
dictionary.
Example
Appending values to the dictionary
We can add new elements to the existing dictionary, extend it with single pair of values or join two
dictionaries into one. If we want to add only one element to the dictionary, then we should use the
following method.
Syntax:
Dictionary name [key]=value
36. Prof. K. Adisesha 36
List few Dictionary Methods?
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does
not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value
pairs
values() Returns a list of all the values in the dictionary
clear ( ) Method: It removes all items from the particular dictionary.
Syntax:
d.clear( ) #d dictionary
Example
Day={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
print Day
Day.clear( )
print Day
Output: {'wed': 'Wednesday', 'mon': 'Monday', 'tue': 'Tuesday'}
{}
cmp ( ) Method: This is used to check whether the given dictionaries are same or not. If both are
same, it will return ‘zero’, otherwise return 1 or -1. If the first dictionary having more number of
items, then it will return 1, otherwise return -1.
Syntax:
37. Prof. K. Adisesha 37
cmp(d1,d2) #d1and d2 are dictionary.
returns 0 or 1 or -1
Example
Day1={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Day2={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Day3={'1':'Sun','2':'Mon','3':'Tues','4':'Wed'}
cmp(D1,D3) #both are not equal
Output: 1
cmp(D1,D2) #both are equal
Output: 0
cmp(D3,D1)
Output: -1
del() Method: This is used to Removing an item from dictionary. We can remove item from the
existing dictionary by using del key word.
Syntax:
del dicname[key]
Example
Day1={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
del Day1["3"]
print Day
Output: {'1':'Sun','2':'Mon',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
len( ) Method: This method returns number of key-value pairs in the given dictionary.
Syntax:
len(d) #d dictionary returns number of items in the list.
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
len(Day)
Output: 4
Merging dictionaries: An update ( )
Two dictionaries can be merged in to one by using update ( ) method. It merges the
keys and values of one dictionary into another and overwrites values of the same key.
Syntax:
Dic_name1.update (dic_name2)
Using this dic_name2 is added with Dic_name1.
Example
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
get(k, x ) Method: There are two arguments (k, x) passed in ‘get( )’ method. The first argument is
key value, while the second argument is corresponding value. If a dictionary has a given key (k),
which is equal to given value (x), it returns the corresponding value (x) of given key (k). If omitted
and the dictionary has no key equal to the given key value, then it returns None.
38. Prof. K. Adisesha 38
Syntax:
D.get (k, x) #D dictionary, k key and x value
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Day.get('4',"wed") # corresponding value 3 'Wed'
Day.get("6","mon") # default value of 6 ‘fri’
Day.get("2") # default value of 2 ‘mon’
Day.get("8") # None
has_key( ) Method: This function returns ‘True’, if dictionary has a key, otherwise it returns
‘False’.
Syntax:
D.has_key(k) #D dictionary and k key
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
D.has_key("2")
True
D.has_key("8")
False
items( ) Method: It returns the content of dictionary as a list of key and value. The key and value
pair will be in the form of a tuple, which is not in any particular order.
Syntax:
D.items() # D dictionary
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
D.items()
['1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat']
keys() Method: It returns a list of the key values in a dictionary, which is not in any particular
order.
Syntax:
D.keys( ) #D dictionary
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
D.keys()
[1', '2', 3', 4', '5', '6, 7']
values() Method: It returns a list of values from key-value pairs in a dictionary, which is not in
any particular order. However, if we call both the items () and values() method without changing
the dictionary's contents between these two (items() and values()), Python guarantees that the order
of the two results will be the same.
Syntax:
D.values() #D values
Example
39. Prof. K. Adisesha 39
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Day.values()
['Wed', 'Sun, 'Thu', 'Tue', 'Mon', 'Fri', 'Sat']
Day.items()
['1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat']
Python Dictionaries
What is Dictionary?
Dictionary is listed in curly brackets { }, inside these curly brackets, keys and values are declared.
Each key is separated from its value by a colon (:) while commas separate each element.
How to creating a Dictionary?
To create a dictionary, you need to include the key: value pairs in a curly braces as per following
syntax:
<dictionary-name>={<key>:<Value>, <key>:<Value>,...}
Example:
dictr = {'Name': Sunny', 'Age': 18, 'Place': 'Bangalore'}
What are the properties of Dictionary Keys?
There are two important points while using dictionary keys
More than one entry per key is not allowed ( no duplicate key is allowed)
The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
Dictionary keys are case sensitive- Same key name but with the different case are treated as
different keys in Python dictionaries.
How to access elements from a dictionary?
While indexing is used with other container types to access values, dictionary uses keys. Key can
be used either inside square brackets or with the get() method.
Example:
>>>dict = {'Name':Sunny', 'Age': 18,'Place':'Bangalore'}
>>>print(my_dict['name'])
# Output: Sunny
There is also a method called get() that will give you the same result:
>>>print(dict.get('age'))
# Output: 18
40. Prof. K. Adisesha 40
How to change or add elements in a dictionary?
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
dict = {'Name':Sunny', 'Age': 18,'Place':'Bangalore'}
update value to Dictionary
dict['age'] = 27
print(dict)
#Output: {'age': 27, 'name': 'Sunny'}
add item to Dictionary
dict['address'] = 'Downtown'
print(dict)
Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
How to delete or remove elements from a dictionary?
We can remove a particular item in a dictionary by using the method pop(). This method removes
as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionary
dirc = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item
>>>print(dirc.pop(4))
# Output: 16
>>>print(dirc)
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
# remove an arbitrary item
>>>print(dirc.popitem())
# Output: (1, 1)
# delete a particular item
>>>del dirc[5]
>>>print(squares)
Output: {2: 4, 3: 9}
# remove all items
dirc.clear()
41. Prof. K. Adisesha 41
>>>print(dirc)
# Output: {}
# delete the dictionary itself
>>>del squares
>>> print(dirc)
Output: Throws Error
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is
for keys only, not for values.
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Case1:
print(1 in squares)
# Output: True
Case2:
print(2 not in squares)
# Output: True
Loop Through a Dictionary
Loop through a dictionary is done through using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
42. Prof. K. Adisesha 42
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2. There are
ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in method dict().
Example
Make a copy of a dictionary with the dict() method:
Ruthisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)Run example »
n example »
Write a python program to input ‘n’ names and phone numbers to store it in a dictionary and to
input any name and to print the phone number of that particular name.
Code
phonebook=dict()
n=input("Enter total number of friends: ")
i=1
while i<=n:
a=raw_input("enter name: ")
b=raw_input("enter phone number: ")
phonebook[a]=b
i=i+1
name=input("enter name :")
43. Prof. K. Adisesha 43
f=0
l=phonebook.keys()
for i in l:
if (cmp(i,name)==0):
print "Phone number= ",phonebook[i]
f=1
if (f==0):
print "Given name not exist"
Output
Enter total number of friends 2
enter name: Prajwal
enter phone number: 23456745
enter name: Sunny
enter phone number: 45678956
2. Write a program to input ‘n’ employee number and name and to display all employee’s
information in ascending order based upon their number.
Code
empinfo=dict()
n=input("Enter total number of employees")
i=1
while i<=n:
a=raw_input("enter number")
b=raw_input("enter name")
empinfo[a]=b
i=i+1
l=empinfo.keys()
l.sort()
print "Employee Information"
print "Employee Number",'t',"Employee Name"
for i in l:
print i,'t',empinfo[i]
3. Write the output for the following Python codes.
A={1:100,2:200,3:300,4:400,5:500}
print A.items()
print A.keys()
print A.values()
Output
[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)]
[1, 2, 3, 4, 5]
[100, 200, 300, 400, 500]
4. Write a program to create a phone book and delete particular phone number using name.
Code
phonebook=dict()
44. Prof. K. Adisesha 44
n=input("Enter total number of friends")
i=1
while i<=n:
a=raw_input("enter name")
b=raw_input("enter phone number")
phonebook[a]=b
i=i+1
name=raw_input("enter name")
del phonebook[name]
l=phonebook.keys()
print "Phonebook Information"
print "Name",'t',"Phone number"
for i in l:
print i,'t',phonebook[i]
Write a program to input total number of sections and class teachers’ name in 11th class
and display all information on the output screen.
Code
classxi=dict()
n=input("Enter total number of section in xi class")
i=1
while i<=n:
a=raw_input("enter section")
b=raw_input ("enter class teacher name")
classxi[a]=b
i=i+1
print "Class","t","Section","t","teacher name"
for i in classxi:
print "XI","t",i,"t",classxi[i]