0% found this document useful (0 votes)
2 views73 pages

20214254 Python Module 2

The document covers various aspects of strings in Python, including accessing characters, slicing, and using string methods. It also discusses data encryption techniques such as the Caesar cipher and provides insights into number systems like binary, octal, and hexadecimal. Additionally, it explains file operations in Python, including reading from and writing to text files, along with examples and problems for practice.

Uploaded by

jocktmpx4oxc
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)
2 views73 pages

20214254 Python Module 2

The document covers various aspects of strings in Python, including accessing characters, slicing, and using string methods. It also discusses data encryption techniques such as the Caesar cipher and provides insights into number systems like binary, octal, and hexadecimal. Additionally, it explains file operations in Python, including reading from and writing to text files, along with examples and problems for practice.

Uploaded by

jocktmpx4oxc
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
You are on page 1/ 73

Date: 06/03/2023

Monday

MODULE II

Strings

* Much about computation is concerned with manipulating text.

Accessing Characters and Substrings in Strings

* A string is a data structure.

* A string is a sequence of zero or more characters.

* A Python string can be represented using either single quote marks or


double quote marks. String Examples:

* A string’s length is the number of characters it contains.

- Python’s len function returns this value when it is passed a string.

* The positions of a string’s characters are numbered from 0, on the left,


to the length of the string minus 1, on the right.
* The string is an immutable data structure.

- This means that its internal data elements, the characters, can be
accessed, but cannot be replaced, inserted, or removed.

The Subscript Operator

* Subscript opertaor is used to inspect one character at a given position in


a string without visiting all the characters in it.

* Syntax:

<a string>[<an integer expression>]

- The first part of this operation is the string you want to inspect.

- The integer expression in brackets indicates the position of a particular


character in that string. The integer expression is also called an index.

* Attempting to access a character using a position that equals the string’s


length results in an error.
* The positions usually range from 0 to the length minus 1

* Illustration: Code segment to display the characters in a string and their


positions

* Python allows negative subscript values to access characters at or near


the end of a string. The programmer counts backward from –1 to access
characters from the right end of the string.

Q:WAP to dispaly reverse of a given string.

Slicing for Substrings

* Portions of strings called substrings

* Python’s subscript operator can obtain a substring through a process


called Slicing

- To extract a substring, the programmer places a colon ( : ) in the


subscript. An integer value can appear on either side of the colon.

* Generally, when two integer positions are included in the slice, the range
of characters in the substring extends from the first position up to but not
including the second position.

* But, when the integer is omitted on either side of the colon, all of the
characters extending to the end or the beginning are included in the
substring.
Q: WAP to print the filenames with .txt extension from the following list
(use slicing) :

The for statement to iterate in this list is:

Write the remaining code.

Testing for a Substring with the in Operator

* To pick out strings that contain known substrings, we can use Python’s
in operator

- When used with strings, the left operand of in is a target substring, and
the right operand is the string to be searched.

- The operator in returns True if the target string is somewhere in the


search string, or False otherwise.

Q: Code that traverses a list of filenames and prints just the filenames that
have a .txt extension using in operator
Problems

1. Assume that the variable data refers to the string "myprogram.exe" .


Write the values of the following expressions:
a. data[2]
b. data[-1]
c. len(data)
d. data[0:8]
2. Assume that the variable myString refers to a string. Write a code
segment that uses a loop to print the characters of the string in reverse
order.

Data Encryption

* Data traveling on the Internet is vulnerable to spies and potential


thieves.

- wireless transmission

- sniffing softwares

* Most applications now use data encryption to protect information


transmitted on networks.

* Encryption technique

- The sender encrypts a message by translating it to a secret code, called a


cipher text .

- At the other end, the receiver decrypts the cipher text back to its original
plaintext form.
- Both parties to this transaction must have at their disposal one or more
keys that allow them to encrypt and decrypt messages.

* A very simple encryption method that has been in use for thousands of
years is called a Caesar cipher .

Encryption strategy: Replace each character in the plaintext with the


character that occurs a given distance away in the sequence.

For positive distances, the method wraps around to the beginning of


the sequence to locate the replacement characters for those characters near
its end.

Example: For example, if the distance value of a Caesar cipher equals


three characters, the string "invaders" would be encrypted as
"lqydghuv" .

- To decrypt this cipher text back to plaintext, you apply a method that uses
the same distance value but looks to the left of each character for its
replacement.

This decryption method wraps around to the end of the sequence to


find a replacement character for one near its beginning.

* Illustartion
- The next two Python scripts implement Caesar cipher methods for any
strings that contain the lowercase letters of the alphabet and for any
distance values between 0 and 26.
Problems

