Introduction to Python Programming (BPLCK105-205B)
Introduction to Python Programming (BPLCK105-205B)
Accredited with “A” Grade by NAAC | NBA Accredited for CSE, ECE & Mining Engg Programs
Oorgaum, Kolar Gold Fields - 563 120, Karnataka | Web : www.drttit.edu.in
DEPARTMENT OF
BASIC SCIENCE & HUMANITIES
Dr. T. Thimmaiah Institute of Technology
VISION
To produce technically competent engineers having innovative skills, positive
attitude, leadership and professional ethics, with a focus on developing
sustainable and new technology.
MISSION
Create a conducive environment for teaching, learning and innovation by
providing state of the art infrastructure.
Learn sustainable and new technologies through industry institute collaborations.
Produce technically competent engineers with ethics, discipline and social
consciousness through holistic education.
FOREWORD
This book is being prepared as a guide for the students to prepare thoroughly from
the examination and knowledge point of view to clear the course. The students
should read and practice this book completely to score good marks.
All the modules have been covered completely by considering the curriculum
content. The rst module is Python basics, the second module is List, Dictionaries
and Structuring data, the third module is Manipulating Strings and Reading Files,
the fourth module is Organizing Files and fth module is Classes and Objects
covering the syllabus.
This book is prepared considering previous years university question papers and
typical programs have been executed to cover all the topics. The English language
is simple and easy to understand. Also, the ow charts shown are self-explanatory
in nature.
Short answers to the points have been written to remember and recall with ease.
The students who prepare thoroughly from this book can attempt any type of
questions asked in the examination.
We thank our beloved president of Golden Valley Educational Trust, Dr.T. Venkat
Vardhan for his continuous support and encouragement.
We also thank our Principal, Vice-Principal, Dean Academics, IQAC Head, HOD
and all members in our department for their encouragement and motivation.
Course Instructors
Dr. Narasimha C, Associate Professor
Prof. Inbalatha K, Sr. Assistant Professor
Prof. Jillian Rufus J, Assistant Professor
Prof. Jeevika Mary.A, Assistant Professor
EDITORIAL NOTE
We congratulate and appreciate the authors for their effort towards making this
course simple and student friendly. This will denitely help the students to face the
exam with condence and score better.
We wish the students will positively and effectively make use of this guide.
This is the rst edition of the guide we welcome the feedback and suggestions from
students and faculty members to improve further for the benets of the students.
Module1:-Python Basics
Topics PageNo
1.1 Print(), input() and string replication 1-1
1.2 Elements of Flow Control 1-2
1.3 Functions: def Statements with Parameters 1-10
1.4 Local and Global Scope 1-10
1.5 A Short Program: Guess the Number 1-12
Question Bank 1-14
Introduction to Python Programming (BPLCK105/205B)
Module-1
Python Basics
1.1 Print(), input() and string replication
1) Demonstrate with example print (), input () and string replication. (6M)
[June/July 2023]
The print() Function
➢ The print() function displays the string value inside the parentheses on the screen.
➢ The line print ('Hello world!') means “Print out the text in the string 'Hello world!'.”
➢ When Python executes this line, you say that Python is calling the print () function and
the string value is being passed to the function.
➢ A value that is passed to a function call is an argument.
➢ The quotes are not printed to the screen. They just mark where the string begins and
ends; they are not part of the string value.
➢ Note: We can also use this function to put a blank line on the screen; just call print ()
with nothing in between the parentheses.
➢ This function call evaluates to a string equal to the user’s text, and the previous line of
code assigns the myName variable to this string value.
➢ We can think of the input() function call as an expression that evaluates to whatever
string the user typed in. If the user entered 'Al', then the expression would evaluate to
myName = 'Al'.
String Replication.
➢ The * operator is used for multiplication when it operates on two integer or floating-
point values.
➢ But, when the * operator is used on one string value and one integer value, it becomes
the string replication operator.
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-1
Introduction to Python Programming (BPLCK105/205B)
➢ The * operator can be used with only two numeric values (for multiplication) or one
string value and one integer value (for string replication). Otherwise, Python will just display
an error message.
2) Develop a program to generate Fibonacci square of length (N), Read N from the
console. (6M) [Jun/July 2023]
Output:
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-2
Introduction to Python Programming (BPLCK105/205B)
Flow Chart:
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-3
Introduction to Python Programming (BPLCK105/205B)
5. A colon
5. Starting on the next line, an indented block of code (called the for clause)
➢ Example and output:
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-4
Introduction to Python Programming (BPLCK105/205B)
➢ The code in a while clause will be executed as long as the while statement’s condition is
True.
➢ In code, a while statement always consists of the following:
1. The while keyword
2. A condition (that is, an expression that evaluates to True or False.
3. A colon
4. Starting on the next line, an indented block of code (called the while clause)
➢ We can see that a while statement looks similar to an if statement. The difference is in
how they behave. At the end of an if clause, the program execution continues after the if
statement.
➢ But, at the end of a while clause, the program execution jumps back to the start of the
while statement. The while clause is often called the while loop or just the loop.
Example:
➢ These statements are similar—both if and while check the value of spam, and if it’s less
than five, they print a message.
➢ But when we run these two code snippets, for the if statement, the output is simply
"Hello, world."
➢ But for the while statement, it’s "Hello, world." repeated five times!
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-5
Introduction to Python Programming (BPLCK105/205B)
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-6
Introduction to Python Programming (BPLCK105/205B)
Break Statements:
➢ There is a shortcut to getting the program execution to break out of a while loop’s clause
early.
➢ If the execution reaches a break statement, it immediately exits the while loop’s clause.
➢ In code, a break statement simply contains the break keyword.
➢ Example:
➢ The first line 1 creates an infinite loop; it is a while loop whose condition is always
True. (The expression True, after all, always evaluates down to the value True.)
➢ The program execution will always enter the loop and will exit it only when a break
statement is executed. (An infinite loop that never exits is a common programming bug.)
➢ Just like before, this program asks the user to type your name 2.
➢ Now, however, while the execution is still inside the while loop, an if statement gets
executed 3 to check whether name is equal to your name.
➢ If this condition is True, the break statement is run 4, and the execution moves out of
the loop to print('Thank you!') 5.
➢ Otherwise, the if statement’s clause with the break statement is skipped, which puts the
execution at the end of the while loop.
➢ At this point, the program execution jumps back to the start of the while statement 1 to
recheck the condition. Since this condition is merely the True Boolean value, the execution
enters the loop to ask the user to type your name again.
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-7
Introduction to Python Programming (BPLCK105/205B)
Flowchart:
while True:
print('Who are you?')
name = input()
➊ if name != 'Joe':
➋ continue
print('Hello, Joe. What is the password? (It is a fish.)')
➌ password = input()
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-8
Introduction to Python Programming (BPLCK105/205B)
if password == 'swordfish':
➍ break
➎print('Access granted.')
➢ If the user enters any name besides Joe 1, the continue statement 2 causes the program
execution to jump back to the start of the loop.
➢ When it reevaluates the condition, the execution will always enter the loop, since the
condition is simply the value True. Once they make it past that if statement, the user is asked
for a password 3.
➢ If the password entered is swordfish, then the break statement 4 is run, and the execution
jumps out of the while loop to print Access granted 5.
➢ Otherwise, the execution continues to the end of the while loop, where it then jumps
back to the start of the loop.
Flowchart:
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-9
Introduction to Python Programming (BPLCK105/205B)
➢ When we call the print() or len() function, we pass in values, called arguments in this
context, by typing them between the parentheses.
➢ We can also define our own functions that accept arguments.
➢ The definition of the hello() function in this program has a parameter called name 1.
➢ A parameter is a variable that an argument is stored in when a function is called. The first
time the hello() function is called, it’s with the argument 'Alice' 3.
➢ The program execution enters the function, and the variable name is automatically set to
'Alice', which is what gets printed by the print() statement 2.
➢ One special thing to note about parameters is that the value stored in a parameter is
forgotten when the function returns.
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-10
Introduction to Python Programming (BPLCK105/205B)
➢ A local scope is created whenever a function is called. Any variables assigned in this
function exist within the local scope. When the function returns, the local scope is destroyed,
and these variables are forgotten.
➢ Scopes matter for several reasons:
1. Code in the global scope cannot use any local variables.
2. However, a local scope can access global variables.
3. Code in a function’s local scope cannot use variables in any other local scope.
4. We can use the same name for different variables if they are in different scopes. That is,
there can be a local variable named spam and a global variable also named spam.
➢ The error happens because the eggs variable exists only in the local scope created when
spam() is called.
Once the program execution returns from spam, that local scope is destroyed, and there is no
longer a variable named eggs. Global Variables Can Be Read from a Local Scope
➢ Consider the following program:
➢ Since there is no parameter named eggs or any code that assigns eggs a value in the
spam() function, when eggs is used in spam(), Python considers it a reference to the global
variable eggs. This is why 42 is printed when the previous program is run.
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-11
Introduction to Python Programming (BPLCK105/205B)
6) Develop a program to read the name and year of birth of a person. Print whether
the person is a senior citizen or not. (7M) [June/July 2023]
Output:
Enter the name of person: Maha
Enter the year of birth of person: 1985
Maha is not a senior citizen.
This is a simple “guess the number” game. When we run this program, the output will look
something like this:
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-12
Introduction to Python Programming (BPLCK105/205B)
➢ Output:
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-13
Introduction to Python Programming (BPLCK105/205B)
Question bank
1) Demonstrate with example print (), input () and string replication. (6M)
2) Develop a program to generate Fibonacci square of length (N), Read N from the
console.(6M)
3) Explain elif, for, while, break and continue statements in python with examples for
each.(8M)
4) What are User Defined Functions? How can we pass parameters in User Defined
Functions? Explain with suitable example. (5M)
5) Explain Local and Global Scope with variables for each.(8M)
6) Develop a program to read the name and year of birth of a person. Print whether the
person is a senior citizen or not. (7M)
7) Write a python program to guess the secret number between 1 to 25 within 5 guess if the
number is same then it is right guess else wrong guess.(8M)
Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-14
Dr. T. THIMMAIAH INSTITUTE OF TECHNOLOGY
(Estd. 1986) Oorgaum, Kolar Gold Fields, Karnataka – 563120
(Affiliated to VTU, Belgaum, Approved by AICTE - New Delhi)
NAAC Accredited 'A' Grade, NBA Accredited for CSE, ECE & Mining Engg Programs
Topics Page No
2.1 List Data Type and Methods 2-1
2.2 Dictionary and Methods 2-2
2.3 List and Tuple 2-3
2.4 Dictionaries and Structuring Data 2-4
Question Bank 2-8
Introduction to Python Programming (BPLCK105/205B)
Module-2
Lists, Dictionaries and Structuring Data
2.1 List Data Type and Methods
1. What is a List? Explain append( ), insert( ) and remove( ) methods with examples
[June/July 2023 – 8M]
A list is a value that contains multiple values in an ordered sequence.
A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
A list begins with an opening square bracket and ends with a closing square bracket,
[ ].Values inside the list are also called items and are separated with commas
append( ) and insert( ) methods
➢ To add new values to a list, use the append( ) and insert( ) methods.
➢ The append( ) method call adds the argument to the end of the list.
Example:
➢ The insert( ) method can insert a value at any index in the list. The first argument to
insert( ) is the index for the new value, and the second argument is the new value to
be inserted.
Example:
remove ( ) methods
➢ The remove( ) method is passed the value to be removed from the list it is called on.
Example:
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-1
Introduction to Python Programming (BPLCK105/205B)
➢ If the value appears multiple times in the list, only the first instance of the value will be
removed.
➢ The remove( ) method is good when you know the value you want to remove from the
list.
Example:
➢ A for loop can iterate over the keys, values, or key-value pairs in a dictionary
by using keys(),values(), and items() methods.
➢ The values in the dict_items value returned by the items() method are tuples of the key
and value.
Example:
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-2
Introduction to Python Programming (BPLCK105/205B)
➢ If we want a true list from one of these methods, pass its list-like return value to the
list() function.
Example:
➢ The list(spam.keys()) line takes the dict_keys value returned from keys() and
passes it to list(),which then returns a list value of ['color', 'age'].
➢ We can also use the multiple assignment trick in a for loop to assign the key and
value to separate variables.
Example:
➢ The tuple data type is almost identical to the list data type, except in two ways.
➢ First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].
Example:
➢ Second, benefit of using tuples instead of lists is that, because they are immutable and
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-3
Introduction to Python Programming (BPLCK105/205B)
their contentsdon’t change. Tuples cannot have their values modified, appended, or
removed.
Example:
➢ If you have only one value in your tuple, you can indicate this by placing a trailing
comma after thevalue inside the parentheses.
➢ Converting a tuple to a list is handy if you need a mutable version of a tuple value.
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-4
Introduction to Python Programming (BPLCK105/205B)
5. Dictionary is used to store large amounts of data for easy and quick access
6. Dictionaries are used to build the indexes of the content
7. Dictionaries are used when you wish to build the map objects
5. Read N numbers from the console and create a list. Develop a program to
compute and print mean, variance and standard deviation with messages
June/July 2023 (10M )
Program:
N=int(input(‘Enter the number of elements:’))
lis=[ ]
For i in range(N):
lis.append(int(input(‘Enter the element:’)))
mean = round(sum(lis)/N,2)
print(‘\nMean is ‘,mean)
lis_mean=[ ]
for i in range(N):
lis_mean.append((lis[i]-mean)**2)
variance = round(sum(lis_mean)/N,2)
print(‘Variance is’,variance)
SD = round(variance**(1/2),2)
print(‘Standard deviation is’,SD)
if SD>=1.5:
print(‘High Dispersion, Low reliability.’)
else:
print(‘Low Dispersion, Reliable.’)
Output:
Enter the number of elements: 8
Enter the element: 10
Enter the element: 12
Enter the element: 23
Enter the element: 23
Enter the element: 16
Enter the element: 23
Enter the element: 21
Enter the element: 16
Mean is 18.0
Variance is 24.0
Standard deviation is 4.9
High Dispersion, Low Reliability.
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-5
Introduction to Python Programming (BPLCK105/205B)
• second argument is the value to set at that key if the key does not exist. If the key does exist,the
setdefault() method returns the key’s value.
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'. When spam.setdefault('color', 'white') is called next, the value for that
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-6
Introduction to Python Programming (BPLCK105/205B)
key is not changed to 'white' because spam already has a key named 'color'.
7. Discuss list and dictionary data structure with example for each.
June/July 2023 (6M )
List
A list is a value that contains multiple values in an ordered sequence.
A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
A list begins with an opening square bracket and ends with a closing square bracket,
[]. Values inside the list are also called items and are separated with commas
Example:
Dictionary
A dictionary is a collection of many values. 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, {}.
Example:
This assigns a dictionary to the myCat variable. This dictionary’s keys are 'size', 'color',
and 'disposition'. The values for these keys are 'fat', 'gray', and 'loud', respectively.
You can access these values through their keys:
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-7
Introduction to Python Programming (BPLCK105/205B)
Question bank
1) What is a List? Explain append( ), insert( ) and remove( ) methods with examples (8M)
7) Discuss list and dictionary data structure with example for each. (6M)
Prof. Jillian Rufus J , Asst. Prof., Dept. of EEE, Dr.TTIT, KGF 2-8
Dr. T. THIMMAIAH INSTITUTE OF TECHNOLOGY
(Estd. 1986) Oorgaum, Kolar Gold Fields, Karnataka – 563120
(Affiliated to VTU, Belgaum, Approved by AICTE - New Delhi)
NAAC Accredited 'A' Grade, NBA Accredited for CSE, ECE & Mining Engg Programs
Topics PageNo
3.1 Working with Strings 3-1
3.2 Project: Adding Bullets to Wiki Markup 3-2
3.3 The OS path Module 3-4
3.4 Reading and Writing the Contents of the File 3-6
Question Bank 3-12
Introduction to Python Programming (BPLCK105/205B)
Module 3
1. Explain the following methods with suitable examples [June/ July 2023-8M]
• These methods do not change the string itself but return new string values.
• If we want to change the original string, we have to call upper() or lower() on the string
and then assign the new string to the variable where the original was stored.
• The upper() and lower() methods are helpful if we need to make a case-insensitive
comparison.
• In the following small program, it does not matter whether the user types Great,
GREAT, or grEAT, because the string is first converted to lowercase.
Program Output
• The isupper() and islower() methods will return a Boolean True value if the string has
atleast one letter and all the letters are upper case or lowercase, respectively.
Since the upper() and lower() string methods themselves return strings, you can call
string methods on those returned string values as well. Expressions that do this will look like a
chain of method calls.
• When editing a Wikipedia article, we can create a bulleted list by putting each list item
on its own line and placing a star in front.
• We have a really large list that we want to add bullet points to. We could just type
those stars at the beginning of each line, one by one. Or we could automate this task
with a short Python script.
• The bulletPointAdder.pyscript will get the text from the clipboard, add a star and space
to the beginning of each line, and then paste this new text to the clipboard.
2. Do something to it
• Steps1 and 3 are pretty straight forward and involve the pyperclip.copy() and
pyperclip.paste() functions. Saving the following program as bulletPointAdder.py:
• The call to pyperclip.paste() returns all the text on the clipboard as one big string. If
we used the “List of Lists of Lists” example, the strings to reading text.
• The\n new line characters in this string cause it to be displayed with multiple lines
when it is printed or pasted from the clipboard.
• We could write code that searches for each \n newline character in the string and then
adds the star just after that. But it would be easier to use the split() method to return a
list of strings, one for each line in the original string, and then add the star to the front
of each string in the list.
• We split the text along its newlines to get a list in which each item is one line of the
text. For each line, we add a star and a space to the start of the line. Now each string in
lines begins with a star
Step3: Join the Modified Lines
• The lines list now contains modified lines that start with stars.
• pyperclip.copy() is expecting a single string value, not a list of string values. To make
this single string value, pass lines into the join() method to get a single string joined
from the list’s strings.
• When this program is run, it replaces the text on the clip board with text that has stars
at the start of each line.
3.3 The OS path Module
3) Explain with suitable python program segments [Model paper June/ July 2023-10M]
• The os.path module contains many helpful functions related to filenames and file
paths
• Since os.path is a module inside the os module, you can import it by simply running
import os.
Handling Absolute and Relative Paths
• The os.path module provides functions for returning the absolute path of a relative
path and for checking whether a given path is an absolute path.
• Calling os.path.abspath(path) will return a string of the absolute path of the argument.
• Calling os.path.dirname(path) will return a string of everything that comes before the
last slash in the path argument
• Calling os.path.basename(path) will return a string of everything that comes after
the last slash in the path argument.
C:\Windows\System32\calc.exe
The base name follows the last slash in a path and is the same as the file name. The dir name is
everything before the last slash.
• If you need a path’s dir name and base name together, you can just call os.path.split()
to get a tuple value with these two strings
• You could create the same tuple by calling os.path.dirname() and os.path.basename()
and placing their return values in a tuple.
• os.path.split() does not take a file path and return a list of strings of each folder.
For that, use the split() string method and split on the string in os.sep.
4) Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(),
and file methods open(), readlines(), and write()]. (Lab program 6)
Sample Input
Content available of the file is:
'Bluetooth technology is a high speed, low powered wireless technology that is used to transmit
and', 'receive data serially. The Bluetooth transceivers consist of many devices such as mobile
phones,', 'computers, and other electronic devices'
Sorted content is :
'Bluetooth technology is a high speed, low powered wireless technology that is used to transmit
and', 'computers, and other electronic devices', 'receive data serially. The Bluetooth transceivers
consist of many devices such as mobile phones’
5) Illustrate with example opening of a file with open(), reading the contents of the file
with read(), and writing to files with write() [June/ July 2023-12M]
>>>helloFile = open('C:\\Users\\your_home_folder\\hello.txt')
If you’re using OS X, enter the following into the interactive shell instead:
>>>helloFile = open('/Users/your_home_folder/hello.txt')
When a file is opened in read mode, Python lets you only read data from the file; you can’t
write or modify it in any way.
• Read mode is the default mode for files you open in Python.
• If you don’t want to rely on Python’s defaults, you can explicitly specify the mode by
passing the string value 'r' as a second argument to open().
• open('/Users/asweigart/ hello.txt', 'r') and open('/Users/asweigart/hello.txt')
Reading the Contents of Files
If you want to read the entire contents of a file as a string value, use the File object’s read()
method
>>>helloContent = helloFile.read()
>>>helloContent
'Hello world!'
• Alternatively, you can use the readlines() method to get a list of string values from the
file, one string for each line of text.
• For example, create a file named sonnet29.txt in the same directory as hello.txt and
write the following text in it:
• Make sure to separate the four lines with line breaks
When, in disgrace with fortune and men's eyes, I all alone beweep my outcast state, And trouble
deaf heaven with my bootless cries, and look upon myself and curse my fate,
>>>sonnetFile = open('sonnet29.txt')
>>>sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n', ' I all alone be weep my outcast state,\n',
And trouble deaf heaven with my bootless cries,\n', And look upon myself and curse my fate,']
Writing to Files
• Python allows you to write content to a file in a way similar to how the print() function
“writes” strings to the screen.
• You can’t write to a file you’ve opened in read mode, though. Instead, you need to open
it in “write plaintext” mode or “append plaintext” mode, or write mode and append
mode for short.
• Write mode will overwrite the existing file and start from scratch, just like when you
overwrite a variable’s value with a new value
• Pass 'w' as the second argument to open() to open the file in write mode Append mode,
on the other hand, will append text to the end of the existing file.
• Pass 'a' as the second argument to open() to open the file in append mode.
• If the filename passed to open() does not exist, both write and append mode will create a
new, blank file. For example
7) Write a python program that accepts a sentence and find the number of words, digits,
upper case letters and lower case letters
[Makeup paper Nov-Dec 2023- 6M]
def analyze_sentence(sentence):
# Initialize counts
word_count = 0
digit_count = 0
upper_count = 0
lower_count = 0
if __name__ == "__main__":
main()
Input
Enter a sentence: To read and write data using the shelve module, you first import shelve.
Call 2569787415
Output
Analysis of the sentence to read and write data using the shelve module, you first import
shelve. Call 2569787415':
Number of words: 15
Number of digits: 10
Number of uppercase letters: 2
Number of lowercase letters: 60
Question Bank
Tableof contents
Module4:-ORGANIZING FILES
Topics PageNo
4.1 The shutil Module 4-1
4.2 Permanently Deleting Files and Folders 4-4
4.3 Assertions 4-5
4.4 Logging 4-6
4.5 Getting the Traceback as a String 4-7
4.6 Walking a Directory Tree 4-8
Question Bank 4-12
Introductionto Python Programming (BPLCK105/205B)
MODULE 4
ORGANIZING FILES
4.1 The shutil Module
1. Explain the functions with example [June/July 2023 (10M)]
i. Shutil.copy ()
ii. Shutil.move()
iii. Shutil.rmtree()
iv. Shutil.copytree()
i. Shutil.copy ()
➢ The shutil module provides functions for copying files, as well as entire folders. Calling
shutil.copy(source, destination) will copy the file at the path source to the folder at the path
destination.
➢ If destination is a filename, it will be used as the new name of the copied file. This
function returns a string of the path of the copied file.
Program:
>>> import shutil, os
>>>os.chdir('C:\\')
u>>>shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt'
>>>shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
'C:\\delicious\\eggs2.txt'
➢ The first shutil.copy() call copies the file at C:\spam.txt to the folder C:\delicious. The
return value is the path of the newly copied file. Note that since a folder was specified as the
destination
➢ The original spam.txt filename is used for the new, copied file’s filename. The second
shutil.copy()call also copies the file at C:\eggs.txt to the folder C:\delicious but gives the
copied file the name eggs2.txt.
ii. Shutil.move()
➢ Calling shutil.move(source, destination) will move the file or folder at the path source to
the path destination and will return a string of the absolute path of the new location.
If destination points to a folder, the source file gets moved into destination and keeps
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-1
Introductionto Python Programming (BPLCK105/205B)
➢ Assuming a folder named eggs already exists in the C:\ directory, this shutil.move()
calls says, “Move C:\bacon.txt into the folder C:\eggs.”
➢ The destination path can also specify a filename
>>>shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
iii. Shutil.rmtree()
➢ Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it
contains will also be deleted.
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
If you had any important files ending with .rxt, they would have been accidentally,
permanently deleted
iv. Shutil.copytree()
➢ The first shutil.copy() call copies the file at C:\spam.txt to the folder C:\delicious. The
return value is the path of the newly copied file. Note that since a folder was specified as the
destination.
➢ The original spam.txt filename is used for the new, copied file’s filename. The second
shutil.copy()call also copies the file at C:\eggs.txt to the folder C:\delicious but gives the
copied file the name eggs2.txt.
Program:
>>> import shutil, os
>>>os.chdir('C:\\')
>>>shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
'C:\\bacon_backup'
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-2
Introductionto Python Programming (BPLCK105/205B)
➢ The shutil.copytree() call creates a new folder named bacon_backup with the same
content as the original bacon folder
Program:
>>> import shutil, os
>>>os.chdir('C:\\')
u>>>shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt'
>>>shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
'C:\\delicious\\eggs2.txt'
➢ The first shutil.copy() call copies the file at C:\spam.txt to the folder C:\delicious. The
return value is the path of the newly copied file. Note that since a folder was specified as the
destination
➢ The original spam.txt filename is used for the new, copied file’s filename. The second
shutil.copy()call also copies the file at C:\eggs.txt to the folder C:\delicious but gives the
copied file the name eggs2.txt.
Program:
>>> import shutil, os
>>>os.chdir('C:\\')
>>>shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
'C:\\bacon_backup'
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-3
Introductionto Python Programming (BPLCK105/205B)
➢ The shutil.copytree() call creates a new folder named bacon_backup with the same
content as the original bacon folder
Moving and Renaming Files and Folders
➢ Calling shutil.move(source, destination) will move the file or folder at the path source to
the path destination and will return a string of the absolute path of the new location.
➢ If destination points to a folder, the source file gets moved into destination and keeps its
current filename
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-4
Introductionto Python Programming (BPLCK105/205B)
4.3 Assertions
4. Explain the role of assertions in python with a suitable program
[June/July 2023 (5M)]
➢ An assertion is a sanity check to make sure your code isn’t doing something obviously
wrong.
➢ These sanity checks are performed by assert statements. If the sanity check fails, then an
AssertionError exception is raised.
➢ Assert statement consists of the following:
➢ The assert keyword
• A condition (that is, an expression that evaluates to True or False)
• A comma
• A string to display when the condition is False
➢ For example,
>>>ages=[26,57,92,54,22,15,17,80,47,73]
>>>ages.sort()
>>>ages
[15, 17, 22, 26, 47, 54, 57, 73, 80, 92]
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-5
Introductionto Python Programming (BPLCK105/205B)
>>>assert
ages[0]<=ages[-1] # assert that the first age is <= the last age
The assert statement here asserts that the first item is ages should be less than or equal to last
one
4.4 Logging
5. Explain the support for logging with logging module [June/July 2023 (6 M)]
➢ Logging is a great way to understand what’s happening in your program and in what
order its happening.
➢ Python’s logging module makes it easy to create a record of custom messages that you
write.
➢ These log messages will describe when the program execution has reached the logging
function call and list any variables you have specified at that point in time.
➢ On the other hand, a missing log message indicates a part of the code was skipped and
never executed.
Using the logging Module
➢ To enable the logging module to display log messages on your screen as your program
runs, import logging
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-6
Introductionto Python Programming (BPLCK105/205B)
Logging
Level Description
Function
The lowest level. Used for small details. Usually you care
DEBUG logging.debug()
about these messages only when diagnosing problems.
Used to record information on general events in your
INFO logging.info() program or confirm that things are working at their point in
the program.
Used to indicate a potential problem that doesn’t prevent
WARNING logging.warning the program from working but might do so in the future.
()
Used to record an error that caused the program to fail to do
ERROR logging.error()
something.
The highest level. Used to indicate a fatal error that has
CRITICAL logging.critical() caused or is about to cause the program to stop running
entirely.
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-7
Introductionto Python Programming (BPLCK105/205B)
➢ For example,
>>> import traceback
>>> try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInfo.txt.')
116
The traceback info was written to errorInfo.txt. The 116 is the return value from the write()
method, since 116 characters were writtento the file
Traceback
File "<pyshell#28>", line 2, in <mo
Exception: This is the error message.
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-8
Introductionto Python Programming (BPLCK105/205B)
➢ If you want to rename every file in some folder and also every file in every subfolder of
that folder.
➢ That is, you want to walk through the directory tree, touching each file as you go.
➢ Writing a program to do this could get tricky; fortunately, Python provides a function to
handle this process for you.
Fig.4.1 : An example folder that contains three folders and four file
import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print('')
➢ The os.walk() function is passed a single string value: the path of a folder. You can use
os.walk() in a for loop statement to walk a directory tree, much like how you can use the
range() function to walk over a range of numbers.
➢ Unlike range(), the os.walk() function will return three values on each iteration through
the loop:
1. A string of the current folder’s name
2. A list of strings of the folders in the current folder
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-9
Introductionto Python Programming (BPLCK105/205B)
9. Develop a program to backing up a given folder into a zip file by using relevant
modules and suitable methods [June/July 2023 (10 M)]
Program
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
newBase = os.path.basename(folder)
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
# Main Program
backupToZip(r'C:\Users\Sathish\Desktop\bb')
Output:
Done.
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-10
Introductionto Python Programming (BPLCK105/205B)
10. Write a function named DivExp which takes TWO parameters a, b and returns a
value c (c=a/b). Write suitable assertion for a>0 in function DivExp and raise an
exception for when b=0. Develop a suitable program which reads two values from the
consoleand calls a function DivExp. [June/July 2023 (10 M)]
Program:
def DivExp(a,b):
try:
c=a/b
except ZeroDivisionError:
print('Error: Division by zero')
else:
return c
a = int(input('Enter the Divident value of \'a\': '))
b = int(input('Enter the Divisor value of \'b\': '))
d=DivExp(a,b)
if d is not None:
print('The result of division is: ', d)
else:
print('The result of division is: infinity')
Output:
Enter the Divident value of 'a': 10
Enter the Divisor value of 'b': 0
Error: Division by zero
The result of division is: infinity
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-11
Introductionto Python Programming (BPLCK105/205B)
Question Bank
1. Explain the functions with example
i. Shutil.copy ()
ii. Shutil.move()
iii. Shutil.rmtree()
iv. Shutil.copytree() (10M)
2. How to organize a file using shutil.module? (6M)
3. Explain permanent delete and safe delete with a suitable python program (10M)
4. Explain the role of assertions in python with a suitable program (5M)
5. Explain the support for logging with logging module (6M)
6. Describe the concept of logging. Also discuss the levels of logging (7M)
7. What is traceback? Explain with example (6M)
8. Explain a directory tree in detail and write python program to display all the folders,
subfolders, subfolders and file names (10M)
9. Develop a program to backing up a given folder into a zip file by using relevant
modules and suitable methods (10M)
10. Write a function named DivExp which takes TWO parameters a, b and returns a value c
(c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception for
when b=0. Develop a suitable program which reads two values from the console and
calls a function DivExp. (10M)
Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-12
Dr. T. THIMMAIAH INSTITUTE OF TECHNOLOGY
(Estd. 1986) Oorgaum, Kolar Gold Fields, Karnataka – 563120
(Affiliated to VTU, Belgaum, Approved by AICTE - New Delhi)
NAAC Accredited 'A' Grade, NBA Accredited for CSE, ECE & Mining Engg Programs
Topics PageNo
5.1 Classes and Objects 5-1
5.2 Classes and Functions 5-2
5.3 Classes and Methods 5-5
Question Bank 5-8
Introduction to Python Programming (BPLCK105/205B)
Module-5
1) What is class? How to define class in python? How to initiate a class and how the
class members are accessed explain with examples? (6M) [Dec. 2023/Jan. 2024]
➢ A class is programmer defined data type which binds data and functions together into a
single entity
pass
print (point)
➢ The process of creating a new object is called as instantiation and the object is called as
an instance of a class
➢ Class members that is the attributes and methods can be accessed using the object of a
class
Syntax:
objectname.attributename
objectname.methodname()
2) Define class and object? What are programmer defined types? Explain with
examples? (6M) [June/July 2023]
➢ Class is user defined data type which binds data and function together into a single
entity. A class can have a set of variables also known as attributes and member function
also known as methods.
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-1
Introduction to Python Programming (BPLCK105/205B)
➢ Object: - an object is an instance of a class and it has physical existence. One can create
➢ Programmer defined types i.e. a class in python can be created using a keyword class.
Here, we are creating an empty class without any members by just using the keyword
pass within it
class point :
pass
print(point)
output
The process of the creating a new object is called as instantiation and the object is
instance of a class
point (p)
< __ main __ point object at 0x003C1BF0
3) Develop a program that uses class student which prompts the user to enter the
marks in three subjects, calculates total marks, percentage and displays the details.
(8M) [Nov/ Dec 2023]
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-2
Introduction to Python Programming (BPLCK105/205B)
class Student:
def __init__(self, name = " ", usn = " ", marks = [0,0,0,0]):
self.name = name
self.usn = usn
self.marks = marks
def getMarks(self):
def display(self):
print(self.name)
print(self.usn)
print(self.marks[0:3])
s1 = Student()
s1.getMarks()
s1.display()
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-3
Introduction to Python Programming (BPLCK105/205B)
➢ A pure function is a function which takes objects as arguments and does some work
without modifying any of the original arguments
Ex:
Class Time:
hours
minutes
seconds
def add_time(t1,t2):
Sum=Time()
Sum.hour=t1.hour+t2hour
Sum.minute=t1.minute+t2.minute
Sum.second=t1.second+t2.second
If Sum.second>=60:
Sum.second-=60
Sum.minute=1
If Sum.minute>=60:
Sum.minute-=60
Sum.hour t=1
return sum
t1=time()
t1.hour=10
t1.minute=1
t1.second=14
t2=time()
t2.hour=2
t2.minute=4
t2.second=6
t3=time()
t3=add_time(t1,t2)
5
➢ In the above example we have a class time and function add_time(t1,t2) it takes two
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-4
Introduction to Python Programming (BPLCK105/205B)
objects t1 and t2 adds the time (hour, min, sec) and prints without modifying the
original value of t1and t2
5) Explain __init__ special method with an example? (4M) [Dec. 2023/Jan. 2024]
➢ The init (initialization) method is a special method that gets invoked when an object is
instantiated.
Ex:
# inside class Time:
Self.hour=hour
Self.minute=minute
Self.second=second
When no parameters are given during objects creation then the default values are
assigned
hour=0
minutes=0
seconds=0
time = Time(10,10,10)
then hours=10
minutes=10
seconds=10
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-5
Introduction to Python Programming (BPLCK105/205B)
➢ __str__ is a special method like int that is supposed to return a string representation of
an object.
def __str__(self):
return ‘%.2d:%.2d:%.2d’%(self.hour,self.minute,self.second)
>> print(time)
Output: 09:45:00
7) Explain polymorphism in python with a suitable example? (7M) [Nov/ Dec 2023]
➢ Polymorphism means having many forms. Polymorphism means the same function
Ex:
a)
def add(a,b,c=0):
return p+q+r
print(add(6,23))
print(add(10,20,30))
➢ Here the functions add is used to add the numbers. When the function is called with the
name and passing two arguments it will add two numbers and returns the sum. The
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-6
Introduction to Python Programming (BPLCK105/205B)
b) Addition operator
num1=1
num2=2
print(num1+num2)
o/p=3
str1=”python “
str2=”programming “
print(str1+” ” str2)
o/p=python programming
➢ Here we can see that single operator “ +” is used to carry addition operation on integer
data type and string data type (string concatenation) so the “+” operator has different
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-7
Introduction to Python Programming (BPLCK105/205B)
Question bank
1) How to define class in python? How to initiate a class and how the class members are
4) Define classes and objects in python. Create a class called Employee and initialize with
employee id and name. a) Set Age to assign age to the employee, b) Set Salary to assign
salary to the employee, c) Display to display all information of the employee (8M)
6) Write a function called print time that takes a time object and print it in the form of hour:
minute: second.(6M)
Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-8
Program Outcomes (Pos)
Graduates will be able to:
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one ‘s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Department of Basic Science and Humanities Vision
The Department of Science and Humanities is committed to inculcate competence and
prociency in the eld of Basic Science, with professional ethics, critical and logical thinking.