0% found this document useful (0 votes)
21 views18 pages

Python Dictionaries: Mapping Type Guide

Dictionaries in Python are mutable mapping types that associate keys with values, allowing for unordered collections of data. They can be created, accessed, updated, and deleted using specific syntax and methods, and support various built-in functions and operators for manipulation. Key operations include adding or modifying entries, checking for key membership, and using methods like clear(), get(), and update() to manage dictionary contents.

Uploaded by

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

Python Dictionaries: Mapping Type Guide

Dictionaries in Python are mutable mapping types that associate keys with values, allowing for unordered collections of data. They can be created, accessed, updated, and deleted using specific syntax and methods, and support various built-in functions and operators for manipulation. Key operations include adding or modifying entries, checking for key membership, and using methods like clear(), get(), and update() to manage dictionary contents.

Uploaded by

sudhashri1203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT III

MAPPING TYPE: DICTIONARIES


1. EXPLAIN ABOUT DICTIONARIES. (PART-B)
Dictionaries are the sole mapping type in Python. Mapping objects have a one-to-many correspondence
between hashable values (keys) and the objects they represent (values). They are similar to Perl
hashes and can be generally considered as mutable hash tables.
A dictionary object itself is mutable and is yet another container type that can store any number of
Python objects, including other container types.
Sequence types use numeric keys only (numbered sequentially as indexed). Mapping types may use
most other object types as keys; strings are the most common.
Unlike sequence type keys, mapping keys are often, if not directly, associated with the data value that is
stored.
But because we are no longer using "sequentially ordered" keys with mapping types, we are left with an
unordered collection of data.
The reason why they are commonly referred to as hash tables is because that is the exact type of object
that dictionaries are. Dictionaries are one of Python's most powerful data types.
Python dictionaries are implemented as resizeable hash tables.
The syntax of a dictionary entry is key:value Also, dictionary entries are enclosed in braces ( { } ).
How to Create and Assign Dictionaries
Creating dictionaries simply involves assigning a dictionary to a variable, regardless of whether the
dictionary has elements or not:
>>> D1 = {}
>>> D2 = {1: 'Au', 2: 'Ag', 3:'Cu'}
>>> D3 = {'Au':'Gold', 'Ag':'Silver', 'Cu':'Copper'}
>>> D4 = {'name': 'nasra', 1: [2, 4, 3]}
>>> print('Empty dictionary:', D1)
Empty dictionary: {}
>>> print('Dictionary with int keys:',D2)
Dictionary with int keys: {1: 'Au', 2: 'Ag', 3: 'Cu'}
>>> print('Dictionary with str keys:\n',D3)
Dictionary with str keys:
{'Au': 'Gold', 'Ag': 'Silver', 'Cu': 'Copper'}
How to Access Values in Dictionaries
To traverse a dictionary (normally by key), you only need to cycle through its keys, like this:
>>> dict2 = {'name': 'earth', 'port': 80}
>>>> for key in [Link]():
... print('key=%s, value=%s' % (key, dict2[key]))
...
key=name, value=earth
key=port, value=80
Iterators were created to simplify accessing of sequence-like objects such as dictionaries and files.
Using just the dictionary name itself will cause an iterator over that dictionary to be used in a for loop:
>>>> for key in dict2:
... print('key=%s, value=%s' % (key, dict2[key]))
...
key=name, value=earth
key=port, value=80
To access individual dictionary elements, use the familiar square brackets along with the key to obtain
its value:
>>> dict2['name']
'earth'
>>> print ('host %s is running on port %d' % (dict2['name'], dict2['port']))
host earth is running on port 80
34

Downloaded by priya loganathan (priyacs104@[Link])


The keys in dict2 are 'name' and 'port', and their associated value items are 'earth' and 80, respectively.
Access to the value is through the key, as you can see from the explicit access to the 'name' key. If we
attempt to access a data item with a key that is not part of the dictionary, we get an error:
>>> dict2['server']
Traceback (innermost last):
File "<stdin>", line 1, in ?
KeyError: server
In this example, we tried to access a value with the key 'server' which, as you know from the code above,
does not exist. The best way to check if a dictionary has a specific key is to use the dictionary's
has_key() method, or better yet, the in or not in operators starting with version 2.2.
The has_key() method will be obsoleted in future versions of Python, so it is best to just use in or not in.
The Boolean has_key() and the in and not in operators are Boolean, returning true if a dictionary has
that key and False otherwise.
>>> 'server' in dict2 # or dict2.has_key('server')
False
>>> 'name' in dict2 # or dict2.has_key('name')
True
>>> dict2['name']
'earth'
Here is another dictionary example mixing the use of numbers and strings as keys:
>>> dict3 = {}
>>> dict3[1] = 'abc'
>>> dict3['1'] = 3.14159
>>> dict3[3.2] = 'xyz'
>>> dict3
{3.2: 'xyz', 1: 'abc', '1': 3.14159}
Rather than adding each key-value pair individually, we could have also entered all the data for dict3 at
the same time:
dict3 = {3.2: 'xyz', 1: 'abc', '1': 3.14159}
Creating the dictionary with a set key-value pair can be accomplished if all the data items are known in
advance. The goal of the examples using dict3 is to illustrate the variety of keys that we can use.
How to Update Dictionaries
We can update a dictionary by adding a new entry or element (i.e., a key-value pair), modifying an
existing entry, or deleting an existing entry.
>>> dict2['name'] = 'venus' # update existing entry
>>> dict2['port'] = 6969 # update existing entry
>>> dict2['arch'] = 'sunos5' # add new entry
>>> print('host %(name)s is running on port %(port)d' % dict2)
host venus is running on port 6969
If the key does exist, then its previous value will be overridden by its new value. The print statement
above illustrates an alternative way of using the string format operator ( % ), specific to dictionaries.
How to Remove Dictionary Elements and Dictionaries
Removing an entire dictionary is not a typical operation. Generally, we either remove individual
dictionary elements or clear the entire contents of a dictionary.
However, if we really want to "remove" an entire dictionary, use the del statement. Here are some
deletion examples for dictionaries and dictionary elements:
del dict2['name'] # remove entry with key 'name'
[Link]() # remove all entries in dict1
del dict2 # delete entire dictionary
[Link]('name') # remove & return entry w/key
MAPPING TYPE OPERATORS
2. DISCUSS ABOUT MAPPING TYPE OPERATORS. (PART-B)
Dictionaries will work with all of the standard type operators but do not support operations such as
concatenation and repetition. Those operations, although they make sense for sequence types, do not
translate to mapping types.
35