1. Write the encrypted text of each of the following words using a Caesar
cipher with a distance value of 3:
a. python
b. hacker
c. wow
13/03/2023
Monday

Strings and Number Systems

* When you perform arithmetic operations, you use the decimal number
system .

- This system, also called the base ten number system, uses the ten
characters 0, 1, 2, 3, 4, 5, 6, 7,8, and 9 as digits.

* The binary number system is used to represent all information in a


digital computer.

- The two digits in this base two number system are 0 and 1.

* Because binary numbers can be long strings of 0s and 1s, computer


scientists often use other number systems, such as octal (base eight) and
hexadecimal (base 16) as short hand for these numbers.

* To identify the system being used, you attach the base as a subscript to
the number.

- For example, the following numbers represent the quantity 41510 in the
binary, octal, decimal, and hexadecimal systems:

* The digits used in each system are counted from 0 to n – 1, where n is


the system’s base.
- To represent digits with values larger than 9 10 , systems such as base 16
use letters.

The Positional System for Representing Numbers

* All of the number systems we have examined use positional notation:

=> the value of each digit in a number is determined by the digit’s


position, in the number.

* Each digit has a positional value .

- The positional value of a digit is determined by raising the base of the


system to the power specified by the position ( baseposition ) .

- For an n-digit number, the positions (and exponents) are numbered from
n – 1 down to 0, starting with the leftmost digit and moving to the right.

Eg: The positional values of the three-digit number 41510 are 100 (102 ) ,
10 (101), and 1 (100), moving from left to right in the number.

- To determine the quantity represented by a number in any system from


base 2 through base 10, you multiply each digit (as a decimal number) by
its positional value and add the results.
1.Converting Binary to Decimal

* Like the decimal system, the binary system also uses positional notation.

- Each digit or bit in a binary number has a positional value that is a power
of 2.

- To determine the integer quantity that a string of bits represents, multiply


the value of each bit (0 or 1) by its positional value and add the results.

Eg:

- In computing the value of a binary number, we can ignore the values of


the positions occupied by 0s and simply add the positional values of the
positions occupied by 1s.

* How to code an algorithm for the conversion of a binary number to


the equivalent decimal number as a Python script?

- The input to the script is a string of bits, and its output is the
integer that the string represents.
2. Converting Decimal to Binary

* The algorithm repeatedly divides the decimal number by 2.

- After each division, the remainder (either a 0 or a 1) is placed at the


beginning of a string of bits.

- The quotient becomes the next dividend in the process.

- The string of bits is initially empty, and the process continues while the
decimal number is greater than 0.
Octal Number System

* The octal system uses a base of eight and the digits 0 . . . 7.


* To convert from octal to binary, you start by assuming that each digit in
the octal number represents three digits in the corresponding binary
number.

- You then start with the leftmost octal digit and write down the
corresponding binary digits, padding these to the left with 0s to the count
of 3, if necessary.

-You proceed in this manner until you have converted all of the octal
digits.

Hexadecimal Number System

*The hexadecimal or base-16 system (called “hex” for short), uses 16


different digits.

* It uses the digits 0 . . . 9 and and the letters A . . . F

* To convert from hexadecimal to binary, you replace each hexadecimal


digit with the corresponding 4-bit binary number.

* To convert from binary to hexadecimal, you factor the bits into groups
of four and look up the corresponding hex digits.
String Methods

* Text processing involves many different operations on strings.


* Python includes a set of string operations called methods

Ex: split() can be used to obtain the list of the words contained in an
input string.

Illustration Scenario - Analyze someone’s writing style:


WAP to obtain a list of the words contained in an input string. Compute
and print the average of the lengths of the words in the list.

* Syntax of method

- A method behaves like a function but has a slightly different syntax.

- Unlike a function, a method is always called with a given data value


(called an object) , which is placed before the method name in the call.

<an object>.<method name>(<argument-1>,..., <argument-n>)

- Methods can also expect arguments and return values

- A method knows about the internal state of the object with which it is
called.

* In Python, all data values are in fact objects, and every data type
includes a set of methods to use with objects of that type.
* To view the complete list and the documentation of the string methods
enter dir(str) at a shell prompt.
* Now to extract a filename’s extension, we use the expression:

>>>filename.split('.')[-1]
Problems

1. Assume that the variable data refers to the string "Python rules!" . Use a
string method to perform the following tasks:

a. Obtain a list of the words in the string.

b. Convert the string to uppercase.

c. Locate the position of the string "rules" .

d. Replace the exclamation point with a question mark.

2. Using the value of data from Problem 1, write the values of the
following expressions:

a. data.endswith('i')

