0% found this document useful (0 votes)
9 views66 pages

Introduction to Python Programming (BPLCK105-205B)

The document is a guidebook for the 'Introduction to Python Programming' course at Dr. T. Thimmaiah Institute of Technology, aimed at helping students prepare for examinations. It covers essential topics such as Python basics, flow control, string manipulation, and object-oriented programming, with an emphasis on practical examples and exercises. The guide encourages students to engage with the material to enhance their understanding and performance in the course.

Uploaded by

sparkysanthosh69
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)
9 views66 pages

Introduction to Python Programming (BPLCK105-205B)

The document is a guidebook for the 'Introduction to Python Programming' course at Dr. T. Thimmaiah Institute of Technology, aimed at helping students prepare for examinations. It covers essential topics such as Python basics, flow control, string manipulation, and object-oriented programming, with an emphasis on practical examples and exercises. The guide encourages students to engage with the material to enhance their understanding and performance in the course.

Uploaded by

sparkysanthosh69
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/ 66

Afliated to Visvesvaraya Technological University, Belagavi | Approved by AICTE - New Delhi

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

Introduction to Python Programming


(BPLCK105/205B)

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

As new subjects and topics are added in the current


syllabus, the students nd it difcult to cope up to study the
entire syllabus. Also, students don't nd time to invest in
innovation or upskilling themselves to the requirements of
the industry.

Keeping this in mind, our dedicated faculty members have


worked to bring out this guidebook which help the
students to clear the courses easily. I extend my heartfelt
appreciation to the authors for their tireless efforts in
creating a resource that not only educates but also inspires.

I encourage every student to approach this book as a


guide with curiosity and eagerness to learn and perform
better in examinations. May this guide serve as a
cornerstone in your academic journey, igniting a passion
towards engineering that will illuminate your path towards
a brighter future.

Best wishes for an enriching and fullling learning


experience!

Dr. T. VENKAT VARDHAN


President, GVET
PREFACE

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 denitely help the students to face the
exam with condence 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 benets of the students.

Dr. Jenitha A, IQAC Head


Prof. Ruckmani Divakaran, Dean Academics
Dr. H G Shenoy, Vice Principal
Dr. Syed Ariff, Principal
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

Department of Basic Science and Humanities


Table of contents

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.

The Input Function


➢ The input() function waits for the user to type some text on the keyboard and press
ENTER

➢ 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:

Enter the required length of Fibonacci sequence: 10


The first 10 terms of Fibonacci series are:0 1 1 2 3 5 8 13 21 34

1.2 Elements of Flow Control


3) Explain elif, for, while, break and continue statements in python with examples for
each. (8 M) [June/July 2023]
elif Statements:
➢ While only one of the if or else clauses will execute, we may have a case where we want

Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-2
Introduction to Python Programming (BPLCK105/205B)

one of many possible clauses to execute.


➢ The elif statement is an “else if” statement that always follows an if or another elif
statement.
➢ It provides another condition that is checked only if all of the previous conditions were
False.
➢ In code, an elif statement always consists of the following:
1. The elif 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 elif clause)
Example:

Flow Chart:

Figure 1: The flowchart for an else statement

for loops and the range() function:


➢ If we want to execute a block of code only a certain number of times then we can do this
with a for loop statement and the range() function.
➢ In code, a for statement looks something like for i in range(5): and always includes the
following:

Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-3
Introduction to Python Programming (BPLCK105/205B)

1. The for keyword


2. A variable name
3. The in keyword
4. A call to the range() method with up to three integers passed to it

5. A colon

5. Starting on the next line, an indented block of code (called the for clause)
➢ Example and output:

➢ The code in the for loop’s clause is run five times.


➢ The first time it is run, the variable i is set to 0.
➢ The print() call in the clause will print Jimmy Five Times (0).
➢ After Python finishes an iteration through all the code inside the for loop’s clause, the
execution goes back to the top of the loop, and the for statement increments i by one.
➢ Flowchart

Figure 2: The flowchart for an for loop


➢ This is why range(5) results in five iterations through the clause, with i being set to 0, then
1, then 2, then 3, and then 4.
➢ The variable i will go up to, but will not include, the integer passed to range().

while loop Statements:


➢ We can make a block of code execute over and over again with a while statement.

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)

Figure 3: The flowchart for the if statement code

Figure 4: The flowchart for the while statement code