Downloaded by priya loganathan (priyacs104@[Link])


Standard Type Operators (Not supported in Python 3)
Here are some basic examples using some of those operators:
>>> dict4 = {'abc': 123}
>>> dict5 = {'abc': 456}
>>> dict4 < dict5
True
Mapping Type Operators
Dictionary Key-Lookup Operator ([ ])
The only operator specific to dictionaries is the key-lookup operator, which works very similarly to the
single element slice operator for sequence types.
For sequence types, an index offset is the sole argument or subscript to access a single element of a
sequence.
For a dictionary, lookups are by key, so that is the argument rather than an index. The key-lookup
operator is used for both assigning values to and retrieving values from a dictionary:
>>>dict4[k] = v # set value 'v' in dictionary with key 'k'
>>>dict4[k] # lookup value in dictionary with key 'k'
(Key) Membership (in, not in)
We can use the in and not in operators to check key membership instead of the has_key() method:
>>> dict2 = {'name': 'earth', 'port': 80}
>>> 'name' in dict2
True
>>> 'phone' in dict2
False
>>> 'name' not in dict2
False
>>> 'phone' not in dict2
True
MAPPING TYPE BUILT-IN AND FACTORY FUNCTIONS
3. WRITE SHORT NOTE ON MAPPING TYPE BUILT-IN FUNCTIONS. (PART-B/C)
4. EXPLAIN ABOUT FACTORY FUNCTIONS. (PART-B)
Standard Type Functions [type(), str(), and cmp()]
The type() factory function, when applied to a dict, returns, the dict type, "<type 'dict'>". The str()
factory function will produce a printable string representation of a dictionary. These are fairly
straightforward.
Comparisons of dictionaries are based on an algorithm that starts with sizes first, then keys, and finally
values.
*Dictionary Comparison Algorithm (Not supported in Python 3)
In the following example, we create two dictionaries and compare them, then slowly modify the
dictionaries to show how these changes affect their comparisons:
>>> dict1 = {}
>>> dict2 = {'host': 'earth', 'port': 80}
>>> dict1==dict2
False
Mapping Type Built-in and Factory Functions
Size, their keys match, and so do their values, hence the reason that 0 is returned by cmp().
>>> dict1['prot'] = 'tcp'
>>> dict1==dict2
False
The algorithm pursues comparisons in the following order.
❖ In other words, the dictionary with more keys is greater, i.e., len(dict1) > len(dict2).
❖ If both dictionary lengths are the same and the keys match exactly, the values for each key in both
dictionaries are compared.
If we have reached this point, i.e., the dictionaries have the same length, the same keys, and the same
values for each key, then the dictionaries are an exact match and 0 is returned.
36

Downloaded by priya loganathan (priyacs104@[Link])


How dictionaries are compared

Mapping Type Related Functions


Dict ( )
The dict() factory function is used for creating dictionaries. If no argument is provided, then an empty
dictionary is created. The fun happens when a container object is passed in as an argument to dict().
If the argument is an iterable, i.e., a sequence, an iterator, or an object that supports iteration, then each
element of the iterable must come in pairs.
For each pair, the first element will be a new key in the dictionary with the second item as its value.
>>> dict(zip(('x','y'); (1,2)))
{'x': 1, 'y': 2}{'y': 2, 'x' : 1}
Len()
The len() BIF is flexible. It works with sequences, mapping types, and sets For a dictionary, it returns the
total number of items, that is, key-value pairs:
>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict2
{'port': 80, 'name': 'earth'}
>>> len(dict2)
2
When referencing dict2, the items are listed in reverse order from which they were entered into the
dictionary.
Hash()
The hash() BIF is not really meant to be used for dictionaries per se, but it can be used to determine
whether an object is fit to be a dictionary key (or not).
>>> int_val = 4
>>> print("The integer hash value is : " + str(hash(int_val)))
The integer hash value is : 4
MAPPING TYPE BUILT-IN METHODS
5. DISCUSS ABOUT MAPPING TYPE BUILT-IN METHODS. (PART-B)
Method Name Operation
[Link]() Removes all elements of dict
[Link](seq, val=None) Creates and returns a new dictionary with the elements of seq as the keys
and val as the initial value for all keys
37

Downloaded by priya loganathan (priyacs104@[Link])