b. " totally ".join(data.split())


14/03/23
Tuesday

Text Files

* A text file is a software object that stores data on a permanent medium


such as a disk, CD, or flash memory.

* When compared to keyboard input from a human user, the main advan-
tages of taking input data from a file are the following:

- The data set can be much larger.

- The data can be input much more quickly and with less chance of error.

- The data can be used repeatedly with the same program or with different
programs.

Text Files and Their Format

* Using a text editor such as Notepad or TextEdit, you can create, view,
and save data in a text file

* All data output to or input from a text file must be strings.

- Thus, numbers must be converted to strings before output, and these


strings must be converted back to numbers after input.

* The data in a text file can be viewed as characters, words, numbers, or


lines of text, depending on the text file’s format and on the purposes for
which the data are used.

- When the data are numbers (either integers or floats), they must be
separated by whitespace characters—spaces, tabs, and newlines—in the
file.
1. Writing Text to a File

* It requires 3 steps: Open the file, Write text to it, and Close the file.

1. Python’s open function, opens a connection to the file on disk and


returns a file object.

Syntax:

f = open( filename, mode string )

- It has two arguments, a file name and a mode string.

Eg: f = open("myfile.txt", 'w')

- The mode string is 'r' for input files and 'w' for output files

- If the file does not exist, it is created with the given filename.

- If the file already exists, Python opens it. When an existing file is opened
for output, any data already in it are erased.

2. String data are written to a file using the method write() with the file
object.

- The write method expects a single string argument

eg: f.write("First line.\nSecond line.\n")

3. When finished with writing, the file should be closed using the method
close(). Failure to close an output file can result in data being lost.

f.close()
2.Writing Numbers to a File

* The file method write() expects a string as an argument.

- Therefore, other types of data, such as integers or floating-point


numbers, must first be converted to strings before being written to an
output file.

* In Python, the values of most data types can be converted to strings, by


using the str() function.

* Illustration:
Q: WAP to generate and write Five hundred random integers between 1
and 500 to a text file named integers.txt

1. Reading Text from a File

* Open the file

- You open a file for input (reading) using the same open command used
for file writing. The only difference is that the mode string is 'r' .

f = open("myfile.txt", 'r')

* Read the filename

Method 1: The simplest way to read a input from a file is to use the file
method read().
- It reads the entire contents of the file as a single string. If the file contains
multiple lines of text, the newline characters will be embedded in this
string.

* It is not necessary to close the file.

Method 2: An application might read and process the text one line at a
time.

Method 3: In cases where you might want to read a specified number of


lines from a file (say, the first line only), you can use the file method
readline().

- The readline method consumes a line of input and returns this string,
including the newline.

- If readline encounters the end of the file, it returns the empty string.
2. Reading Numbers from a File

* All the file input operations return data to the program as strings.

- If these strings represent other types of data, such as integers or


floating-point numbers, the programmer must convert them to the
appropriate types before manipulating them further.

- String representations of integers and floating-point numbers can be


converted to the numbers themselves by using the functions int and float

* Illustration

Q: Open a file of random integers written earlier, read the numbers, and
print their sum.
- Here string method strip is used to remove the newline and then the int
function is used to obtain the integer value.

* How to obtain numbers from a text file in which they are separated by
spaces ?

- Here start by reading lines in a for loop. But each line now can contain
several integers separated by spaces.
- Use split() to obtain a list of the strings representing these integers, and
then process each string in this list with another for loop.

Major File Operations


Accessing and Manipulating Files and Directories on Disk

* The file system of a computer allows you to create folders or directories,


within which you can organize files and other directories.

* The complete set of directories and files forms a tree-like structure, with
a single root directory at the top and branches down to nested files and
subdirectories.

* When you launch Python, either from the terminal or from IDLE, the
shell is connected to a current working directory.

- At any point during the execution of a program, you can open a file in
this directory just by using the file’s name.

* You can also access any other file or directory within the computer’s file
system by using a pathname .
- A file’s pathname specifies the chain of directories needed to access a file
or directory.
Absolute pathname

* When the chain starts with the root directory, it’s called an absolute
pathname . The root directory is the leftmost name and the target
directory or file name is the rightmost name.

- The '/' character must begin an absolute pathname on Unix-based


systems.

- A disk drive letter must begin an absolute pathname on Windows-


based systems

- To open myfile.txt in child directory from the current directry using


absolute path name:

f = open("/Users/lambertk/parent/current/child/myfile.txt", 'r')

Relative pathname

* When the chain starts from the current working directory, it’s called a
relative pathname .

- Here, Pathnames to files in directories below the current working