➢ In the while loop, the condition is always checked at the start of each iteration (that is,
each time the loop is executed).
➢ If the condition is True, then the clause is executed, and afterward, the condition is
checked again.
➢ The first time the condition is found to be False, the while clause is skipped.

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:

Figure 5: The flowchart for the break statement code


Continue statements:
➢ Like break statements, continue statements are used inside loops.
➢ When the program execution reaches a continue statement, the program execution
immediately jumps back to the start of the loop and reevaluates the loop’s condition.
➢ Example :

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:

Figure 6: The flowchart for the continue statement code

Prof. Jeevika Mary. A , Asst. Prof., Dept. of ECE, Dr.TTIT, KGF 1-9
Introduction to Python Programming (BPLCK105/205B)

1.3 Functions: def Statements with Parameters


4) What are User Defined Functions? How can we pass parameters in User Defined
Functions? Explain with suitable example (5 M) [June/July 2023]

➢ 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.

Example with output:

➢ 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.

1.4 Local and Global Scope


5) Explain Local and Global Scope with variables for each.(8M) [June/July 2023]
➢ Parameters and variables that are assigned in a called function are said to exist in that
function’s local scope.
➢ Variables that are assigned outside all functions are said to exist in the global scope.
➢ A variable that exists in a local scope is called a local variable, while a variable that
exists in the global scope is called a global variable.
➢ A variable must be one or the other; it cannot be both local and global.
➢ When a scope is destroyed, all the values stored in the scope’s variables are forgotten.
➢ There is only one global scope, and it is created when your program begins. When your
program terminates, the global scope is destroyed, and all its variables are forgotten.

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.

Local Variables Cannot Be Used in the Global Scope


➢ Consider this program, which will cause an error when you run it:

➢ 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.

1.5 A Short Program: Guess the Number


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) [Nov/ Dec 2023]

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

Department of Basic Science and Humanities


Table of contents

Module1:- Lists, Dictionaries and Structuring Data

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.

2.2: Dictionary and Methods


2. Explain the following methods with example:
i)keys( ) ii) values( ) iii) items( ) June/July 2023 (12M )

The keys(), values(), and items() Methods


➢ There are three dictionary methods that will return list-like values of the
dictionary’s keys, values,or both keys and values: keys(), values(), and items().
➢ Data types (dict_keys, dict_values, and dict_items, respectively) can be used in for
loops.

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:

2.3: List and Tuple


3. How is tuple different from a list and which function is used to convert list to
tuple? Explain
June/July 2023 (6M )

➢ 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 Types with the list() and tuple() Functions


➢ The functions list() and tuple() will return list and tuple versions of the values passed to
them.

➢ Converting a tuple to a list is handy if you need a mutable version of a tuple value.

2.4: Dictionaries and Structuring Data

4. List the merits of dictionary over list. June/July 2023 (4M )

1. The dictionary is created by placing elements in { } as “key”:”value”, each key-value


pair is separated by commas “, “
2. Unlike lists, items in dictionaries are unordered.
3. We can have arbitrary values for the keys that allows us to organize our data in powerful
ways.
4. The list is an ordered collection of data, whereas the dictionaries store the data in the
form of key-value pairs using the hashtable structure.

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)

6. Explain with a programming example to each


i) get( ) ii) setdefault( ) June/July 2023 (6M )

The get( ) Method

Dictionaries have a get() method that takes two arguments:


➢ The key of the value to retrieve and
➢ A fallback value to return if that key does not exist.

The setdefault() Method


➢ To set a value in a dictionary for a certain key only if that key does not already have a
value.

➢ The setdefault() method offers a way to do this in one line of code.


➢ Setdeafault() takes 2 arguments:

• The The first argument is the key to check for, and

• 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)

2) Explain the following methods with example:


i)keys( ) ii) values( ) iii) items( ) (12M)
3) How is tuple different from a list and which function is used to convert list to tuple?
Explain (6M)
4) List the merits of dictionary over list. (4M)
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. (10M)
6) Explain with a programming example to each
i) get( ) ii) setdefault (6M )

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

Department of Basic Science and Humanities


Table of contents

Module3:-MANIPULATING STRINGS AND READING FILES

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

MANIPULATING STRINGS AND READING FILES


3.1 Working with Strings

1. Explain the following methods with suitable examples [June/ July 2023-8M]

i) upper ii) lower iii) is_upper iv) is_lower