[Link](key, default=None) For key key, returns value or default if key not in dict.
dict.has_key (key) Returns True if key is in dict, False otherwise; partially deprecated by
the in and not in operators.
[Link]() Returns a list of the (key, value) tuple pairs of dict
[Link]() Returns a list of the keys of dict
[Link] *() iteritems(), iterkeys(), itervalues() are all methods that behave the same
as their non-iterator counterparts but return an iterator instead of a list.
[Link](key [, default]) Similar to get() but removes and returns dict[key] if key present and
raises KeyError if key not in dict and default not given.
[Link](key,default=None) Similar to get(), but sets dict[key]=default if key is not already in dict.
[Link](dict2) Add the key-value pairs of dict2 to dict.
[Link]() Returns a list of the values of dict.
Basic dictionary methods focus on their keys and values. These are keys(), which returns a list of the
dictionary's keys, values(), which returns a list of the dictionary's values, and items(), which returns a list
of (key, value) tuple pairs.
These are useful when you wish to iterate through a dictionary's keys or values, albeit in no particular
order.
>>> [Link]()
dict_keys(['name', 'port'])
>>> [Link]()
dict_values(['earth', 80])
>>> [Link]()
dict_items([('name', 'earth'), ('port', 80)])
>>> for eachKey in [Link]():
... print('dict2 key', eachKey, 'has value', dict2[eachKey])
...
dict2 key name has value earth
dict2 key port has value 80
The keys() method is fairly useful when used in conjunction with a for loop to retrieve a dictionary's
values as it returns a list of a dictionary's keys. However, because its items are unordered, imposing
some type of order is usually desired.
The update() method can be used to add the contents of one directory to another. Any existing entries
with duplicate keys will be overridden by the new incoming entries.
Nonexistent ones will be added. All entries in a dictionary can be removed with the clear() method.
>>> dict3= {'host':'venus', 'server':'http'}
>>> [Link](dict3)
>>> dict2
{'name': 'earth', 'port': 80, 'host': 'venus', 'server': 'http'}
>>> [Link]()
>>> dict3
{}
The copy() method simply returns a copy of a dictionary. Note that this is a shallow copy only.
Finally, the get() method is similar to using the key-lookup operator ([ ]), but allows you to provide a
default value returned if a key does not exist. If a key does not exist and a default value is not given, then
None is returned.
This is a more flexible option than just using key-lookup because you do not have to worry about an
exception being raised if a key does not exist.
>>> dict4 = [Link]()
>>> dict4
{'name': 'earth', 'port': 80, 'host': 'venus', 'server': 'http'}
>>> [Link]('host')
'venus'
>>> [Link]('xxx')
>>> type([Link]('xxx'))

38

Downloaded by priya loganathan (priyacs104@[Link])


<type 'NoneType'>
The built-in method, setdefault(), has the sole purpose of making code shorter by collapsing a common
idiom: you want to check if a dictionary has a key.
That is precisely what setdefault() does:
>>> [Link]('port', 8080)
80
CONDITIONALS AND LOOPS
6. WRITE SHORT NOTE ON LOOPING. (PART-B/C)
Python's conditional and looping statements, and all their related components as if, while, for, and their
friends else, elif, break, continue, and pass.
IF STATEMENT
7. DISCUSS ABOUT IF STATEMENTS. (PART-B)
The if statement is made up of three main components: the keyword itself, an expression that is tested
for its truth value, and a code suite to execute if the expression evaluates to non-zero or true.
The syntax for an if statement is:
if expression:
expr_true_suite
The suite of the if clause, expr_true_suite, will be executed only if the above conditional expression
results in a Boolean true value.
Multiple Conditional Expressions
The Boolean operators and, or, and not can be used to provide multiple conditional expressions or
perform negation of expressions in the same if statement.
if not warn and (system_load >= 10):
print('WARNING: losing resources')
warn += 1
Single Statement Suites
If the suite of a compound statement, i.e., if clause, while or for loop, consists only of a single line, it
may go on the same line as the header statement:
if make_hard_copy: send_data_to_printer()
ELSE STATEMENT
8. EXPLAIN ABOUT ELSE STATEMENTS IN PYTHON. (PART-B)
The else statement identifies a block of code to be executed if the conditional expression of the if
statement resolves to a false Boolean value.
The syntax is what you expect:
if expression:
expr_true_suite
else:
expr_false_suite
Example:
if passwd == [Link]:
ret_str = "password accepted"
id = [Link]
valid = True
else:
ret_str = "invalid password entered... try again!"
valid = False
"Dangling else" Avoidance
Python's design of using indentation rather than braces for code block delimitation not only helps to
enforce code correctness, but it even aids implicitly in avoiding potential problems in code that is
syntactically correct.
One of those such problems is the (in)famous "dangling else" problem, a semantic optical illusion.
Python puts up guardrails not necessarily to prevent you from driving off the cliff, but to steer you away
from danger. The same example:
if balance > 0.00:
if balance - amt > min_bal and atm_cashout():
39

Downloaded by priya loganathan (priyacs104@[Link])