directory begin with a subdirectory name and are completed with names
and separator symbols on the way to the target filename.

- Paths to items in the other parts of the file system require you to specify a
move “up” to one or more ancestor directories, by using the .. symbol
between the separators.

- To open the files named myfile.txt in the child, parent, and sibling
directories, where current is the current working directory, you could use
relative pathnames as follows:
Error checking with file operations

* Before attempting to open a file for input, the programmer should


check to see if a file with the given pathname exists on the disk.

* Following table gives some file system functions, that supports this
checking.
Problems

1. Write a code segment that opens a file named myfile.txt for input and
prints the number of lines in the file.

2. Write a code segment that opens a file for input and prints the number of
four-letter words in the file.

3. Assume that a file contains integers separated by newlines. Write a code


segment that opens the file and prints the average value of the integers.

4. Write a code segment that prints the names of all of the items in the
current working directory.

5. Write a code segment that prompts the user for a filename. If the file
exists, the program should print its contents on the terminal. Otherwise, it
should print an error message.
Lists

* Data Structure: A data structure combines several data values into


a unit so that they can be treated as one thing.

- The data elements within a data structure are usually organized in a


special way that allows the programmer to access and manipulate
them.

Eg: String - string is a data structure that organizes text as a sequence


of characters.

*List: List is a data structure that allows the programmer to manipulate a


sequence of data values of any types.

- A list is a sequence of data values called items or elements . An item can


be of any type.

* Some real-world examples of lists:

- A shopping list for the grocery store


- A to-do list
- A guest list for a wedding
- A recipe, which is a list of instructions
- A text document, which is a list of lines
- The names in a phone book

* Each of the items in a list is ordered by position.

- Like a character in a string, each item in a list has a unique index that
specifies its position.

- The index of the first item is 0, and the index of the last item is the length
of the list minus 1.
List Literals and Basic Operators

* A list literal is written as a sequence of data values separated by


commas. The entire sequence is enclosed in square brackets, [ ] .

eg: [1951, 1969, 1984] # A list of integers


["apples", "oranges", "cherries"] # A list of strings
[] # An empty list

* You can also use other lists as elements in a list, thereby creating a list of
lists.

[[5, 9], [541, 78]]

* When the Python interpreter evaluates a list literal, each of the elements
in it are evaluated.

ie, [] delimiters evaluates its arguments before using their values.

* You can build lists of integers using the range and list functions.
- A list function can build a list from any iterable sequence of elements,
such as a string.

* The function len and the subscript operator [] work on lists, just as they
do for strings.

* Concatenation ( + ) and equality ( == ) also work as on lists

* The print function does not alter the look of a list.

* To print the contents of a list without the brackets and commas, you can
use a for loop.
* You can use the in operator to detect the presence or absence of a given
element.
15/03/23
Wednesday

Replacing an Element in a List

* List is mutable
=> A list is changeable—that is, it is mutable. At any point in a list’s
lifetime, elements can be inserted, removed, or replaced.
-The list itself maintains its identity but its internal state—its length
and its contents—can change.

* String is an immutable data structure .


=> This means that its internal data elements, the characters, can be
accessed, but cannot be replaced, inserted, or removed.

* The subscript operator is used to replace an element at a given position:

Illustration 1: Replace each number in a list with its square

- Here, the code uses a for loop over an index rather than a for loop over
the list elements, because the index is needed to access the positions for
the replacements.
Illustration 2: Extract a list of the words in a sentence and then convert
them to uppercase letters.

List Methods for Inserting and Removing Elements

* The list type includes several methods for inserting and removing
elements.

* Illustration
* Differnces in the use of insert, append and extend.

- The method insert expects an integer index and the new element as
arguments

- The method append expects just the new element as an argument and
adds the new element to the end of the list

- The method extend adds the elements of its list argument to the end of
the list.

Note that the + operator builds and returns a brand new list containing the
elements of the two operands, whereas append and extend modify the list
object on which the methods are called.

* The method pop is used to remove an element at a given position.

- If the position is not specified, pop removes and returns the last element.
- If the position is specified, pop removes the element at that position and
returns it.
- The method pop and the subscript operator expect the index argument to
be within the range of positions currently in the list. If that is not the case,
Python raises an exception.

Searching a List

* How to search for a given element in a list?

- List type does not include the convenient find method that is used with
strings. Find returns either the index of the given substring in a string
or –1 if the substring is not found.

1. Use in operator to determine an element’s presence or absence in the list

2. Then use the method index to locate an element’s position in a list

Note: Index raises an exception when the target element is not found.
To guard against this unpleasant consequence, you must first use
the in operator to test for presence and then the index method if this test
returns True .
Sorting a List