Several string methods analyze strings or create transformed string values.
The upper(), lower(), isupper(), and islower() String Methods
• The upper() and lower() string methods return a new string where all the letters in the
original string have been converted to upper case or lower case, respectively.

• 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.

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-1


Introduction to Python Programming (BPLCK105/205B)

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.

3.2 Project: Adding Bullets to Wiki Markup


2) Explain the steps involved in adding bullets to WikiMarkup. Support with appropriate
code [June/ July 2023-10M]

• 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.

Ex: Program output

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-2


Introduction to Python Programming (BPLCK105/205B)

Step 1: Copy and Paste from the Clipboard


• You want the bulletPointAdder.py program to do the following:

1. Paste text from the clipboard

2. Do something to it

3. Copy the new text to the clipboard

• Steps1 and 3 are pretty straight forward and involve the pyperclip.copy() and
pyperclip.paste() functions. Saving the following program as bulletPointAdder.py:

Step2:Separate the Lines of Text and Add the Star

• 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.

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-3


Introduction to Python Programming (BPLCK105/205B)

• 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]

a) os.path.basename() b)os.path.join() c)os.path.dirname() d)os.path.split()

The os.path Module

• 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.

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-4


Introduction to Python Programming (BPLCK105/205B)

This is an easy way to convert a relative path into an absolute one.


• Calling os.path.isabs(path) will return True if the argument is an absolute path and
False if it is a relative path
• Calling os.path.relpath(path, start) will return a string of a relative path from the start
path to path. If start is not provided, the current working directory is used as the start
path.
>>>os.path.abspath('.')
'C:\\Python34'
>>>os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>>os.path.isabs('.')
False
>>>os.path.isabs(os.path.abspath('.'))
True

• Enter the following calls to os.path.relpath() into the interactive shell

• 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

Dir name Base name

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.

• But os.path.split() is a nice shortcut if you need both values.

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-5


Introduction to Python Programming (BPLCK105/205B)

• 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)

[June/ July 2023-10M]

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’

3.4 Reading and Writing the contents of the File

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]

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-6


Introduction to Python Programming (BPLCK105/205B)

Opening Files with the open() Function


• To open a file with the open() function, you pass it a string path indicating the file you

want to open; it can be either an absolute or relative path.


• The open() function returns a File object. Try it by creating a text file named hello.txt
using Note pad or Text Edit.
• Type Hello world! as the content of this text file and save it in your user home folder.

>>>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,']

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-7


Introduction to Python Programming (BPLCK105/205B)

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

6) Write a python program to count number of lines in a file


[Makeup paper Nov-Dec 2023- 6M]
Program
def count_lines(filename):
try:
# Open the file in read mode
with open(filename, 'r') as file:
# Initialize line counter
line_count = 0
# Iterate through each line in the file

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-8


Introduction to Python Programming (BPLCK105/205B)

for line in file:


line_count += 1
return line_count
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except IsADirectoryError:
print(f"Error: '{filename}' is a directory, not a regular file.")
except Exception as e:
print(f"Error: An unexpected error occurred - {e}")
# Example usage:
filename = 'sample.txt' # Replace with your file name or path
num_lines = count_lines(filename)
if num_linesis not None:
print(f"The file '{filename}' has {num_lines} lines.")

Input Text file (sample.txt)


To read and write data using the shelve module, you first import shelve. Call
shelve.open() and pass it a filename, and then store the returned shelf value in a variable. Create
a list cats and write shelf File['cats'] = cats to store the list in shelf File as a value associated
with the key 'cats' (like in a dictionary). Then we call close() on shelf File. programs can use the
shelve module to later reopen and retrieve the data from these shelf files Shelf values don’t have
to be opened in read or write mode—they can do both once opened
Output
The file 'sample.txt' has 6 lines.

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

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-9


Introduction to Python Programming (BPLCK105/205B)

# Iterate through each character in the sentence


for char in sentence:
if char.isalpha():
if char.islower():
lower_count += 1
elifchar.isupper():
upper_count += 1
elifchar.isdigit():
digit_count += 1

# Count words (split by whitespace)


words = sentence.split()
word_count = len(words)
return word_count, digit_count, upper_count, lower_count

# Function to get user input and display results


def main():
sentence = input("Enter a sentence: ")
word_count, digit_count, upper_count, lower_count = analyze_sentence(sentence)