print('Here's your cash; please take all bills.')
else:
print('Your balance is zero or negative.')
Python's use of indentation forces the proper alignment of code, giving the programmer the ability to
make a conscious decision as to which if an else statement belongs to.
It is impossible to create a dangling else problem in Python. Also, since parentheses are not required,
Python code is easier to read.
ELIF STATEMENT
9. WRITE SHORT NOTE ON ELIF STATEMENT. (PART-B)
elif is the Python else-if statement. It allows one to check multiple expressions for truth value and
execute a block of code as soon as one of the conditions evaluates to true.
However, unlike else, for which there can be at most one statement, there can be an arbitrary number of
elif statements following an if.
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
:
elif expressionN:
exprN_true_suite
else:
none_of_the_above_suite
One well-known benefit of using mapping types such as dictionaries is that the searching is very fast
compared to a sequential lookup as in the above if-elif-else statements or using a for loop, both of which
have to scan the elements one at a time.
CONDITIONAL EXPRESSIONS
10. EXPLAIN ABOUT CONDITIONAL EXPRESSIONS. (PART-B)
The main motivation for even having a ternary operator is to allow the setting of a value based on a
conditional all on a single line, as opposed to the standard way of using an if-else statement, as in this
min() example using numbers x and y:
x,y=4,3
if x<y:
smaller=x
else:
smaller=y
print(smaller)
Output:
3
WHILE STATEMENT
11. DISCUSS IN DETAIL ABOUT WHILE STATEMENT. (PART-B)
Python while clause will be executed continuously in a loop until that condition is no longer satisfied.
General Syntax
Here is the syntax for a while loop:
while expression:
suite_to_repeat
The suite_to_repeat clause of the while loop will be executed continuously in a loop until expression
evaluates to Boolean False.
Counting Loops
count = 0
while (count < 9):
print('the index is:', count)
count += 1
The suite here, consisting of the print and increment statements, is executed repeatedly until count is no
longer less than 9. With each iteration, the current value of the index count is displayed and then bumped
up by 1.
40

Downloaded by priya loganathan (priyacs104@[Link])


Infinite Loops
Infinite while loop refers to a while loop where the while condition never becomes false. When a
condition never becomes false, the program enters the loop and keeps repeating that same block of code
over and over again, and the loop never ends.
For example:
a=1
while a==1:
b = input("what’s your name? ")
print("Hi", b, ", Welcome to Intellipaat!")
If we run the above code block, it will execute an infinite loop that will ask for our names again and again.
The loop won’t break until we press ‘Ctrl+C’.
FOR STATEMENT
12. EXPLAIN ABOUT FOR STATEMENT WITH EXAMPLE. (PART-B)
A for-loop is a set of instructions that is repeated, or iterated, for every value in a sequence. Sometimes
for-loops are referred to as definite loops because they have a predefined begin and end as bounded by
the sequence.
It can loop over sequence members, it is used in list comprehensions and generator expressions, and it
knows how to call an iterator's next() method and gracefully ends by catching StopIteration exceptions.
Python's for loop is more akin to a shell or scripting language's iterative foreach loop.
General Syntax
The for loop traverses through individual elements of an iterable (like a sequence or iterator) and
terminates when all the items are exhausted.
Here is its syntax:
for looping_variable in sequence:
code block
A for-loop assigns the looping variable to the first element of the sequence. It executes everything in the
code block. Then it assigns the looping variable to the next element of the sequence and executes the
code block again. It continues until there are no more elements in the sequence to assign.
Used with Sequence Types
The below examples will include string, list, and tuple types.
>>> for each in 'Sea':
... print('Current letter:', each)
...
Current letter: S
Current letter: e
Current letter: a
When iterating over a string, the iteration variable will always consist of only single characters.
When seeking characters in a string, more often than not, the programmer will either use in to test for
membership, or one of the string module functions or string methods to check for sub strings.
There are three basic ways of iterating over a sequence:
1. Iterating by Sequence Item
2. Iterating by Sequence Index
3. Iterating with Item and Index
Iterating by Sequence Item
>>> nameList = ['Arun', 'Sakthi', 'Dinesh']
>>> for each in nameList:
... print(each, "Kumaran")
Arun Kumaran
Sakthi Kumaran
Dinesh Kumaran
In the above example, a list is iterated over, and for each iteration, the eachName variable contains the
list element that we are on for that particular iteration of the loop.
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself:
41

Downloaded by priya loganathan (priyacs104@[Link])


>>> nameList = ['Ram', 'Ravi', 'Kumar', 'Suresh']
>>> for nameIndex in range(len(nameList)):
... print("Mr.", nameList[nameIndex])
...
Mr. Ram
Mr. Ravi
Mr. Kumar
Mr. Suresh
Rather than iterating through the elements themselves, we are iterating through the indices of the list.
Iterating with Item and Index
The enumerate() function adds a counter to an iterable and returns it as an enumerate object (iterator
with index and the value).
>>> nameList = ['Sanjai', 'Saran', 'Naveen']
>>> for i, each in enumerate(nameList):
... print("%d %s Kumar" % (i+1, each))
...
1 Sanjai Kumar
2 Saran Kumar
3 Naveen Kumar
USED WITH ITERATOR TYPES
Using for loops with iterators is identical to using them with sequences. An iterator does not represent a
set of items to loop over.
Iterator objects have a next() method, which is called to get subsequent items. When the set of items has
been exhausted, the iterator raises the StopIteration exception to signal that it has finished. Calling next()
and catching StopIteration is built-in to the for statement.
Range() Built-in Function:
The range function in Python is a built-in function that is commonly used to generate a sequence of
numbers. It is often used in for loops to iterate over a set of values, or to create lists and other sequences
of numbers.
Range() Full Syntax:
Python presents two different ways to use range(). The full syntax requires that two or all three integer
arguments are present: range(start, end, step=1)
The range() will then return a list where for any k, start <= k < end and k iterates from start to end in
increments of step. step cannot be 0, or an error condition will occur.
>>> x = range(3, 20, 4)
>>> for n in x:
… print(n)

3
7
11
15
19
If step is omitted and only two arguments given, step takes a default value of 1.
>>> x = range(3, 7)
>>> for n in x:
… print(n)

3
4
5
6

An example used in the interpreter environment:


>>> for eachVal in range(2, 10, 3):
42

Downloaded by priya loganathan (priyacs104@[Link])


... print("Value is: ", eachVal)
...
Value is: 2
Value is: 5
Value is: 8
Range() Abbreviated Syntax:
Range() also has two abbreviated syntax formats:
range(end)
range(start, end)
Given only a single value, start defaults to 0, step defaults to 1, and range() returns a list of numbers
from zero up to the argument end:
>>> for count in range(5):
... print(count)

0
1
2
3
4
xrange() Built-in Function:
xrange() is similar to range() except that if you have a really large range list, xrange() may come in
handier because it does not have to make a complete copy of the list in memory.
This built-in was made for exclusive use in for loops. It does not make sense outside a for loop.
SEQUENCE-RELATED BUILT-IN FUNCTIONS
13. DISCUSS ABOUT SEQUENCE RELATED BUILT-IN FUNCTIONS. (PART-B)
sorted(), reversed(), enumerate(), zip():
Below are some examples of using these loop-oriented sequence-related functions. The reason why they
are "sequence-related" is that half of them (sorted() and zip()) return a real sequence (list), while the
other two (reversed() and enumerate()) return iterators (sequence-like).
>>> albums = ('Poe', 'Gaudi', 'Freud', 'Poe2')
>>> years = (1976, 1987, 1990, 2003)
>>> for album in sorted(albums):
... print(album)
...
Freud
Gaudi
Poe
Poe2
>>> for album in reversed(albums):
... print(album)
...
Poe2
Freud
Gaudi
Poe
>>> for i, album in enumerate(albums):
... print(i, album)
...
0 Poe
1 Gaudi
2 Freud
3 Poe2

>>> for album, yr in zip(albums, years):


... print(yr, album)
43

Downloaded by priya loganathan (priyacs104@[Link])


...
1976 Poe
1987 Gaudi
1990 Freud
2003 Poe2
BREAK STATEMENT
14. COMMENT ON BREAK STATEMENT. (PART-B)
The break statement in Python terminates the current loop and resumes execution at the next statement.
The most common use for break is when some external condition is triggered (usually by testing with an
if statement), requiring a hasty exit from a loop.
The break statement can be used in both while and for loops. For example:
num=int(input("Enter the Number:"))
count = num / 2
while(count > 0):
if(num % count == 0):
print(int(count),"is the largest factor of", num)
break
count -= 1
The task of this piece of code is to find the largest divisor of a given number num.
CONTINUE STATEMENT
15. DISCUSS IN DETAIL ABOUT CONTINUE STATEMENT. (PART-B)
The continue statement is used to end the current iteration in a for loop (or a while loop), and continues
to the next iteration.
The while loop is conditional, and the for loop is iterative, so using continue is subject to the same
requirements before the next iteration of the loop can begin. Otherwise, the loop will terminate normally.
for var in "College":
if var == "e":
continue
print(var)
Output:
C
o
l
l
g
PASS STATEMENT
16. EXPLAIN ABOUT PASS STATEMENT. (PART-B)
Python pass statement is used when a statement is required syntactically but you do not want any
command or code to execute.
Python pass statement is a null operation; nothing happens when it executes. Python pass statement is
also useful in places where your code will eventually go, but has not been written yet. For example:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
44

Downloaded by priya loganathan (priyacs104@[Link])


Good bye!
ITERATORS AND THE ITER () FUNCTION
17. DISCUSS IN DETAIL ABOUT ITERATORS IN PYTHON. (PART-B)
18. COMMENT ON ITER( ). (PART-B)
WHAT ARE ITERATORS?
Iterators come in handy when we are iterating over something that is not a sequence but exhibits
behavior that makes it seem like a sequence, for example, keys of a dictionary, lines of a file, etc.
WHY ITERATORS?
The defining PEP (234) cites that iterators:
❖ Provide an extensible iterator interface.
❖ Bring performance enhancements to list iteration.
❖ Allow for big performance improvements in dictionary iteration.
❖ Allow for the creation of a true iteration interface as opposed to overriding methods originally meant
for random element access.
❖ Be backward-compatible with all existing user-defined classes and extension objects that emulate
sequences and mappings.
❖ Result in more concise and readable code that iterates over non-sequence collections (mappings and
files, for instance).
HOW DO YOU ITERATE?
Basically, instead of an index to count sequentially, an iterator is any item that has a next() method.
When the next item is desired, either you or a looping mechanism like for will call the iterators next()
method to get the next value.
Once the items have been exhausted, a StopIteration exception is raised, not to indicate an error, but to
let folks know that we are done.
Iterators do have some restrictions. For example, you cannot move backward, go back to the beginning,
or copy an iterator.
If you want to iterate over the same objects again (or simultaneously), you have to create another iterator
object.
There is a reversed() built-in function that returns an iterator that traverses an iterable in reverse order.
There is also an entire module called itertools that contains various iterators you may find useful.
USING ITERATORS WITH SEQUENCES
Iterating through Python sequence types is as expected:
>>> myTuple = (123, 'xyz', 45.67)
>>> i = iter(myTuple)
>>> print(next(i))
123
>>> print(next(i))
'xyz'
>>> print(next(i))
45.67
>>> print(next(i))
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
print(next(i))
StopIteration
USING ITERATORS WITH DICTIONARIES
Dictionaries and files are two other Python data types that received the iteration makeover. A
dictionary's iterator traverses its keys.
Example:
>>> likes = {"color": "blue", "fruit": "apple", "pet": "dog"}
>>> for key in likes:
... print(key, "->", likes[key])
...
color -> blue
fruit -> apple
45

Downloaded by priya loganathan (priyacs104@[Link])


pet -> dog
USING ITERATORS WITH FILES
File objects produce an iterator that calls the readline() method. Thus, they loop through all lines of a
text file, allowing the programmer to replace essentially for eachLine in [Link]() with the
more simplistic for eachLine in myFile:
>>> myFile = open('[Link]')
>>> for eachLine in myFile:
... print(eachLine)
...
This is a New File. Just Created!
>>> [Link]()
MUTABLE OBJECTS AND ITERATORS
Remember that interfering with mutable objects while you are iterating them is not a good idea. This was
a problem before iterators appeared.
One popular example of this is to loop through a list and remove items from it if certain criteria are met
(or not):
for eachURL in allURLs:
if not [Link]('[Link]
[Link](eachURL)
All sequences are immutable except lists, so the danger occurs only there. A sequence's iterator only
keeps track of the Nth element you are on, so if you change elements around during iteration, those
updates will be reflected as you traverse through the items. If you run out, then StopIteration will be
raised.
HOW TO CREATE AN ITERATOR
Its syntax is one of the following:
1. iter(obj)
2. iter(func, sentinel)
If you call iter() with one object, it will check if it is just a sequence, for which the solution is simple: It
will just iterate through it by (integer) index from 0 to the end.
If you call iter() with two arguments, it will repeatedly call func to obtain the next value of iteration until
that value is equal to sentinel.
FILES AND INPUT/OUTPUT
19. DISCUSS IN DETAIL ABOUT FILES AND I/O. (PART-B)
FILE OBJECTS
File objects can be used to access not only normal disk files, but also any other type of "file" that uses
that abstraction. Once the proper "hooks" are installed, you can access other objects with file-style
interfaces in the same manner you would access normal files.
We will find many cases where we are dealing with "file-like" objects. Some examples include "opening
a URL" for reading a Web page in real-time and launching a command in a separate process and
communicating to and from it like a pair of simultaneously open files, one for write and the other for
read.
The open() built-in function returns a file object that is then used for all succeeding operations on the
file. There are a large number of other functions that return a file or file-like object. One primary reason
for this abstraction is that many input/output data structures prefer to adhere to a common interface. It
provides consistency in behavior as well as implementation.
FILE BUILT-IN FUNCTIONS [OPEN() AND FILE()]
20. EXPLAIN ABOUT FILE BUILT-IN FUNCTIONS. (PART-B)
The open() built-in function provides a general interface to initiate the file input/output (I/O) process.
The open() BIF returns a file object on a successful opening of the file or else results in an error
situation. When a failure occurs, Python generates or raises an IOError exception.
The basic syntax of the open() built-in function is:
file_object = open(file_name, access_mode='r', buffering=-1)
The file_name is a string containing the name of the file to open. It can be a relative or absolute/full
pathname. The access_mode optional variable is also a string, consisting of a set of flags indicating

46

Downloaded by priya loganathan (priyacs104@[Link])


which mode to open the file with. Generally, files are opened with the modes 'r,' 'w,'or 'a,' representing
read, write, and append, respectively.
Any file opened with mode 'r' or 'U' must exist. Any file opened with 'w' will be truncated first if it
exists, and then the file is (re)created.
Any file opened with 'a' will be opened for append. All writes to files opened with 'a' will be from end-
of-file, even if you seek elsewhere during access.
If the file does not exist, it will be created, making it the same as if you opened the file in 'w' mode.
There are other modes supported by fopen() that will work with Python's open(). These include the '+'
for read-write access and 'b' for binary access.
If access_mode is not given, it defaults automatically to 'r.'
The other optional argument, buffering, is used to indicate the type of buffering that should be performed
when accessing the file.
A value of 0 means no buffering should occur, a value of 1 signals line buffering, and any value greater
than 1 indicates buffered I/O with the given value as the buffer size.
The lack of or a negative value indicates that the system default buffering scheme should be used, which
is line buffering for any teletype or tty-like device and normal buffering for everything else. Under
normal circumstances, a buffering value is not given, thus using the system default.
Here are some examples for opening files:
fp = open('/etc/motd') #open file for read
fp = open('test', 'w') #open file for write
fp = open('data', 'r+') #open file for read/write
fp = open('c:\[Link]', 'rb') #open binary file for read
THE FILE() FACTORY FUNCTION
Both open() and file() do exactly the same thing and one can be used in place of the other. Anywhere
you see references to open(), you can mentally substitute file() without any side effects whatsoever.
Generally, the accepted style is that we use open() for reading/writing files, while file() is best used
when we want to show that we are dealing with file objects, i.e., if instance(f, file).
UNIVERSAL NEWLINE SUPPORT (UNS)
In a Python with universal newline support open() the mode parameter can also be “U”, meaning “open
for input as a text file with universal newline interpretation”. Mode “rU” is also allowed, for symmetry
with “rb”. Mode “U” cannot be combined with other mode flags such as “+”. Any line ending in the
input file will be seen as a '\n' in Python, so little other code has to change to handle universal newlines.
A file object that has been opened in universal newline mode gets a new attribute “newlines” which
reflects the newline convention used in the file. The value for this attribute is one of None (no newline
read yet), "\r", "\n", "\r\n" or a tuple containing all the newline types seen.
FILE BUILT-IN METHODS
21. DISCUSS ABOUT FILE BUILT-IN METHODS. (PART-B)
File methods come in four different categories: input, output, movement within a file (Intra-file motion),
and miscellaneous.
1) Input:
The read() method is used to read bytes directly into a string, reading at most the number of bytes
indicated. If no size is given (the default value is set to integer -1) or size is negative, the file will be read
to the end.
The readline() method reads one line of the open file. The line, including termination character(s), is
returned as a string. Like read(), there is also an optional size option, which, if not provided, default to 1,
meaning read until the line-ending characters (or EOF) are found. If present, it is possible that an
incomplete line is returned if it exceeds size bytes.
The readlines() method reads all (remaining) lines and returns them as a list of strings. Its optional
argument, sizhint, is a hint on the maximum size desired in bytes. If provided and greater than zero,
approximately sizhint bytes in whole lines are read and returned as a list.
Instead of reading all the lines in at once, xreadlines() reads in chunks at a time, and thus were optimal
for use with for loops in a memory-conscious way.
Another odd bird is the readinto() method, which reads the given number of bytes into a writable buffer
object, the same type of object returned by the unsupported buffer() built-in function.
2) Output:
47