* You can arrange elements in the list in numeric or alphabetical order.

* The list method sort mutates a list (changes) a list by arranging its
elements in ascending order.

Mutator Methods and the Value None

* Mutable objects (such as lists) have some methods devoted entirely to


modifying the internal state of the object. Such methods are called
mutators.

Eg: list methods insert , append , extend , pop , and sort .

- a mutator method usually returns no value of interest to the caller; it does


only a change of state in the list.

- Python nevertheless automatically returns the special value None even


when a method does not explicitly return a value.

>>> aList = aList.sort()


>>> print(aList)
None

Note: After the list object is sorted, this assignment has the result of setting
the variable aList to the value None . The next print statement shows that
the reference to the list object is lost.
Aliasing and Side Effects

* Here the list second is created by assignment of first list

- But after the assignment second = first , the variables first and second
refer to the exact same list object. They becomes aliases for the same
object. This type of change is known as a side effect .

* To prevent aliasing, you can create a new object and copy the contents of
the original to it.
* A simpler way to copy a list is, to pass the source list to a call of the list()
function:

>>> third = list(first)

Equality: Object Identity and Structural Equivalence

* To check whether two variables refer to the exact same object or to


different objects we have two operators:

1. == operator : It returns True if the variables are aliases for the same
object.((object identity))
Unfortunately, == also returns True if the contents of two different
objects are the same.(structural equivalence)
2. is operator: Python’s is operator can be used to test for object identity.
It returns True if the two operands refer to the exact same object, and it
returns False if the operands refer to distinct objects (even if they are
structurally equivalent).

Taking Input of a Python List


* We can take the input of a list of elements as string, integer, float, etc.
listString = input("Enter elements (Space-Separated): ")
lst = listString.split()
print('The list is:', lst)
Slicing of a List

We can get substrings and sublists using a slice.


* To print elements from beginning to a range use: [: Index]
* To print elements from end-use: [:-Index]
* To print elements from a specific Index till the end use : [Index:]
* To print the whole list in reverse order, use : [::-1]
List Comprehension

* Python List comprehensions are used for creating new lists from other iterables like tuples,
strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which
is executed for each element along with the for loop to iterate over each element.

Output: [1, 9, 25, 49, 81]


This is same as:

Problems

1. Write a Python program to get the largest number from a list.

2.Write a Python program to sum all the items in a list.

3. Write a Python program to get the frequency of elements in a list

4. WAP to read aset of numbers from a text file and prints their median.

5. Assume that the variable data refers to the list [5, 3, 7] . Write the values
of the
following expressions:
a. data[2]
b. data[-1]
c. len(data)
d. data[0:2]
e. 0 in data
f. data + [2, 10, 5]
g. tuple(data)
22/03/23
Wednesday
List Comprhesion (Contd)
List comprehension in Python is an easy and compact syntax for creating a
list from a string or another list.

* The list comprehension syntax contains three parts:


1. an expression,
2. one or more for loop, and optionally,
3. one or more if conditions.

* The list comprehension must be in the square brackets [].

* The result of the first expression will be stored in the new list. The for
loop is used to iterate over the iterable object that optionally includes the if
condition.

* List comprehension works with string lists also.


Tuples

* A tuple is a type of sequence that resembles a list, but a tuple is


immutable.

- anytime you foresee using a list whose structure will not change, you
can, and should, use a tuple instead.

* Tuple is indicated in Python by enclosing its elements in parentheses


instead of square brackets.

* Most of the operators and functions used with lists also apply to tuples.

* You must be careful when using a tuple of one element. In that case, you
place a comma after the expression within the parentheses.
Dictionaries

* A dictionary organizes information by association, not position.

- A dictionary associates a set of keys with values.

Dictionary Literals

* A Python dictionary is written as a sequence of key/value pairs


separated by commas.

- These pairs are sometimes called entries.

- The entire sequence of entries is enclosed in curly braces ( { and } ).

- A colon ( : ) separates a key and its value.

-The keys in a dictionary can be data of any immutable types, including


tuples, although keys normally are strings or integers.

- The associated values can be of any types.

- Example :

* You can even create an empty dictionary—that is, a dictionary that


contains no entries.

{}
Adding Keys and Replacing Values

* You add a new key/value pair to a dictionary by using the subscript


operator [] .

* The subscript is also used to replace a value at an existing key

Accessing Values

* Subscript operator can be used to obtain the value associated with a


key.

- if the key is not present in the dictionary, Python raises an exception


* If the existence of a key is uncertain, the programmer can test for it using
the operator in