print(f"\nAnalysis of the sentence '{sentence}':")


print(f"Number of words: {word_count}")
print(f"Number of digits: {digit_count}")
print(f"Number of uppercase letters: {upper_count}")
print(f"Number of lowercase letters: {lower_count}")

if __name__ == "__main__":
main()

Input
Enter a sentence: To read and write data using the shelve module, you first import shelve.
Call 2569787415

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-10


Introduction to Python Programming (BPLCK105/205B)

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

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-11


Introduction to Python Programming (BPLCK105/205B)

Question Bank

1. Explain the following methods with suitable examples (8M)


2. Explain the steps involved in adding bullets toWikiMarkup. Support with appropriate
code (10M)
3. Explain with suitable python program segments
a) os.path.basename() b)os.path.join() c)os.path.dirname() d)os.path.split() (10M)
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()]. (10M)
5. Illustrate with example opening of a file with open(), reading the contents of the file
with read(), and writing to files with write() (12M)
6. Write a python program to count number of lines in a file (6M)
7. Write a python program that accepts a sentence and find the number of words, digits,
upper case letters and lower case letters (6M)

Prof. Inbalatha K, Dept. of CSE(AI & ML), Dr.TTIT, KGF 3-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

Department of Basic Science and Humanities

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)

its current filename


>>> import shutil
>>>shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'

➢ 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

2. How to organize a file using shutil.module [Makeup paper Aug 2023-6 M]


➢ The shutil (or shell utilities) module has functions to let you copy, move, rename, and
delete files in your Python programs
Copying Files and Folders
➢ 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.

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 shutil


>>>shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'
➢ 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

4.2 Permanently Deleting Files and Folders


3. Explain permanent delete and safe delete with a suitable python program
[Makeup paper Aug 2023-10M]
➢ You can delete a single file or a single empty folder with functions in the os module,
Where as to delete a folder and all of its contents, you use the shutil module. Calling
os.unlink(path) will delete the file at path.
➢ Calling os.rmdir(path) will delete the folder at path. This folder must be empty of any
files or folders
➢ 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)

Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-4
Introductionto Python Programming (BPLCK105/205B)

Safe Deletes with the send2trash Module


➢ Since Python’s built-in shutil.rmtree() function irreversibly deletes files and folders, it
can be dangerous to use.
➢ A much better way to delete files and folders is with the third-party send2trash Module.
➢ You can install this module by running pip install send2trash from a Terminal Window
➢ Using send2trash is much safer than Python’s regular delete functions, because it will
send folders and files to your computer’s trash or recycle bin instead of permanently deleting
them.

>>> import send2trash


>>>baconFile = open('bacon.txt', 'a') # creates the file
>>>baconFile.write('Bacon is not a vegetable.')
25
>>>baconFile.close()
>>> send2trash.send2trash('bacon.txt')

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

logging.basic Config(level=logging.DEBUG, format='%(asctime)s-%(levelname)s


%(message)s')
➢ when Python logs an event, it creates a LogRecord object that holds information about
that event
➢ The logging module’s basicConfig() function lets you specify what details about the
Log Record object you want to see and how you want those details displayed

Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-6
Introductionto Python Programming (BPLCK105/205B)

6. Describe the concept of logging. Also discuss the levels of logging


[Makeup paper Aug 2023-7 M]
➢ Logging levels provide a way to categorize your log messages by importance. There are
five logging levels Messages can be logged at each level using a different logging function.

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.

4.5 Getting the Traceback as a String


7. What is traceback? Explain with example [June/July 2023 (6 M)]
➢ When Python encounters an error, it produces a treasure trove of error information
called the traceback.
➢ The traceback includes the error message, the line number of the line that caused the
error, and the sequence of the function calls that led to the error.
def sp
bacon()
def bacon():
raise Exception('This is the error message.')
spam()
Output:
Traceback (most recent call last):

Prof. Jillian Rufus & Prof. Jeevika Mary.A, Dr.TTIT, KGF 4-7
Introductionto Python Programming (BPLCK105/205B)

File "errorExample.py", line 7, in <module>


spam()
File "errorExample.py", line 2, in spam
bacon()
File "errorExample.py", line 5, in bacon
raise Exception('This is the error message.')
Exception: Thisisthe error message.

➢ The traceback is displayed by Python whenever a raised exception goes unhandled


➢ But you can also obtain it as a string by calling traceback.format_exc(). This function is
useful if you want the information from an exception’s traceback but also want an except
statement to gracefully handle the exception.

➢ 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.

4.6 Walking a Directory Tree


8. Explain a directory tree in detail and write python program to display all the
folders, subfolders, subfolders and file names [June/July 2023
(10 M)]

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)