Downloaded by priya loganathan (priyacs104@[Link])


The write() built-in method has the opposite functionality as read() and readline(). It takes a string that
can consist of one or more lines of text data or a block of bytes and writes the data to the file.
The writelines() method operates on a list just like readlines(), but takes a list of strings and writes them
out to a file. Line termination characters are not inserted between each line, so if desired, they must be
added to the end of each line before writelines() is called.
3) Intra-file Motion:
The seek() method moves the file pointer to different positions within the file. The offset in bytes is
given along with a relative offset location, whence.
A value of 0, the default, indicates distance from the beginning of a file (a position measured from the
beginning of a file is also known as the absolute offset), a value of 1 indicates movement from the
current location in the file, and a value of 2 indicates that the offset is from the end of the file.
Use of the seek() method comes into play when opening a file for read and write access. tell() is a
complementary method to seek(); it tells you the current location of the filein bytes from the beginning
of the file.
4) File Iteration:
Going through a file line by line is simple:
for eachLine in f:
:
Inside this loop, to do whatever we need to with eachLine, representing a single line of the text file.
Using [Link]() to read in all the data, giving the programmer the ability to free up the file
resource as quickly as possible. If that was not a concern, then programmers could call [Link]() to
read in one line at a time.
The iterator next method, [Link]() could be called as well to read in the next line in the file. Like all
other iterators, Python will raise StopIteration when no more lines are available.
So remember, if you see this type of code, this is the "old way of doing it," and you can safely remove
the call to readline().
for eachLine in [Link]():
:
Others:
The close() method completes access to a file by closing it.
The Python garbage collection routine will also close a file when the file object reference has decreased
to zero.
It is possible to lose output data that is buffered if you do not explicitly close a file.
The fileno() method passes back the file descriptor to the open file. This is an integer argument that can
be used in lower-level operations such as those featured in the os module, i.e., [Link]().
Rather than waiting for the (contents of the) output buffer to be written to disk, calling the flush()
method will cause the contents of the internal buffer to be written (or flushed) to the file immediately.
The isatty() is a Boolean built-in method that returns true if the file is a tty-like device and False
otherwise.
The Truncate() method truncates the file to the size at the current file position or the given size in bytes.
File Method Miscellany:
Example:
filename = input('Enter file name: ')
f = open(filename, 'r')
for eachLine in f:
print(eachLine,)
[Link]()
The comma placed at the end of the print statement is to suppress the NEWLINE character that print
normally adds at the end of output. The reason for this is because every line from the text file already
contains a NEWLINE.
File objects also have a truncate() method, which takes one optional argument, size. If it is given, then
the file will be truncated to, at most, size bytes.
If you call truncate() without passing in a size, it will default to the current location in the file. For
example, if you just opened the file and call truncate(), your file will be effectively deleted, truncated to
zero bytes because upon opening a file, the "read head" is on byte 0, which is what tell() returns.
48