* Another way to test for the existence and then access a key is through the
method get .
- This method expects two arguments, a possible key and a default value.
- If the key is in the dictionary, the associated value is returned.
- However, if the key is absent, the default value passed to get is returned.

Removing Keys

* To delete an entry from a dictionary, one removes its key using the
method pop .

- This method expects a key and an optional default value as arguments.

- If the key is in the dictionary, it is removed, and its associated value is


returned. Otherwise, the default value is returned.

* If pop is used with just one argument, and this key is absent from the
dictionary, Python raises an exception.
Traversing a Dictionary

* When a for loop is used with a dictionary, the loop’s variable is bound
to each key in an unspecified order.

- Illustration: Code segment prints all of the keys and their values in the
info dictionary

- Alternatively, you could use the dictionary method items() to access the
dictionary’s entries.

Note: Here the entries are represented as tuples within the list

- A tuple of variables can then access the key and value of each entry in
this list within a for loop
- On each pass through the loop, the variables key and value within
the tuple are assigned the key and value of the current entry in the list.

* If a special ordering of the keys is needed, you can obtain a list of keys
using the keys method and process this list to rearrange the keys

* To see the complete documentation for dictionaries, you can run


help(dict) at a shell prompt
* Illustration: Convert a hexadecimal number to a binary number.

- The algorithm visits each digit in the hexadecimal number, selects the
corresponding four bits that represent that digit in binary, and adds
these bits to a result string.

- If you maintain the set of associations between hexadecimal digits and


binary digits in a dictionary, then you can just look up each hexadecimal
digit’s binary equivalent with a subscript operation. Such a dictionary is
sometimes called a lookup table
- The function convert expects two parameters: a string representing the
number to be converted and a table of associations of digits. The function
uses the associations in the table to perform the conversion.

Problems

1. Assume that the variable data refers to the dictionary {'b':20, 'a':35} .
Write the values of the following expressions:

a. data['a']
b. data.get('c', None)
c. len(data)
d. data.keys()
e. data.values()
f. data.pop('b')
g. data # After the pop above

3. Assume that the variable data refers to the dictionary {'b':20, 'a':35} .
Write the expressions that perform the following tasks:
a. Replace the value at the key 'b' in data with that value’s negation.
b. Add the key/value pair 'c':40 to data .
c. Remove the value at key 'b' in data , safely.
d. Print the keys in data in alphabetical order.
27/03/2023
Monday

Design with Functions

* Defining Simple Functions

- Thus far, our programs have consisted of short code segments or scripts.
Some of these have used built-in functions to do useful work.

- Defining our own functions allows us to organize our code in existing


scripts more effectively.

- Our scripts can be made useful, if we package them as functions and use
them in other needed scripts.

The Syntax of Simple Function Definitions

* The definition of this function consists of a header and a body

Header

- The header includes the keyword def as well as the function name and
list of parameters.

- A parameter is the name used in the function definition for an argument


that is passed to the function when it is called.

- The number and positions of the arguments of a function call should


match the number and positions of the parameters in that function’s
definition.
Some functions expect no arguments, so they are defined with no
parameters.

Function Body

- The function’s body contains one or more statements.


The function’s body contains the statements that execute when the
function is called.

Return Statement

- The programmer places a return statement at each exit point of a function


when that function should explicitly return a value.
Syntax: return <expression>

- Upon encountering a return statement, Python evaluates the expression


and immediately transfers control back to the caller of the function.

- The value of the expression is also sent back to the caller.

- If a function contains no return statement, Python transfers control to the


caller after the last statement in the function’s body is executed, and the
special value None is automatically returned.

Illustration 1: Write a function that computes the square of a number.

Illustration 2: Write a function that computes the average value in a list of


numbers.
Defining a main Function

* In scripts that include the definitions of several cooperating functions, it


is useful to define a special function named main that serves as the entry
point for the script.

- This function usually expects no arguments and returns no value.

- The definition of the main function and the other function definitions
may appear in any order in the script, as long as main is called at the very
end of the script.

When Python loads the module, the code for all the function definitions
are loaded and compiled, but not executed.

Main is then called within an if statement as the last step in the script.

* Illustration: Calculate the square of a number


- When the script is launched from IDLE or a terminal prompt, the value of
the module variable __name __ will be "__main__" . In that case, the main
function is called and the script runs as a standalone program.

- This mechanism aids in testing, as the script can be run repeatedly in the
shell by calling main() , rather than reloading it from the editor’s window.

* Role of function in Software system Design

- In designing a system, we organize the structure of a system and


coordinate the actors within it to achieve its purpose.

- A function packages an algorithm in a chunk of code that you can call by


name.
* Important points to remember about function

- A function can be called from anywhere in a program’s code, including


