20214254 Python Module 2
20214254 Python Module 2
Monday
MODULE II
Strings
- This means that its internal data elements, the characters, can be
accessed, but cannot be replaced, inserted, or removed.
* Syntax:
- The first part of this operation is the string you want to inspect.
* 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) :
* 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.
Q: Code that traverses a list of filenames and prints just the filenames that
have a .txt extension using in operator
Problems
Data Encryption
- wireless transmission
- sniffing softwares
* Encryption technique
- 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 .
- 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.
* 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
* 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 two digits in this base two number system are 0 and 1.
* 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:
- 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.
* 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.
Eg:
- 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 string of bits is initially empty, and the process continues while the
decimal number is greater than 0.
Octal Number System
- 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.
* To convert from binary to hexadecimal, you factor the bits into groups
of four and look up the corresponding hex digits.
String Methods
Ex: split() can be used to obtain the list of the words contained in an
input string.
* Syntax of method
- 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:
2. Using the value of data from Problem 1, write the values of the
following expressions:
a. data.endswith('i')
Text Files
* 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 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.
* Using a text editor such as Notepad or TextEdit, you can create, view,
and save data in a text file
- 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.
Syntax:
- 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.
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
* Illustration:
Q: WAP to generate and write Five hundred random integers between 1
and 500 to a text file named integers.txt
- 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')
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.
Method 2: An application might read and process the text one line at a
time.
- 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.
* 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.
* 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.
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 .
- 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
* 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.
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
- 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
* You can also use other lists as elements in a list, thereby creating a list of
lists.
* When the Python interpreter evaluates a list literal, each of the elements
in it are evaluated.
* 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.
* 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
* 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.
- 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.
* 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.
- 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
- 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.
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
* The list method sort mutates a list (changes) a list by arranging its
elements in ascending order.
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
- 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:
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).
* 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.
Problems
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 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.
- anytime you foresee using a list whose structure will not change, you
can, and should, use a tuple instead.
* 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
Dictionary Literals
- Example :
{}
Adding Keys and Replacing Values
Accessing Values
* 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 .
* 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
- 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.
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
- Thus far, our programs have consisted of short code segments or scripts.
Some of these have used built-in functions to do useful work.
- Our scripts can be made useful, if we package them as functions and use
them in other needed scripts.
Header
- The header includes the keyword def as well as the function name and
list of parameters.
Function Body
Return Statement
- 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.
- 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.
* 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.
=> it requires the programmer to laboriously enter or copy the same code
over and over, and to get it correct every time.
- 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.
- 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.
* 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 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.
- 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
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
- 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.
* 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.
* 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.
* 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
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.
Lifetime
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.