Downloaded by priya loganathan (priyacs104@[Link])


Example for both file input and output as well as using the seek() and tell() methods for file positioning
is as follows:
import os
filename = input('Enter file name: ')
fobj = open(filename, 'w')
while True:
aLine = input("Enter a line ('.' to quit): ")
if aLine != ".":
[Link]('%s%s' % (aLine, [Link]))
else:
break
[Link]()
FILE BUILT-IN ATTRIBUTES
22. EXPLAIN ABOUT FILE BUILT-IN ATTRIBUTES. (PART-B)
File Object Attribute Description
[Link] True if file is closed and False otherwise.
Encoding that this file uses when Unicode strings are written to file, they will
[Link] be converted to byte strings using [Link]; a value of None indicates
that the system default encoding for converting Unicode strings should be used.
[Link] Access mode with which file was opened.
[Link] Name of file.
None if no line separators have been read, a string consisting of one type of
[Link] line separator, or a tuple containing all types of line termination characters
read so far.
[Link] 0 if space explicitly required with print, 1 otherwise;
STANDARD FILES
There are generally three standard files that are made available to our program starts. These are standard
input (usually the keyboard), standard output (buffered output to the monitor or display), and standard
error (unbuffered output to the screen).
Python makes these file handles available to you from the sys module. Once you import sys, you have
access to these files as [Link], [Link], and [Link]. The print statement normally outputs to
[Link] while the input() built-in function receives its input from [Link].
COMMAND-LINE ARGUMENTS
23. DISCUSS IN DETAIL ABOUT COMMAND LINE ARGUMENTS. (PART-B)
The sys module also provides access to any command-line arguments via [Link]. Command-line
arguments are those arguments given to the program in addition to the script name on invocation.
In Python, the value for argc is simply the number of items in the [Link] list, and the first element of
the list, [Link][0], is always the program name.
Summary:
❖ [Link] is the list of command-line arguments.
❖ len([Link]) is the number of command-line arguments.
To create a small test program called [Link] with the following lines:
import sys
print('you entered', len([Link]), 'arguments...')
print('they were:', str([Link]))
REFERENCE BOOK:
1. Wesley J. Chun, "Core Python Programming", Pearson Education Publication, 2012.
2. [Link]
IMPORTANT / POSSIBLE QUESTIONS
PART – A (1 MARK)
1. What will be the output of the following Python code?
x = 123
for i in x:
49