code within other functions.

- During program execution, there may be a complex chain of function


calls, where one function calls another and waits for its results to be
returned, and so on.

- A function can receive data from its caller via arguments.

- When a function is called, any expressions supplied as arguments are


first evaluated. Their values are copied to temporary storage locations
named by the parameters in the function’s definition.

- A function may have one or more return statements, whose purpose is to


terminate the execution of the function and return control to its caller.

- A return statement may be followed by an expression. In that case,


Python evaluates the expression and makes its value available to the caller
when the function stops execution.

Functions as Abstraction Mechanisms

* Functions are not necessary


=> It is possible to construct any algorithm using only Python’s
built-in operators and control statements (without using fuctions). But the
resulting code would be extremely complex, difficult to prove correct, and
almost impossible to maintain.

* People cope with complexity by developing a mechanism to simplify or


hide it.

* An abstraction hides detail and thus allows a person to view many things
as just one thing.
* Effective designers must invent useful abstractions to control
complexity.

1. Functions Eliminate Redundancy

* The first way that functions serve as abstraction mechanisms is by


eliminating redundant, or repetitious, code.

* Illustration: Program to do summation, that returns the sum of the


numbers within a given range of numbers

* If the summation function didn’t exist, the programmer would have to


write the entire algorithm every time a summation is computed.

- In a program that must calculate multiple summations, the same code


would appear multiple times. In other words, redundant code would be
included in the program.

=> it requires the programmer to laboriously enter or copy the same code
over and over, and to get it correct every time.

Then, if the programmer decides to improve the algorithm by adding a


new feature or making it more efficient, he or she must revise each
instance of the redundant code throughout the entire program.
* Any other module or program can import the function for its use.

- Once imported, the function can be called as many times as necessary.

- When the programmer needs to debug, repair, or improve the function,


she needs to edit and test only the single function definition.

2. Functions Hide Complexity

* Functions hide complicated details and logic.

- If the code for the summation is placed in a context of code that is even
slightly complex, the increase in complexity might be enough to result in
conceptual overload for the poor programmers.

3. Functions Support General Methods with Systematic Variations

* An algorithm is a general method for solving a class of problems

- If designed properly, a function’s code captures an algorithm as a general


method for solving a class of problems.

- The function’s arguments provide the means for systematically varying


the problem instances that its algorithm solves.

- The individual problems that make up a class of problems are known as


problem instances .

- The problem instances are the data sent as arguments to the function.
The problem instances for our summation algorithm are the pairs of
numbers that specify the lower and upper bounds of the range of numbers
to be summed.

* When you design an algorithm, it should be general enough to provide a


solution to many problem instances, not just one or a few of them.

=>In other words, a function should provide a general method with


systematic variations.
* Additional arguments can broaden the range of problems that are
solvable.
For example, the summation function could take a third argument that
specifies the step to take between numbers in the range.

4. Functions Support the Division of Labor

* In a computer program, functions can enforce a division of labor.

- Ideally, each function performs a single coherent task, such as computing


a summation or formatting a table of data for output.

- Each function is responsible for using certain data, computing certain


results, and returning these to the parts of the program that requested them.

- Each of the tasks required by a system can be assigned to a function,


including the tasks of managing or coordinating the use of other functions.

Problem Solving with Top-Down Design

* One popular design strategy for solving programs of any significant size
and complexity is called top-down design .

- This strategy starts with a global view of the entire problem and breaks
the problem into smaller, more manageable subproblems—a process
known as problem decomposition .

- As each subproblem is isolated, its solution is assigned to a function.


Problem decomposition may continue down to lower levels, because a
subproblem might in turn contain two or more lower-level problems
to solve.

-As functions are developed to solve each subproblem, the solution to the
overall problem is gradually filled out in detail. This process is also called
stepwise refinement .
* A structure chart is a diagram that shows the relationships among a
program’s functions and the passage of data between them.

- Each box in the structure chart is labeled with a function name.

- The main function at the top is where the design begins, and
decomposition leads us to the lower-level functions on which main
depends.

- The lines connecting the boxes are labeled with data type names, and
arrows indicate the flow of data between them

Illustration: Flesch Index is a measure of text readability. This index is


based on
the average number of syllables per word and the average number of
words per sentence in a piece of text. Index scores usually range from 0 to
100, and they indicate readable prose for the following grade levels:

you have to develop a program that computes the Flesch Index for a text
file.

Q: Write a program that computes the Flesch Index and grade level for text
stored in a text file.
The first and last tasks require no design.
Problems
1. Write a Python function to find the Max of three numbers
2. Write a Python function to sum all the numbers in a list
3. Write a Python function to calculate the factorial of a number (a non-
negative integer). The function accepts the number as an argument