3. A list of strings of the files in the current folder

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

Department of Basic Science and Humanities


Table of contents

Module 5:- Classes and Objects

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

Classes and Objects

5.1 Classes and Objects

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

➢ Class is defined using a keyword “Class”

ex: class Point :

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

P= point() => reference to the point object is created and assigned to p.

➢ 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)

➢ Class acts like a prototype/template/blueprint (no physical space or memory)

➢ Object: - an object is an instance of a class and it has physical existence. One can create

any number of objects for a class

➢ 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

<class __ main __ point>

The term __ main __ indicates that the class

point is in the main scope of the current module

P = point() reference is a point object is created and assigned to p

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

5.2 Classes and Functions

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):

self.name = input(" Enter the student name :") 5

self.usn = input(" Enter the usn name :")

self.marks[0] = int(input(" Enter the marks in subject 1 :"))

self.marks[1] = int(input(" Enter the marks in subject 2 :"))

self.marks[2] = int(input(" Enter the marks in subject 3 :"))

self.marks[3] = self.marks[0] + self.marks[1] + self.marks[2]

def display(self):

print(self.name)

print(self.usn)

print(self.marks[0:3])

print("Total marks is :", self.marks[3])

print("Percentage :", self.marks[3]/3)

s1 = Student()

s1.getMarks()

s1.display()

Enter the usn name : Suresh


Enter the usn name : 1GV23MI0028
[86, 75, 92]
Total marks is: 253
Percentage: 84.33333333333333

Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-3
Introduction to Python Programming (BPLCK105/205B)

4) Define pure functions. Illustrate with an example python program? (8M)


[June/July 2023]

➢ 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.3 Classes and Methods

5) Explain __init__ special method with an example? (4M) [Dec. 2023/Jan. 2024]

The __init__ method

➢ The init (initialization) method is a special method that gets invoked when an object is
instantiated.

Ex:
# inside class Time:

def __init__(self, hour=0, minute=0, second=0):

Self.hour=hour

Self.minute=minute

Self.second=second

When we create an object of class time:

>>time=Time() creating an object (instantiation)

Automatically the __init__ special method gets executed.

When no parameters are given during objects creation then the default values are

assigned

hour=0

minutes=0

seconds=0

>>> When the object is created with values

time = Time(10,10,10)

then hours=10

minutes=10

seconds=10

It overrides the default values of 0

Dr. Narasimha C., Assoc. Prof., Dept. of ME, Dr. TTIT, KGF 5-5
Introduction to Python Programming (BPLCK105/205B)

6) Explain __str__ method with an example? (4M) [Dec. 2023/Jan. 2024]

➢ __str__ is a special method like int that is supposed to return a string representation of
an object.

Ex: String method for time objects.

# inside class Time:

def __str__(self):

return ‘%.2d:%.2d:%.2d’%(self.hour,self.minute,self.second)

When we print an object, python invokes the __str__ special method.

>> time = Time(9,45)

>> 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

name but with different signatures, for multiples types.

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

function is used to add three numbers also.

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

forms which is an occurrence of polymorphism in python.

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

accessed explain with examples. (6M)

2) Explain __init__ and __str__ method with an example. (5M)

3) Explain operator overloading and polymorphism with example. (5M)

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)

5) Explain printing objects in python.(5M)

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:

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex
engineering problems.

2. Problem analysis: Identify, formulate, research literature, and analyze complex


engineering problems reaching substantiated conclusions using rst principles of
mathematics, natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specied needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

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.

7. Environment and Sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts and demonstrate the knowledge of need
for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

9. Individual and Teamwork: Function effectively as an individual, and as a member or leader


in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.

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
prociency in the eld of Basic Science, with professional ethics, critical and logical thinking.

Department of Basic Science and Humanities Mission


To develop a strong scientic foundation through fundamental principles of Physics,
Chemistry and Mathematics to pursue a successful engineering carrier.
To transform students into dynamic, responsible and productive Professionals in their
respective elds.
To integrate human values and social concerns with technical education.

You might also like