Downloaded by priya loganathan (priyacs104@[Link])


print(i)
a) 1 2 3 b) 123 c) error d) none of the mentioned
2. What will be the output of the following Python code?
i=1
while True:
if i%3 == 0:
break
print(i)
i+=1
a) 1 2 b) 1 2 3 c) error d) none of the mentioned
3. Which of the following functions is a built-in function in python?
a) seed() b) sqrt() c) factorial() d) print()
4. What will be the output of the following Python expression?
round(4.576)
a) 4.5 b) 5 c) 4 d) 4.6
5. What will be the output of the following Python function?
sum(2,4,6)
sum([1,2,3])
a) Error, 6 b) 12, Error c) 12, 6 d) Error, Error
6. What will be the output of the following Python code?
def to_upper(k):
return [Link]()
x = ['ab', 'cd']
print(list(map(to_upper, x)))
a) [‘AB’, ‘CD’] b) [‘ab’, ‘cd’] c) none of the mentioned d) error
7. What will be the output of the following Python code?
x = ['ab', 'cd']
print(list(map(len, x)))
a) [‘ab’, ‘cd’] b) [2, 2] c) [‘2’, ‘2’] d) none of the mentioned
8. To obtain a list of all the functions defined under sys module, which of the following functions can be
used?
a) print(sys) b) print([Link]) c) print(dir[sys]) d) print(dir(sys))
9. The output of the function len([Link]) is
a) Error b) 1 c) 0 d) Junk value
10. To open a file c:\[Link] for reading, we use
a) infile = open(“c:\[Link]”, “r”) b) infile = open(“c:\\[Link]”, “r”)
c) infile = open(file = “c:\[Link]”, “r”) d) infile = open(file = “c:\\[Link]”, “r”)
11. To open a file c:\[Link] for appending data, we use
a) outfile = open(“c:\\[Link]”, “a”)
b) outfile = open(“c:\\[Link]”, “rw”)
c) outfile = open(file = “c:\[Link]”, “w”)
d) outfile = open(file = “c:\\[Link]”, “w”)
12. To read two characters from a file object infile, we use
a) [Link](2) b) [Link]() c) [Link]() d) [Link]()
13. What will be the output of the following Python function?
len(["hello",2, 4, 6])
a) 4 b) 3 c) Error d) 6
14. What will be the output of the following Python code?
for i in range(10):
if i == 5:
break
else:
print(i)
else:
print("Here")
50

