Module 2
Functions
1. “def” Statements with Parameters
2. Return Values and return Statements
3. The None Value
4. Keyword Arguments and print()
23PLCS21- Introduction to Python Programming [Link] H B
Functions
• A function is like a mini-program within a program.
• Python provides several builtin functions like print(), input(), and len() etc.,
• It also allow to write own functions.
[Link] H B 23PLCS21- Introduction to Python Programming
Functions
Defines a function hello().
Body of the function
Function calls
[Link] H B 23PLCS21- Introduction to Python Programming
def Statements with Parameters
• A parameter is a variable that an argument is stored in when a function is called.
[Link] H B 23PLCS21- Introduction to Python Programming
Return Values and return Statements
• The value that a function call evaluates to is called the return value of the function.
• While creating a function using the def statement, specify what the return value
should be with a return statement.
• A return statement consists of the following:
• The return keyword
• The value or expression that the function should return
[Link] H B 23PLCS21- Introduction to Python Programming
[Link] H B 23PLCS21- Introduction to Python Programming
The None Value
• None - represents the absence of a value
• None is the only value of the NoneType data type.
[Link] H B 23PLCS21- Introduction to Python Programming
Keyword Arguments and print()
• Keyword arguments are often used for optional parameters.
• For example,
• end to specify what should be printed at the end of its arguments
• sep to specify what should be printed between its arguments
[Link] H B 23PLCS21- Introduction to Python Programming
Functions
1. Local and Global Scope
2. The global Statement
23PLCS21- Introduction to Python Programming [Link] H B
Local and Global Scope
• Parameters and variables that are assigned in a called function are exist in that
function’s local scope called a local variable.
• Variables that are assigned outside all functions are said to exist in the global
scope is called a global variable.
[Link] H B 23PLCS21- Introduction to Python Programming
Local Scopes Cannot Use Variables in Other Local
Scopes
• Output will be99
• But not 0
[Link] H B 23PLCS21- Introduction to Python Programming
Global Variables Can Be Read from a Local Scope
• Output will be 42 for both print
statements
[Link] H B 23PLCS21- Introduction to Python Programming
Local and Global Variables with the Same Name
[Link] H B 23PLCS21- Introduction to Python Programming
The global Statement
• If you need to modify a global variable from within a function, use the global statement
[Link] H B 23PLCS21- Introduction to Python Programming
Functions
1. Exception Handling
2. A Short Program: Guess the Number
23PLCS21- Introduction to Python Programming [Link] H B
Exception Handling
• Getting an error, or exception, in program means the entire program will crash.
• This should not happen in real-world programs.
• Instead, the program should detect errors, handle them, and then continue to run.
• Errors can be handled with try and except statements
[Link] H B 23PLCS21- Introduction to Python Programming
Exception Handling
[Link] H B 23PLCS21- Introduction to Python Programming
Exception Handling
[Link] H B 23PLCS21- Introduction to Python Programming
A Short Program: Guess the Number
[Link] H B 23PLCS21- Introduction to Python Programming
[Link] H B 23PLCS21- Introduction to Python Programming
Module 2
Lists:
The List Data Type, Working with Lists, Augmented Assignment
Operators, Methods,
[Link] H B 23PLCS21- Introduction to Python Programming
The List Data Type
• A list is a value that contains multiple values in an ordered sequence.
• A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
• Just as string values are typed with quote characters to mark where the string begins and ends, a
list begins and ends with square bracket, [].
• Values inside the list are also called items. Items are separated with commas ,
• The value [] is an empty list that contains no values, similar to '', the empty string.
[Link] H B 23PLCS21- Introduction to Python Programming
The List Data Type
23PLCS21- Introduction to Python Programming [Link] H B
Getting Individual Values in a List
with Indexes
23PLCS21- Introduction to Python Programming [Link] H B
List with Invalid Indexes
23PLCS21- Introduction to Python Programming [Link] H B
Getting Individual Values in a List
with Indexes
• Lists can also contain other list values.
• The values in these lists of lists can be accessed using multiple indexes
23PLCS21- Introduction to Python Programming [Link] H B
Negative Indexes
While indexes start at 0 and go up, you can also use negative integers for
the index.
1. The integer value -1 refers to the last index in a list.
2. The value -2 refers to the second-to-last index in a list, and so on
23PLCS21- Introduction to Python Programming [Link] H B
Getting Sublists with Slices
• A Slice can get several values from a list, in the form of a new list.
• A slice is typed between square brackets, like an index, but it has two integers
separated by a colon :
• spam[2] is a list with an index (one integer).
• spam[1:4] is a list with a slice (two integers).
23PLCS21- Introduction to Python Programming [Link] H B
Getting Sublists with Slices
• As a shortcut, you can leave out one or both of the indexes on either side of the colon in the slice.
• Leaving out the first index is the same as using 0, or the beginning of the list.
• Leaving out the second index is the same as using the length of the list, which will slice to the end of the
list.
23PLCS21- Introduction to Python Programming [Link] H B
Python List Methods
[Link]() adds an element to the end of the list
[Link]() adds all elements of a list to another list
[Link]() inserts an item at the defined index
[Link]() removes an item from the list
[Link]() returns and removes an element at the
given index
[Link]() removes all items from the list
23PLCS21- Introduction to Python Programming [Link] H B
Python List Methods
[Link]() returns the index of the first matched item
[Link]() returns the count of the number times the
specified element appears in the list.
[Link]() sort items in a list in ascending order
[Link]() reverse the order of items in the list
[Link]() returns a shallow copy of the list
23PLCS21- Introduction to Python Programming [Link] H B
1. append()
• adds an element to the end of the list
currencies = ['Dollar', 'Euro', 'Pound']
# append 'Yen' to the list
[Link]('Yen')
print(currencies)
# Output: ['Dollar', 'Euro', 'Pound', 'Yen']
23PLCS21- Introduction to Python Programming [Link] H B
[Link]()
• adds all elements of a list to another list
# create a list
prime_numbers = [2, 3, 5]
# create another list
numbers = [1, 4]
# add all elements of prime_numbers to numbers
[Link](prime_numbers)
print('List after extend():', numbers)
# Output: List after extend(): [1, 4, 2, 3, 5]
23PLCS21- Introduction to Python Programming [Link] H B
3. insert()
• inserts an item at the defined index
# create a list of vowels
vowel = ['a', 'e', 'i', 'u']
#insert ‘o’ at index 3 (4th position)
[Link](3, 'o')
print('List:', vowel)
# Output: List: ['a', 'e', 'i', 'o', 'u']
23PLCS21- Introduction to Python Programming [Link] H B
[Link]()
• removes an item from the list
# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]
# remove 9 from the list
prime_numbers.remove(9)
# Updated prime_numbers List
print('Updated List: ', prime_numbers)
# Output: Updated List: [2, 3, 5, 7, 11]
NB: removes the first matching element (which is passed as an
argument) from the list.
23PLCS21- Introduction to Python Programming [Link] H B
5. pop()returns and removes an element at the given index
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# remove the element at index 2
removed_element = prime_numbers.pop(2)
print('Removed Element:', removed_element)
print('Updated List:', prime_numbers)
# Output:
# Removed Element: 5
# Updated List: [2, 3, 7]
23PLCS21- Introduction to Python Programming [Link] H B
6. index()
• returns the index of the first matched item
animals = ['cat', 'dog', 'rabbit', 'horse']
# get the index of 'dog'
index = [Link]('dog')
print(index)
# Output: 1
23PLCS21- Introduction to Python Programming [Link] H B
[Link]()
• returns the count of the number of times the specified element appears in
the list.
# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]
# check the count of 2
count = [Link](2)
print('Count of 2:', count)
# Output: Count of 2: 3
23PLCS21- Introduction to Python Programming [Link] H B
[Link]()
• sort items in a list in ascending order
prime_numbers = [11, 3, 7, 5, 2]
# sort the list
prime_numbers.sort()
print(prime_numbers)
# Output: [2, 3, 5, 7, 11]
23PLCS21- Introduction to Python Programming [Link] H B
[Link]()
• reverse the order of items in the list
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# reverse the order of list elements
prime_numbers.reverse()
print('Reversed List:', prime_numbers)
# Output: Reversed List: [7, 5, 3, 2]
23PLCS21- Introduction to Python Programming [Link] H B
[Link]()
• returns a shallow copy of the list
# mixed list
prime_numbers = [2, 3, 5]
# copying a list
numbers = prime_numbers.copy()
print('Copied List:', numbers)
# Output: Copied List: [2, 3, 5]
23PLCS21- Introduction to Python Programming [Link] H B
Getting a List’s Length with len()
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
23PLCS21- Introduction to Python Programming [Link] H B
Changing Values in a List with
Indexes
23PLCS21- Introduction to Python Programming [Link] H B
List Concatenation and List
Replication
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']
23PLCS21- Introduction to Python Programming [Link] H B
Removing Values from Lists with del
Statements
• The del statement will delete values at an index in a list.
• All of the values in the list after the deleted value will be moved up one index.
23PLCS21- Introduction to Python Programming [Link] H B
Working with Lists
• Creating many individual variables to store a group of similar values
23PLCS21- Introduction to Python Programming [Link] H B
Working with Lists
print('Enter the name of cat 1:')
catName1 = input()
print('Enter the name of cat 2:')
catName2 = input()
print('Enter the name of cat 3:')
catName3 = input()
print('Enter the name of cat 4:')
catName4 = input()
print('The cat names are:') print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' +
catName4 + ' ' + catName5 + ' ' + catName6)
• It turns out that this is a bad way to write code
23PLCS21- Introduction to Python Programming [Link] H B
Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
Enter the name of cat 2 (Or enter nothing to stop.):
Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
Simon
Enter the name of cat 4 (Or enter nothing to stop.):
Lady Macbeth
Enter the name of cat 5 (Or enter nothing to stop.):
Fat-tail
The cat names are: Zophie Pooka Simon Lady
Macbeth Fat-tail
23PLCS21- Introduction to Python Programming [Link] H B
Working with Lists
• Instead of using multiple, repetitive variables, use a single variable that contains a
list value
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
23PLCS21- Introduction to Python Programming [Link] H B
Using for Loops with Lists
for loop repeats the code block once for each value in a list or list-like value
output
Example for i in [0, 1, 2, 3]: 0
for i in range(4): print(i) 1
print(i) 2
3
It loop through its clause with the variable i set to a successive value
in the [0, 1, 2, 3] list in each iteration
23PLCS21- Introduction to Python Programming [Link] H B
Using for Loops with Lists
• A common Python technique is to use range(len(someList)) with a for loop to iterate
over the indexes of a list
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binder
23PLCS21- Introduction to Python Programming [Link] H B
The in and not in Operators
• You can determine whether a value is or isn’t in a list
• used in expressions and connect two values
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
23PLCS21- Introduction to Python Programming [Link] H B
The Multiple Assignment Trick
• The multiple assignment trick is a shortcut that lets you assign multiple variables with the
values in a list in one line of code.
>>> cat = ['fat', 'black', 'loud'] >>> cat = ['fat', 'black', 'loud']
>>> size = cat[0] >>> size, color, disposition = cat
>>> color = cat[1]
>>> disposition = cat[2]
23PLCS21- Introduction to Python Programming [Link] H B
NB:The number of variables and the length of the list must be exactly equal,
or Python will give you a ValueError:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition, name = cat
ValueError: need more than 3 values to unpack
23PLCS21- Introduction to Python Programming [Link] H B
Augmented Assignment Operators
>>> spam = 42
>>> spam = spam + 1 >>> spam += 1
>>> spam
43
Augmented assignment statement Equivalent assignment statement
spam = spam + 1 spam += 1
spam = spam – 1 spam -= 1
spam = spam * 1 spam *= 1
spam = spam / 1 spam /= 1
spam = spam % 1 spam %= 1
23PLCS21- Introduction to Python Programming [Link] H B
Methods
• A method is the same thing as a function, except it is “called on” a value.
• index() Method
• append() and insert() Methods
• remove()
• sort() Method
23PLCS21- Introduction to Python Programming [Link] H B
Finding a Value in a List with the
index() Method
When there are duplicates of the value in the list, the index of its first appearance is returned.
23PLCS21- Introduction to Python Programming [Link] H B
Adding Values to Lists with the append() and insert()
Methods
append() insert()
23PLCS21- Introduction to Python Programming [Link] H B
Removing Values from Lists with
remove()
If the value appears multiple times in the list, only the first instance of the value will be removed.
Attempting to delete a value that does not exist in the list
23PLCS21- Introduction to Python Programming [Link] H B
Sorting the Values in a List with the
sort() Method
>>> spam = [2, 5, 3.14, 1, -7]
>>> [Link]()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> [Link]()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
23PLCS21- Introduction to Python Programming [Link] H B
Sorting the Values in a List with the
sort() Method
You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order.
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> [Link](reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
23PLCS21- Introduction to Python Programming [Link] H B
Sorting the Values in a List with the
sort() Method
cannot sort lists that have both number values and string values in them
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> [Link]()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
[Link]()
TypeError: unorderable types: str() < int()
23PLCS21- Introduction to Python Programming [Link] H B
Sorting the Values in a List with the
sort() Method
sort() uses “ASCIIbetical order” rather than actual alphabetical
order for sorting strings.
This means uppercase letters come before lowercase letters.
>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
>>> [Link]()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
23PLCS21- Introduction to Python Programming [Link] H B
Sorting the Values in a List with the
sort() Method
To sort the values in regular alphabetical order pass str. lower for the key keyword argument in the sort()
method call.,
23PLCS21- Introduction to Python Programming [Link] H B
Example Program: Magic 8 Ball
with a List
23PLCS21- Introduction to Python Programming [Link] H B
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
[Link] H B 23PLCS21- Introduction to Python Programming
List-like Types: Strings and Tuples
• Lists aren’t the only data types that represent ordered sequences of values.
• For example, strings and lists are actually similar, if you consider a string to be a
“list” of single text characters.
• Many of the things you can do with lists can also be done with strings:
indexing;
slicing;
Using them with for loops,
len(),
in and not in operators.
23PLCS21- Introduction to Python Programming [Link] H B
Example
>>> name[0:4]
>>> name = 'Zophie'
'Zoph'
>>> name[0]
>>> 'Zo' in name
'Z'
True
>>> name[-2]
>>> 'z' in name
'i'
False
>>> 'p' not in name
False
[Link] H B 23PLCS21- Introduction to Python Programming
>>> name = ‘REJI’
>>> for i in name: print('* * * ' + i + ' * * *’)
***R***
* * *E * * *
***J***
***I***
[Link] H B 23PLCS21- Introduction to Python Programming
Mutable and Immutable Data
Types
• A list value is a mutable data type: It can have values added, removed, or changed.
• A string is immutable: It cannot be changed. Trying to reassign a single character in a
string results in a TypeError error,
>>> name = 'Zophie a cat'
>>> name[7] = 'the'
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
name[7] = 'the'
TypeError: 'str' object does not support item
assignment
23PLCS21- Introduction to Python Programming [Link] H B
• The proper way to “mutate” a string is to use slicing and concatenation
• >>> name = 'Zophie a cat'
• >>> newName = name[0:7] + 'the' + name[8:12]
• >>> name
• 'Zophie a cat'
• >>> newName
• 'Zophie the cat'
[Link] H B 23PLCS21- Introduction to Python Programming
The Tuple Data Type
• The tuple data type is almost identical to the list data type, except in two ways.
• Tuples are typed with parentheses, ( and ),
• Tuples are immutable
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
23PLCS21- Introduction to Python Programming [Link] H B
like strings, tuples are immutable.
Tuples cannot have their values modified, appended, or removed.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item
assignment
[Link] H B 23PLCS21- Introduction to Python Programming
Converting Types with the list() and tuple()
Functions
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
23PLCS21- Introduction to Python Programming [Link] H B
Mutable List
23PLCS21- Introduction to Python Programming [Link] H B
Mutable List :del and append can be used
23PLCS21- Introduction to Python Programming [Link] H B
References
Variables store strings and integer values
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam 100
>>> cheese 42
NB:change the value in one variable doesn’t affect the value in
another variable.
[Link] H B 23PLCS21- Introduction to Python Programming
References
• When you assign a list to a variable, you are actually assigning a list reference to the
variable.
• list reference is a value that points to a list
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = 'Hello!'
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese
[0, 'Hello!', 2, 3, 4, 5]
NB:values stored in spam and cheese now both
refer to the same list.
23PLCS21- Introduction to Python Programming [Link] H B
spam = [0, 1, 2, 3, 4, 5]
Stores a reference to a list, not the actual list.
spam = cheese
copies the reference, not the list
[Link] H B 23PLCS21- Introduction to Python Programming
def eggs(someParameter):
[Link]('Hello')
print(someParameter)
spam = [1, 2, 3]
eggs(spam)
print(spam)
[1, 2, 3, 'Hello']
When a function is called,
• The values of the arguments are copied to the parameter variables
• In case of list, copy of refrence are copied
23PLCS21- Introduction to Python Programming [Link] H B
The copy Module’s copy() and deepcopy()
Functions
• If the function modifies the list or dictionary that is passed, you may not want these changes in the
original list or dictionary value.
• For this, Python provides a module named copy that provides both the copy() and deepcopy() functions.
• The deepcopy() function is used to copy if list is having multiple lists as .
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = [Link](spam)
>>> cheese>>> spam[1] = 42
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']
[Link] H B 23PLCS21- Introduction to Python Programming
Module 3
Dictionaries and Strings
23PLCS21- Introduction to Python Programming [Link] H B
The Dictionary Data Type
• A dictionary is a collection of many values.
• But unlike indexes for lists, indexes for dictionaries can use many different
data types, not just integers.
• Indexes for dictionaries are called keys, and a key with its associated value is
called a key-value pair.
• a dictionary is typed with braces, {}
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
23PLCS21- Introduction to Python Programming [Link] H B
The Dictionary Data Type
You can access these values through their keys
>>> myCat['size']
'fat'
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
• Dictionaries can still use integer values as keys, just like lists use integers for indexes
• Dictionary indexes do not have to start at 0
>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}
23PLCS21- Introduction to Python Programming [Link] H B
Dictionaries vs. Lists
There is no “first” item in a dictionary
It does not matter in what order the key-value pairs are typed in a dictionary
Since dictionaries are not ordered, they can’t be sliced like lists.
>>> spam = ['cats', 'dogs', 'moose']
>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon
False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
23PLCS21- Introduction to Python Programming [Link] H B
“out-of-range” IndexError
23PLCS21- Introduction to Python Programming [Link] H B
Example
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
23PLCS21- Introduction to Python Programming [Link] H B
The keys(), values(), and items()
Methods
• They are dictionary methods that will return list-like values of the dictionary’s
keys, values, or both keys and values.
• The values returned by these methods are not true lists:
• They cannot be modified and do not have an append() method.
>>> spam = {'color': 'red', 'age': 42}
>>> for v in [Link]():
print(v)
red
42
23PLCS21- Introduction to Python Programming [Link] H B
spam = {'color': 'red', 'age': 42}
for k in [Link](): A for loop can iterate over the keys
print(k)
Output
color
age
for i in [Link](): A for loop iterate over both keys and values:
print(i)
Output
('color', 'red')
('age', 42)
[Link] H B 23PLCS21- Introduction to Python Programming
Printing true list from one of these methods
>>> spam = {'color': 'red', 'age': 42}
>>> [Link]()
dict_keys(['color', 'age'])
>>> list([Link]())
['color', 'age']
[Link] H B 23PLCS21- Introduction to Python Programming
Multiple assignment trick in for loop
• Used to assign the key and value to separate variables .
spam = {'color': 'red', 'age': 42}
for k, v in [Link]():
print('Key: ' + k + ' Value: ' + str(v))
Key: color Value: red
Key: age Value: 42
[Link] H B 23PLCS21- Introduction to Python Programming
Checking Whether a Key or Value Exists in a
Dictionary >>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in [Link]()
True
>>> 'Zophie' in [Link]()
True
>>> 'color' in [Link]()
False
>>> 'color' not in [Link]()
True
>>> 'color' in spam
False
23PLCS21- Introduction to Python Programming [Link] H B
The get() Method
• Used to check whether a key exists in a dictionary before accessing that key’s
value
• Takes two arguments:
The key of the value to retrieve
A fallback value to return if that key does not exist.
23PLCS21- Introduction to Python Programming [Link] H B
Example 1
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'
[Link] H B 23PLCS21- Introduction to Python Programming
Example 2
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str([Link]('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str([Link]('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'
NB: There is no 'eggs' key in the picnicItems dictionary, the default
value 0 is returned by the get() method
[Link] H B 23PLCS21- Introduction to Python Programming
The setdefault() Method
• To set a value in a dictionary for a certain key only if that key does not already have a value
spam = {'name': ‘aa', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'
• The setdefault() method offers a way to do this in one line of code.
>>> spam = {'name': ‘aa', 'age': 5} >>> [Link]('color', 'white')
>>> [Link]('color', 'black') 'black'
'black' >>> spam
>>> spam {'color': 'black', 'age': 5, 'name': ‘aa'}
{'color': 'black', 'age': 5, 'name': ‘aa'}
23PLCS21- Introduction to Python Programming [Link] H B
The first time setdefault() is called,
the dictionary in spam changes to {'color': 'black', 'age': 5, 'name': 'Pooka'}. The
method returns the value 'black' because this is now the value set for the key 'color'.
The second time
[Link]('color', 'white') is called next, the value for that key is not changed
to 'white' because spam already has a key named 'color'.
setdefault() method is a nice shortcut to ensure that a key
exists.
[Link] H B 23PLCS21- Introduction to Python Programming
Example program
message = 'It was a bright cold day in April, and the clocks
were striking thirteen.'
count = {}
for character in message:
[Link](character, 0)
count[character] = count[character] + 1
print(count)
[Link] H B 23PLCS21- Introduction to Python Programming
Example program -2 count = {}
message = ‘ABCA' count = {‘A’:0}
character=a
count = {} count = {‘A’:1}
for character in message:
[Link](character, 0) character=b count = {‘A’:1,B:0}
count[character] = count[character] + 1
count = {‘A’:1,B:1}
print(count)
count = {‘A’:1,’B’:1,’C’:0}
character=c
count = {‘A’:1,’B’:1,’C’:1}
character=a count = {‘A’:2,’B’:1,’C’:1}
[Link] H B 23PLCS21- Introduction to Python Programming
Pretty Printing
• import the pprint module
• the pprint() and pformat() functions that will “pretty print” a dictionary’s values.
• This is helpful when you want a cleaner display of the items in a dictionary than what print()
provides.
23PLCS21- Introduction to Python Programming [Link] H B
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
[Link](character, 0)
count[character] = count[character] + 1
[Link](count)
[Link] H B 23PLCS21- Introduction to Python Programming
Using Data Structures to Model Real-World
Things
• A Tic-Tac-Toe Board
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
23PLCS21- Introduction to Python Programming [Link] H B
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
‘mid-L’:’ ’, mid-M': 'X', 'mid-R': '
',
'low-L': ' ', 'low-M': ' ', 'low-R': '
'}
theBoard = {'top-L': 'O', 'top-M': ‘O', 'top-R': ‘O',
‘mid-L’:’X’, mid-M': 'X', 'mid-R':
' ',
'low-L': ' ', 'low-M': ' ', 'low-R':
‘X'}
23PLCS21- Introduction to Python Programming [Link] H B
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
23PLCS21- Introduction to Python Programming [Link] H B
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which
space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X‘
printBoard(theBoard)
23PLCS21- Introduction to Python Programming [Link] H B
Nested Dictionaries and Lists
• Dictionaries and lists that contain other dictionaries and lists
allGuests = {'Alice': {'apples': 5, ‘orange': 12},
'Bob': {'sandwiches': 3, 'apples': 2},
'Carol': {‘orange': 3, 'apple': 1}}
23PLCS21- Introduction to Python Programming [Link] H B
Working with Strings
• String Literals
• They begin and end with a single quote.
• Typing 'That is Alice's cat.' won’t work, because Python thinks the string ends after
Alice, and the rest (s cat.')
• Double Quotes
• Strings can begin and end with double quotes, just as they do with single quotes.
• >>> spam = "That is Alice's cat."
23PLCS21- Introduction to Python Programming [Link] H B
Module 3
Manipulating Strings
23PLCS21- Introduction to Python Programming [Link] H B
Working
• Escape Characters
with Strings
• An escape character lets you use characters that are otherwise impossible to put
into a string.
• An escape character consists of a backslash (\) followed by the character you want
to add to the string
• spam = 'Say hi to Bob\'s mother.'
Escape character Prints as
\' Single quote
\" Double quote
\t Tab
\n Newline (line break)
\\ Backslash
23PLCS21- Introduction to Python Programming [Link] H B
Working with Strings
• Raw Strings
• If you place an r before the beginning quotation mark of a
string it makes a raw string.
• A raw string completely ignores all escape characters and
prints any backslash that appears in the string.
• >>> print(r 'That is Carol\'s cat.')
That is Carol\'s cat.
23PLCS21- Introduction to Python Programming [Link] H B
Working with Strings
• Multiline Strings with Triple Quotes
• A multiline string in Python begins and ends with either three single quotes or
three double quotes.
• Any quotes, tabs, or newlines in between the “triple quotes” are considered part
of the string.
• Python’s indentation rules for blocks do not apply to lines inside a multiline string.
Print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
23PLCS21- Introduction to Python Programming [Link] H B
Working with Strings
• Multiline Comments
• While the hash character (#) marks the beginning of a comment for the
rest of the line, a multiline string is often used for comments that span
multiple lines.
"""This is a test Python program.
Written by Al Sweigart al@[Link]
This program was designed for Python 3, not Python 2.
"""
def spam():
"""This is a multiline comment to help
explain what the spam() function does."""
print('Hello!')
23PLCS21- Introduction to Python Programming [Link] H B
Working with Strings
• Indexing and Slicing Strings
• Strings use indexes and slices the same way lists do.
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
23PLCS21- Introduction to Python Programming [Link] H B
Working with Strings
• The in and not in Operators with Strings
>>> 'Hello' in 'Hello World'
True
>>> 'Hello' in 'Hello'
True
>>> 'HELLO' in 'Hello World'
False
>>> '' in 'spam'
True
>>> 'cats' not in 'cats and dogs'
False
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• The upper(), lower(), isupper(), and islower() String Methods
• The upper() and lower() string methods return a new string where all the letters in the original string have been converted to
uppercase or lowercase, respectively.
>>> spam = 'Hello world!'
>>> spam = [Link]()
>>> spam
'HELLO WORLD!'
>>> spam = [Link]()
>>> spam
'hello world!'
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• The isupper() and islower() methods will return a Boolean True value if the string has at least one
letter and all the letters are uppercase or lowercase, respectively. Otherwise, the method returns
False.
>>> spam = 'Hello world!'
>>> [Link]()
False
>>> [Link]()
False
>>> 'HELLO'.isupper()
True
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• The isX String Methods
• Like islower() and isupper(), there are several string methods that have names beginning with the
word is.
• isalpha() returns True if the string consists only of letters and is not blank.
• isalnum() returns True if the string consists only of letters and numbers and is not blank.
• isdecimal() returns True if the string consists only of numeric characters and is not blank.
• isspace() returns True if the string consists only of spaces, tabs, and newlines and is not blank.
• istitle() returns True if the string consists only of words that begin with an uppercase letter followed
by only lowercase letters.
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
while True:
print('Enter your age:')
age = input()
if [Link]():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if [Link]():
break
print('Passwords can only have letters and numbers.')
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• The startswith() and endswith() String Methods
• The startswith() and endswith() methods return True if the string value they are called on begins or
ends
>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
>>> 'Hello world!'.startswith('Hello world!')
True
>>> 'Hello world!'.endswith('Hello world!')
True
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• The join() and split() String Methods
• The join() method is useful when you have a list of strings that need to be
joined together into a single string value.
• The split() method does the opposite: It’s called on a string value and returns a
list of strings
>>> ', '.join(['cats', 'rats', 'bats']) >>> 'My name is Reji'.split()
'cats, rats, bats' ['My', 'name', 'is', ‘Reji']
>>> ' '.join(['My', 'name', 'is', ‘Reji']) a=‘Reji Thomas’
'My name is Reji' r=[Link]()
>>> 'ABC'.join(['My', 'name', 'is', ‘Reji']) print(r)
'MyABCnameABCisABCSisReji' [‘Reij’, ‘Thomas’]
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• Justifying Text with rjust(), ljust(), and center()
• The rjust() and ljust() string methods return a padded version of the string they
are called on, with spaces inserted to justify the text.
• The center() string method works like ljust() and rjust() but centers
>>> 'Hello'.rjust(10) >>> 'Hello'.rjust(20, '*')
' Hello' '***************Hello'
>>> 'Hello'.rjust(20) >>> 'Hello'.ljust(20, '-')
‘ Hello' 'Hello---------------’
>>> 'Hello World'.ljust(20) >>>'Hello'.center(20)
‘Hello World ' ‘ Hello '
>>> 'Hello'.ljust(10) >>> 'Hello'.center(20, '=')
'Hello ' '=======Hello========'
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
def printPicnic(itemsDict, leftWidth, rightWidth): ---PICNIC ITEMS--
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-')) sandwiches.. 4
for k, v in [Link](): apples...... 12
print([Link](leftWidth, '.') + str(v).rjust(rightWidth))
cups........ 4
cookies..... 8000
-------PICNIC ITEMS-------
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} sandwiches.......... 4
printPicnic(picnicItems, 12, 5) apples.............. 12
printPicnic(picnicItems, 20, 6) cups................ 4
cookies............. 8000
23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• Removing Whitespace with strip(), rstrip(), and lstrip()
• strip off whitespace characters (space, tab, and newline) from the left side,
right side, or both sides of a string.
• The strip() string method will return a new string without any whitespace
>>> spam =
'SpamSpamBaconSpamEggsSpamSpa
>>> spam = ' Hello World '
m'
>>> [Link]()
>>> [Link](‘mapS')
'Hello World'
'BaconSpamEggs'
>>> [Link]()
'Hello World '
>>> [Link]()
‘ Hello World'23PLCS21- Introduction to Python Programming [Link] H B
Useful String Methods
• Copying and Pasting Strings with the pyperclip Module
• The pyperclip module has copy() and paste() functions that can send text to
and receive text from your computer’s clipboard.
• Sending the output of your program to the clipboard will make it easy to paste
it to an email, word processor, or some other software.
>>> import pyperclip
>>> [Link]('Hello world!')
>>> [Link]()
'Hello world!'
23PLCS21- Introduction to Python Programming [Link] H B
Project: Password Locker
• Step 1: Program Design and Data Structures
• Step 2: Handle Command Line Arguments
• Step 3: Copy the Right Password
23PLCS21- Introduction to Python Programming [Link] H B
Project: Password Locker
#! python3
# [Link] - An insecure password locker program.
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys, pyperclip
if len([Link]) < 2:
print('Usage: py [Link] [account] - copy account password')
[Link]()
account = [Link][1] # first command line arg is the account name
if account in PASSWORDS:
[Link](PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is23PLCS21-
no account named
Introduction ' + account)
to Python Programming [Link] H B
Project: Adding Bullets to Wiki
Markup
• Step 1: Copy and Paste from the Clipboard
• Step 2: Separate the Lines of Text and Add the Star
• Step 3: Join the Modified Lines
23PLCS21- Introduction to Python Programming [Link] H B
Project: Adding Bullets to Wiki
Markup
#! python3
# [Link] - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.
import pyperclip
text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes for "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
[Link](text)
23PLCS21- Introduction to Python Programming [Link] H B
• A A’
[Link] H B 23PLCS21- Introduction to Python Programming
Regular expressions
Regular Expressions, often shortened as regex, are a sequence of
characters used to check whether a pattern exists in a given text
(string) or not
‘Hi every one my contact no. is 444-123-4567’
To find a phone number in a string.
You know the pattern:
Three numbers, a hyphen, three numbers, a hyphen, and four numbers.
Here’s an example:
415-555-4242
+91-9883443344
18CS55 Application Development Using Python [Link] Thomas
18CS55
Finding Patterns of Text Without Regular
Expressions
def isPhoneNumber(text): if text[7] != '-':
if len(text) != 12: return False
return False for i in range(8, 12):
for i in range(0, 3): if not text[i].isdecimal():
if not text[i].isdecimal(): return False
return False return True
if text[3] != '-': print('415-555-4242 is a phone number:')
return False print(isPhoneNumber('415-555-4242'))
for i in range(4, 7): print('Moshi moshi is a phone number:')
if not text[i].isdecimal(): print(isPhoneNumber('Moshi moshi')
return False
415-555-4242 is a phone number:
True
Moshi moshi is a phone number:
18CS55
Finding Patterns of Text Without Regular
Expressions
def isPhoneNumber(text): if text[7] != '-':
if len(text) != 12: return False
return False for i in range(8, 12):
for i in range(0, 3): if not text[i].isdecimal():
if not text[i].isdecimal(): return False
return False return True
if text[3] != '-': message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
return False for i in range(len(message)):
for i in range(4, 7): chunk = message[i:i+12]
if not text[i].isdecimal(): if isPhoneNumber(chunk):
return False print('Phone number found: ' + chunk)
print('Done')
18CS55
Finding Patterns of Text with Regular
Expressions
• The isPhoneNumber() function is 17 lines but can find only one pattern of phone numbers.
• What about a phone number formatted like 415.555.4242 or (415) 555-4242? Or 415-555-4242
x99?
• The isPhoneNumber() function would fail to validate them.
• Regular expressions, called regexes for short, are descriptions for a Pattern of text.
• For example, a \d in a regex stands for a digit character — that is, any single numeral 0 to 9.
The regex \d\d\d-\d\d\d-\d\d\d\d is used.
A string of three numbers, a hyphen, three more numbers, another
hyphen, and four numbers.
A regular expressions can be much more
sophisticated.
[Link] a 3 in curly brackets ({3}) after a pattern is
like saying, “Match this pattern three times.”
regex \d{3}-\d{3}-\d{4}
\d\d\d-\d\d\d-\d\d\d\d
18CS55
Creating Regex Objects
• All the regex functions in Python are in the re module.
>>> import re
>>> phoneNumRegex = [Link](r'\d\d\d-\d\d\d-\d\d\d\d’)
returns a Regex pattern object (or simply, a Regex object).
The syntax involves backslash-escaped characters, and to prevent these
characters from being interpreted as escape sequences; you use the
raw r prefix.
18CS55
Matching Regex Objects
[Link] the regex module with import re.
[Link] a Regex object with the [Link]() function. (use a raw string.)
[Link] the string you want to search into the Regex object’s search() method. This returns a
Match object.
[Link] the Match object’s group() method to return a string of the actual matched text.
• compile function returns a Regex pattern object (or simply, a Regex object).
• search function:- scan through the given string/sequence, looking for the first
location where the regular expression produces a match.
• group function returns the string matched by the re
Example Program
import re
phoneNumRegex = [Link](r'\d\d\d-\d\d\d-\d\d\d\d')
mo = [Link]('My number is 415-555-4242 and 431-444-242.')
print('Phone number found: ' + [Link]())
Output
Phone number found: 415-555-4242
18CS55
More Pattern Matching with Regular
Expressions
• Grouping with Parentheses
>>> phoneNumRegex = [Link](r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
>>> mo = [Link]('My number is 415-555-4242.')
>>> [Link](1)
'415' >>> [Link]()
>>> [Link](2) ('415', '555-4242')
'555-4242' >>> areaCode, mainNumber = [Link]()
>>> [Link](0) >>> print(areaCode)
'415-555-4242' 415
>>> [Link]() >>> print(mainNumber)
'415-555-4242' 555-4242
Adding parentheses will create groups in the regex:
18CS55
More Pattern Matching with Regular
Expressions
• Matching Multiple Groups with the Pipe
• The | character is called a pipe.
• Use it anywhere you want to match one of many expressions.
>>> heroRegex = [Link] (r'Batman|Tina Fey')
>>> mo1 = [Link]('Batman and Tina Fey.')
>>> [Link]()
'Batman'
>>> mo2 = [Link]('Tina Fey and Batman.')
>>> [Link]()
'Tina Fey'
Use the pipe to match one of several patterns as part of your regex.
• >>> batRegex = [Link](r'Bat(man|mobile|copter|bat)')
• >>> mo = [Link]('Batmobile lost a wheel')
• >>> [Link]()
• 'Batmobile'
• >>> [Link](1)
• 'mobile'
[Link]() returns the full matched text 'Batmobile',
[Link](1) returns just the part of the matched text inside the first parentheses
group, 'mobile'
18CS55
More Pattern Matching with Regular
Expressions
• Optional Matching with the Question Mark
• Sometimes there is a pattern that you want to match only optionally.
• That is, the regex should find a match whether or not that bit of text is there.
• The ? character flags the group that precedes it as an optional part of the pattern.
>>> batRegex = [Link](r'Bat(wo)?man')
>>> mo1 = [Link]('The Adventures of Batman')
>>> [Link]()
'Batman'
>>> mo2 = [Link]('The Adventures of Batwoman')
>>> [Link]()
'Batwoman'
>>> phoneRegex = [Link](r'(\d\d\d-)?\d\d\d-\d\d\d\d')
>>> mo1 = [Link]('My number is 415-555-4242')
>>> [Link]()
'415-555-4242‘
>>> mo2 = [Link]('My number is 555-4242')
>>> [Link]()
'555-4242'
18CS55
More Pattern Matching with Regular
Expressions
• Matching Zero or More with the Star
• The * means “match zero or more”—the group that precedes the star can occur any number of times
in the text
• It can be completely absent or repeated over and over again
>>> batRegex = [Link](r'Bat(wo)*man')
>>> mo1 = [Link]('The Adventures of Batman')
>>> [Link]()
'Batman'
>>> mo2 = [Link]('The Adventures of Batwoman')
>>> [Link]()
'Batwoman'
>>> mo3 = [Link]('The Adventures of Batwowowowoman')
>>> [Link]()
'Batwowowowoman'
18CS55
More Pattern Matching with Regular
Expressions
• Matching One or More with the Plus
• The + (or plus) means “match one or more.”
• The group preceding a plus must appear at least once.
• It is not optional.
>>> batRegex = [Link](r'Bat(wo)+man')
>>> mo1 = [Link]('The Adventures of Batwoman')
>>> [Link]()
'Batwoman'
>>> mo2 = [Link]('The Adventures of Batwowowowoman')
>>> [Link]()
'Batwowowowoman‘
>>> mo3 = [Link]('The Adventures of Batman')
>>> mo3 == None
True
18CS55
More Pattern Matching with Regular
Expressions
• Matching Specific Repetitions with Curly Brackets
• If you have a group that you want to repeat a specific number of times,
follow the group in your regex with a number in curly brackets.
• you can specify a range by writing a minimum, a comma, and a maximum
in between the curly brackets.
(Ha){3}
(Ha)(Ha)(Ha)
(Ha){3,5}
((Ha)(Ha)(Ha))|((Ha)(Ha)(Ha)(Ha))|((Ha)(Ha)(Ha)(Ha)(Ha))
18CS55
More Pattern Matching with Regular
Expressions
• Matching Specific Repetitions with Curly Brackets
>>> haRegex = [Link](r'(Ha){3}')
>>> mo1 = [Link]('HaHaHa')
>>> [Link]()
'HaHaHa'
>>> mo2 = [Link]('Ha')
>>> mo2 == None
True