Design with Recursive Functions

* In top-down design, we decompose a complex problem into a set of


simpler problems and solve these with different functions.

In some cases, you can decompose a complex problem into smaller


problems of the same form.
=> The subproblems can all be solved by using the same function. This
design strategy is called recursive design, and the resulting functions are
called recursive functions.

Defining a Recursive Function

* A recursive function is a function that calls itself.

* To prevent a function from repeating itself indefinitely, it must contain at


least one selection statement.

- This statement examines a condition called a base case to determine


whether to stop or to continue with another recursive step

Illustration : Print the numbers from a lower bound to an upper bound

* The equivalent recursive function

* Most recursive functions expect at least one argument.

- This data value is used to test for the base case that ends the recursive
process, and it is modified in some way before each recursive step.

The modification of the data value should produce a new data value that
allows the function to reach the base case eventually.

Eg:lower
Illustration 2: Compute and returns the sum of the numbers between a
lower and upper values.

- In the recursive version, summation returns 0 if lower exceeds upper (the


base case).

Otherwise, the function adds lower to the summation of lower + 1 and


upper and returns this result

Tracing a Recursive Function

* To get a better understanding of how a recursive function works, it is


helpful to trace its calls.
Using Recursive Definitions to Construct Recursive Functions

* Recursive functions are frequently used to design algorithms for


computing values that have a recursive definition.

- A recursive definition consists of equations that state what


a value is for one or more base cases and one or more recursive cases.

Fibonacci sequence is a series of values with a recursive definition.: 1 1 2


3 5 8 13 . . .
Infinite Recursion

* One design error that might trip up a programmer and the function can
(theoretically) continue executing forever, a situation known as infinite
recursion.

- Infinite recursion arises when the programmer fails to specify the base
case or to reduce the size of the problem in a way that terminates the
recursive process.
The Costs and Benefits of Recursion
* At program startup, the PVM reserves an area of memory named a call
stack. For each call of a function, recursive or otherwise, the PVM must
allocate on the call stack a small chunk of memory called a stack frame.

Problems
1.The factorial of a positive integer n , fact(n) , is defined recursively as
follows:
Define a recursive function fact that returns the factorial of a
given positive integer.

2. Explain what happens when the following recursive function is called


with the value 4 as an argument:

Managing a Program’s Namespace


* For a computer, a variable name means the value to which it happens to
refer at any given point in program execution.

* The computer can keep track of these values easily. But a programmer
charged with editing and maintaining code can occasionally get lost as a
program gets larger and more complex.

* A program’s namespace is the set of variables and their values in it.

* Variable names mainly fall into four categories, depending on where they
are introduced:

1.Module variables.
* Importing a module and entering dir(doctor) at a shell prompt to see
module variables in it. When module variables are introduced in a
program, they are immediately given a value

* A module is a file containing Python definitions and statements. The file


name is the module name with the suffix .py appended.

Definitions from a module can be imported into other modules or into


the main module
Within a module, the module’s name (as a string) is available as the
value of the global variable __name__.
2. Parameters : A parameter name behaves like a variable and is
introduced in a function or method header. The parameter does not receive
a value until the function is called.
3. Temporary variables: Variables introduced in the body of the function
4. Method names: The names split and join are introduced or defined in
the str type. A method reference always uses an object, in this case, a
string, followed by a dot and the method name.
Scope

* In a program, the context that gives a name a meaning is called its


scope . In Python, a name’s scope is the area of program text in which the
nam changePerson e refers to a given value

* Illustration with doctor.py

1.The meanings of temporary variables are restricted to the body of the


functions in which they are introduced, and they are invisible elsewhere in
a module.
The scope of the temporary variables words , replyWords , and word is
the area of code in the body of the function , just below where each
variable is introduced.

2. The scope of the parameter sentence is the entire body of the function
changePerson . Like temporary variables, parameters are invisible outside
the function definitions where they are introduced.

3. The scope of the module variables replacements and changePerson


includes the entire module below the point where the variables are
introduced.
This includes the code nested in the body of the function changePerson .
The scope of these variables also includes the nested bodies of other
function definitions that occur earlier

Lifetime

* A variable’s lifetime is the period of time during program execution


when the variable has memory storage associated with it.

When a variable comes into existence, storage is allocated for it; when it
goes out of existence, storage is reclaimed by the PVM.

-Module variables come into existence when they are introduced via
assignment and generally exist for the lifetime of the program that
introduces or imports those module variables.
-Parameters and temporary variables come into existence when they are
bound to values during a function call but go out of existence when the
function call terminates.

You might also like