Downloaded by priya loganathan (priyacs104@[Link])


a) 0 1 2 3 4 Here b) 0 1 2 3 4 5 Here c) 0 1 2 3 4 d) 1 2 3 4 5

PART – B (5 MARKS)
1. Explain about Dictionaries. (Refer [Link]: 37,[Link])
2. Discuss about Mapping type operators. (Refer [Link]: 37,[Link])
3. Explain about Factory functions. (Refer [Link]: 37,[Link])
4. Discuss about Mapping type built-in methods. (Refer [Link],[Link])
5. Discuss about if statements. (Refer [Link],[Link])
6. Explain about else statements in python. (Refer [Link]: 40,[Link])
7. Write short note on elif statement. (Refer [Link]: 41,[Link])
8. Explain about Conditional expressions. (Refer [Link]: 41,[Link])
9. Discuss in detail about While statement. (Refer [Link]: 41,[Link])
10. Explain about For statement with example. (Refer [Link]: 42,[Link])
11. Comment on Break statement. (Refer [Link],[Link])
12. Discuss in detail about Continue statement. (Refer [Link]: 45,[Link])
13. Explain about Pass statement. (Refer [Link]: 45,[Link])
14. Discuss in detail about Iterators in Python. (Refer [Link],[Link])
15. Discuss in detail about Files and I/O. (Refer [Link]: 47,[Link])
16. Explain about file Built-in functions. (Refer [Link],[Link])
17. Discuss about file Built-in methods. (Refer [Link]: 48,[Link])
PART – C (10 MARKS)
1. Write short note on Mapping type built-in functions. (Refer [Link]: 37,[Link])
2. Write short note on Looping. (Refer [Link]: 40,[Link])
3. Discuss about Sequence related built-in functions. (Refer [Link]: 44,[Link])
4. Discuss in detail about Command line arguments. (Refer [Link]: 50,[Link])

*****UNIT – III COMPLETED*****

51

Downloaded by priya loganathan (priyacs104@[Link])

You might also like