PythonProgrammingNotes Unit1&2
PythonProgrammingNotes Unit1&2
1
INTRODUCTION
Unit Structure
1.0 Objectives
1.1 Introduction: The Python Programming Language
1.2 History
1.3 Features
1.4 Installing Python
1.5 Running Python program
1.6 Debugging
1.6.1 Syntax Errors
1.6.2 Runtime Errors
1.6.3 Semantic Errors
1.6.4 Experimental Debugging
1.7 Formal and Natural Languages
1.8 The Difference Between Brackets, Braces, and Parentheses
1.9 Summary
1.10 References
1.11 Unit End Exercise
1.0 OBJECTIVES
1
We don’t need to use data types to declare variable because it
is dynamically typed so we can write a=10 to declare an integer
value in a variable.
Python makes the development and debugging fast because there is
no compilation step included in python development.
1.2 HISTORY
1.3 FEATURES
1. Easy to Code:
Python is a very developer-friendly language which means that
anyone and everyone can learn to code it in a couple of hours or
days.
As compared to other object-oriented programming languages like
Java, C, C++, and C#, Python is one of the easiest to learn.
4. Object-Oriented Approach:
One of the key aspects of Python is its object-oriented
approach. This basically means that Python recognizes the
concept of class and object encapsulation thus allowing
programs to be efficient in the long run.
5. Highly Portable:
Suppose you are running Python on Windows and you need to shift
the same to either a Mac or a Linux system, then you can easily
achieve the same in Python without having to worry about
changing the code.
This is not possible in other programming languages, thus making
Python one of the most portable languages available in the
industry.
6. Highly Dynamic
Python is one of the most dynamic languages available in the
industry today. What this basically means is that the type of a
variable is decided at the run time and not in advance.
Due to the presence of this feature, we do not need to specify the
type of the variable during coding, thus saving time and increasing
efficiency.
3
Before starting working with Python, a specific path is to set to set path
follow the steps:
Right click on My Computer--> Properties -->Advanced System
setting -->Environment Variable -->New
In Variable name write path and in Variable value copy path up to C://
Python (i.e., path where Python is installed). Click Ok ->Ok.
Example:
Here is the simple code of Python given in the Python file
demo.py. It contains only single line code of Python which prints
the text “Hello World!” on execution.
So, how you can execute the Python program using the command
prompt. To see this, you have to first open the command
prompt using the ‘window+r’ keyboard shortcut. Now, type the
word ‘cmd’ to open the command prompt.
This opens the command prompt with the screen as given
below. Change the directory location to the location where you
have just saved your Python .py extension file.
We can use the cmd command ‘cd’ to change the directory
location. Use ‘cd..’ to come out of directory and “cd” to come
inside of the directory. Get the file location where you saved your
Python file.
4
2) Interactive Mode to Execute Python Program:
To execute the code directly in the interactive mode. You have to
open the interactive mode. Press the window button and type the
text “Python”. Click the “Python 3.7(32 bit) Desktop app” as given
below to open the interactive mode of Python.
You can type the Python code directly in the Python interactive
mode. Here, in the image below contains the print program of
Python.
Press the enter button to execute the print code of Python. The
output gives the text “Hello World!” after you press the enter
button.
Type any code of Python you want to execute and run directly on
interactive mode.
5
3) Using IDLE (Python GUI) to Execute Python Program:
Another useful method of executing the Python code. Use the
Python IDLE GUI Shell to execute the Python program on
Windows system.
Open the Python IDLE shell by pressing the window button of the
keyboard. Type “Python” and click the “IDLE (Python 3.7 32
bit)” to open the Python shell.
Create a Python file with .py extension and open it with the Python
shell. The file looks like the image given below.
6
It contains the simple Python code which prints the text “Hello
World!”. In order to execute the Python code, you have to open the
‘run’ menu and press the ‘Run Module’ option.
A new shell window will open which contains the output of the
Python code. Create your own file and execute the Python code
using this simple method using Python IDLE.
1.6 DEBUGGING
7
We can Change the flow of execution by using jump, continue
statements.
Example:
age=16
if age>18:
print ("you can vote”) # syntax error because of not using indentation
else
print ("you cannot vote”) #syntax error because of not using
indentation
8
1.6.4 Experimental Debugging:
One of the most important skills you will acquire is debugging.
Although it can be frustrating, debugging is one of the most
intellectually rich, challenging, and interesting parts of
programming.
Debugging is also like an experimental science. Once you have an
idea about what is going wrong, you modify your program and try
again.
For some people, programming and debugging are the same thing.
That is, programming is the process of gradually debugging a
program until it does what you want.
The idea is that you should start with a program that does
something and make small modifications, debugging them as you
go, so that you always have a working program.
Brackets [ ]:
Brackets are used to define mutable data types such as list or list
comprehensions.
9
Example:
To define a list with name as L1 with three elements 10,20 and 30
>>> L1 = [10,20,30]
>>> L1
[10,20,30]
Example:
Lookup the first characters of string
str>>>’mumbai’
>>> str [0]
‘m’
Example: To slice a string
>>> str [1:4]
‘umb’
Braces {}
Curly braces are used in python to define set or dictionary.
Example:
Create a set with three elements 10,20,30.
>>> s1 = {10,20,30}
>>> type(s1)
<class ‘set’>
Example:
Create a dictionary with two elements with keys, ‘rollno’ and ‘name’
>>> d1= {‘rollno’:101, ‘name’:’ Vivek’}
>>> type(d1)
<class ‘dict’>
1.9 SUMMARY
1.10 REFERENCES
www.journaldev.com
www.edureka.com
www.tutorialdeep.com
11
www.xspdf.com
Think Python by Allen Downey 1st edition.
Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
*****
12
2
VARIABLES AND EXPRESSION
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Values and Types
2.2.1 Variables
2.2.2 Variable Names and Keywords
2.3 Type conversion
2.3.1 Implicit Type Conversion
2.3.2 Explicit Type Conversion
2.4 Operators and Operands
2.5 Expressions
2.6 Interactive Mode and Script Mode
2.7 Order of Operations
2.8 Summary
2.9 References
2.10 Unit End Exercise
2.0 OBJECTIVES
2.1 INTRODUCTION
13
Python is case sensitive, so myVariable is not the same
as Myvariable which in turn is not the same as MyVariable.
With some exceptions, however, the programmer should avoid
assigning names that differ only by case since human readers can
overlook such differences.
A value is one of the basic things a program works with, like a letter or
a number. The values we have seen so far are 1, 2, and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello,
World!' is a string, so-called because it contains a “string” of letters.
Youcan identify strings because they are enclosed in quotation marks.
If you are not sure what type a value has, the interpreter can tell you.
>>>type ('Hello, World!')
<type ‘str’>
>>> type (17)
<type ‘int’>
Not surprisingly, strings belong to the type str and integers belong to
the type int. Less obviously, numbers with a decimal point belong to a
type called float, because these numbers are represented in a format
called floating-point.
>>> type (3.2)
<type ‘float’>
What about values like '17' and '3.2'? They look like numbers, but they
are in quotation marks like strings.
>>> type (‘17’)
<type ‘str’>
>>> type (‘3.2’)
<type ‘str’>
They are strings.
2.2.1 Variables:
One of the most powerful features of a programming language is the
ability to manipulate variables. A variable is a name that refers to a
value.
An assignment statement creates new variables and gives them values:
>>> message = ‘Welcome to University of Mumbai’
>>> n = 17
>>> pi = 3.1415926535897932
The above example makes three assignments. The first assigns a string
to a new variable named message, the second gives the integer 17 to n,
the third assigns the (approximate) value of π to pi.
14
A common way to represent variables on paper is to write the name
with an arrow pointing to the variable’s value.
>>> type(message)
<type ‘str’>
>>> type(n)
<type ‘int’>
>>> type(pi)
<type ‘float’>
15
Here is a list of the Python keywords. Enter any keyword to get more
help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
You might want to keep this list handy. If the interpreter complains
about one of your variable names and you don’t know why, see if it is
on this list.
The process of converting the value of one data type (integer, string, float,
etc.) to another data type is called type conversion. Python has two types
of type conversion.
Syntax:
<required_datatype>(expression)
17
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
Example:
4+5=9
Here 4 and 5 are Operands and (+), (=) signs are the operators.
They produce the output 9
Arithmetic Operators:
Operators Description
// Perform Floor division (gives integer value after division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division (Modulus)
** Perform exponent (raise to power)
Relational Operators:
Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
19
Relational Operators Examples:
>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>>5!=6
True
Logical Operators:
Operators Description
and Logical AND (When both conditions are true output will
be true)
or Logical OR (If any one condition is true output will be
true
not Logical NOT (Compliment the condition i.e., reverse)
Membership Operators:
Operators Description
20
Membership Operators Examples:
a=10
b=20
list= [10,20,30,40,50]
if (a in list):
print (“a is in given list”)
else:
print (“a is not in given list”)
if (b not in list):
print (“b is not given in list”)
else:
print (“b is given in list”)
Output:
>>>
a is in given list
b is given in list
Identity operators:
Operators Description
is Returns true if identity of two operands are same, else
false
is not Returns true if identity of two operands are not same,
else false.
21
2.5 EXPRESSIONS
The first line assigns a value to miles, but it has no visible effect. The
second line is an expression, so the interpreter evaluates it and displays the
result. So we learn that a marathon is about 42 kilometers.
But if you type the same code into a script and run it, you get no
output at all.
In script mode an expression, all by itself, has no visible effect. Python
actually evaluates the expression, but it doesn’t display the value
unless you tell it to:
miles = 26.2
print (miles * 1.61)
This behavior can be confusing at first.
A script usually contains a sequence of statements. If there is more
than one statement, the results appear one at a time as the statements
execute.
For example
22
print 1
x=2
print x
produces the output
1
2
The assignment statement produces no output.
2.8 SUMMARY
For each of the following expressions, write the value of the expression
and the type (of the value of
the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
24
Use the Python interpreter to check your answers
2.9 REFERENCES
*****
25
3
CONDITIONAL STATEMENTS,
LOOPING, CONTROL STATEMENTS
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Conditional Statements:
3.2.1 if statement
3.2.2 if-else,
3.2.3 if...elif...else
3.2.4 nested if –else
3.3 Looping Statements:
3.3.1 for loop
3.3.2 while loop
3.3.3 nested loops
3.4 Control statements:
3.4.1 Terminating loops
3.4.2 skipping specific conditions
3.5 Summary
3.6 References
3.7 Unit End Exercise
3.0 OBJECTIVES
3.1 INTRODUCTION
26
The boolean expression after if is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
27
You can chain together only simple statements, like assignments,
prints, and function calls.
3.2.1 if statement:
Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute
statement(s) only if the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the
indentation. The body starts with an indentation and the first
unindented line marks the end.
Python interprets non-zero values as True. None and 0 are
interpreted as False.
num = -1
if num > 0:
print (num, "is a positive number.")
print ("This is also always printed.")
28
3.2.2 if-else statement:
Syntax
if test expression:
Body of if
else:
Body of else
The if...else statement evaluates test expression and will execute
the body of if only when the test condition is True.
If the condition is False, the body of else is executed. Indentation is
used to separate the blocks.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print ("Positive or Zero")
else:
print ("Negative number")
Output:
Positive or Zero
In the above example, when num is equal to 3, the test expression
is true and the body of if is executed and the body of else is
skipped.
If num is equal to -5, the test expression is false and the body
of else is executed and the body of if is skipped.
If num is equal to 0, the test expression is true and body of if is
executed and body of else is skipped.
Example of if...elif...else:
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print ("Positive number")
elif num == 0:
print("Zero")
else:
print ("Negative number")
30
an appropriate message
This time we use nested if statement'''
num = float (input ("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print ("Positive number")
else:
print ("Negative number")
Output1:
Enter a number: 5
Positive number
Output2:
Enter a number: -1
Negative number
Output3:
Enter a number: 0
Zero
31
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The
body of for loop is separated from the rest of the code using
indentation.
Example:
print(range(10))
print(list(range(10)))
print (list (range (2, 8)))
print (list (range (2, 20, 3)))
Output:
range (0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
32
We can use the range () function in for loops to iterate through a
sequence of numbers. It can be combined with the len () function to
iterate through a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
city = ['pune', 'mumbai', 'delhi']
# iterate over the list using index
for i in range(len(city)):
print ("I like", city[i])
Output:
I like pune
I like mumbai
I like delhi
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts.
When the for-loop exhausts, it executes the block of code in
the else and prints No items left.
This for...else statement can be used with the break keyword to run
the else block only when the break keyword was not executed.
Example:
# program to display student's marks from record
student_name = 'Soyuj'
marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77}
33
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print ('No entry with that name found.')
Output:
No entry with that name found.
Here, we use a counter variable to print the string Inside loop three
times.
On the fourth iteration, the condition in while becomes False.
Hence, the else part is executed.
Syntax
for iterator in iterable:
for iterator2 in iterable2:
statement(s) of inside for loop
statement(s) of outside for loop
In this first for loop will initiate the iteration and later
second for loop will start its first iteration and till second for loop
complete its all iterations the control will not be given to
first for loop and statements of inside for loop will be executed.
Once all iterations of inside for loop are completed then statements
of outside for loop will be executed and next iteration from
first for loop will begin.
Output:
1 2 3 4 5 6 7 8 9 10 Table of 1
2 4 6 8 10 12 14 16 18 20 Table of 2
3 6 9 12 15 18 21 24 27 30 Table of 3
4 8 12 16 20 24 28 32 36 40 Table of 4
5 10 15 20 25 30 35 40 45 50 Table of 5
6 12 18 24 30 36 42 48 54 60 Table of 6
7 14 21 28 35 42 49 56 63 70 Table of 7
8 16 24 32 40 48 56 64 72 80 Table of 8
36
9 18 27 36 45 54 63 72 81 90 Table of 9
10 20 30 40 50 60 70 80 90 100 Table of 10
Output:
*
**
***
****
*****
******
*******
********
*********
In this first while loop will initiate the iteration and later
second while loop will start its first iteration and till
second while loop complete its all iterations the control will not be
given to first while loop and statements of inside while loop will be
executed.
Once all iterations of inside while loop are completed than
statements of outside while loop will be executed and next iteration
from first while loop will begin.
It is also possible that if first condition in while loop expression is
False then second while loop will never be executed.
Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999
Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222
38
3.4 CONTROL STATEMENTS:
Example:
for num in range (10):
if num > 5:
print ("stop processing.")
break
print(num)
Output:
0
1
2
3
4
5
stop processing.
39
Example of a continue statement:
for num in range (3, 8):
if num == 5:
continue
else:
print(num)
Output:
3
4
6
7
3.5 SUMMARY
3.7 REFERENCES
*****
41
UNIT II
4
FUNCTIONS
Unit Structure
4.0 Objectives
4.1 Introduction
4.2 Function Calls
4.3 Type Conversion Functions
4.4 Math Functions
4.5 Adding New Functions
4.6 Definitions and Uses
4.6.1 Flow of Execution
4.6.2 Parameters and Arguments
4.6.3 Variables and Parameters Are Local
4.6.4 Stack Diagrams
4.7 Fruitful Functions and Void Functions
4.8 Why Functions?
4.9 Importing with from, Return Values, Incremental Development
4.10 Boolean Functions
4.11 More Recursion, Leap of Faith, Checking Types
4.12 Summary
4.13 References
4.14 Unit End Exercise
4.0 OBJECTIVES
4.1 INTRODUCTION
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Example:
def greeting(name):
"""
This function greets to
the person passed in as
43
a parameter
"""
print ("Hello, " + name + ". Good morning!")
Output:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Pulling together the code fragments from the previous section, the
whole program looks like this:
def print_lyrics ():
print ("I'm a lumberjack, and I'm okay.")
print ("I sleep all night and I work all day.")
repeat_lyrics ()
In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which is
called the flow of execution.
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.
A function call is like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to
pick up where it left off.
When you read a program, you don’t always want to read from top
to bottom. Sometimes it makes more sense if you follow the flow
of execution.
49
Inside the function, the arguments are assigned to variables
called parameters. Here is an example of a user-defined function
that takes an argument.
def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce.
When the function is called, it prints the value of the parameter
twice.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice (17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359
For example
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
50
This function takes two arguments, concatenates them, and prints the
result twice. Here is an example that uses it:
>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
51
Each parameter refers to the same value as its corresponding
argument. So, part1 has the same value as line1, part2 has the same
value as line2, and bruce has the same value as cat.
If an error occurs during a function call, Python prints the name of
the function, and the name of the function that called it, and the
name of the function that called that, all the way back to __main__.
52
4.8 WHY FUNCTIONS?
53
>>> cos(pi)
-1.0
The advantage of importing everything from the math module is
that your code can be more concise.
The disadvantage is that there might be conflicts between names
defined in different modules, or between a name from a module
and one of your variables.
55
Following is an example of a recursive function to find the factorial
of an integer.
Factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 (denoted as 6!)
is 1*2*3*4*5*6 = 720.
Example of a recursive function
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
Output:
The factorial of 3 is 6
56
3 * 2 * factorial (1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
4.12 SUMMARY
1. Python provides a built-in function called len that returns the length
of a string, so the value of len('allen') is 5.
Write a function named right_justify that takes a string named s as
a parameter and prints the string with enough leading spaces so that
the last letter of the string is in column 70 of the display.
>>> right_justify('allen')
allen
2. Write a Python function to sum all the numbers in a list. Go to the
editor
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
3. Write a Python program to reverse a string
Sample String : "1234abcd"
Expected Output : "dcba4321"
4. Write a Python function to calculate the factorial of a number (a
non-negative integer). The function accepts the number as an
argument.
5. Write a Python program to print the even numbers from a given
list.
Sample List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result: [2, 4, 6, 8]
57
4.13 REFERENCES
https://www.tutorialsteacher.com/python/math-module
https://greenteapress.com/thinkpython/html/thinkpython004.html
https://beginnersbook.com/
https://www.programiz.com/python-programming/recursion
www.journaldev.com
www.edureka.com
www.tutorialdeep.com
www.xspdf.com
Think Python by Allen Downey 1st edition.
*****
58
5
STRINGS
Unit Structure
5.1 A String is a Sequence
5.2 Traversal with a for Loop
5.3 String Slices
5.4 Strings Are Immutable
5.5 Searching
5.6 Looping and Counting
5.7 String Methods
5.8 The in Operator
5.9 String Comparison
5.10 String Operations
5.11 Summary
5.12 Questions
5.13 References
5.0 OBJECTIVES
>>>food = 'roti'
>>>letter = food[1]
59
in brackets is called an index. The index indicates which character in the
sequence you required.
Example.
‘I want to read book’. This is a string, It has been surrounded in single
quotes.
You can also surround them with triple quotes (groups of 3 single quotes
or double quotes).
“””I want to read book’”””
”’ I want to read book’”’
Or using backslashes.
>> ‘Thank\
Good Morning Sir !’
‘ThanksGood Morning Sir!’
You cannot start a string with a single quote and end it with a double
quote..
But if you surround a string with single quotes and also want to use single
quotes as part of the string, you have to escape it with a backslash (\).
‘Send message to Madam\’s son ’
You can also do this with double-quotes. If you want to ignore escape
sequences, you can create a raw string by using an ‘r’ or ‘R’ prefix with
the string.
>>> str(567)
Output:
‘567’
>>> str('Shri')
Output:
‘Shri’
We have previously seen that the for statement can iterate over the
items of a sequence (a list of names in the case below).
Recall that the loop variable takes on each value in the sequence of
names. The body is performed once for each name. The same was true for
the sequence of integers created by the range function.
Since a string is simply a sequence of characters, the for loop iterates over
each character automatically.
for achar in "Go Spot Go":
print(achar)
61
The loop variable achar is automatically reassigned each character
in the string “Go Spot Go”. We will refer to this type of sequence iteration
as iteration by item. Note that it is only possible to process the characters
one at a time from left to right.
s = "python rocks"
for ch in s:
print("HELLO")
Ans - Yes, there are 12 characters, including the blank.
s = "python rocks"
for ch in s[3:8]:
print("HELLO")
Ans - Yes, The blank is part of the sequence returned by slice
The slicing starts with the start_pos index (included) and ends at
end_pos index (excluded). The step parameter is used to specify the steps
to take from start to end index.
Python String slicing always follows this rule: s[:i] + s[i:] == s for any
index ‘i’.
s = 'HelloWorld'
print(s[:])
print(s[::])
62
Output:
HelloWorld
HelloWorld
Note that since none of the slicing parameters were provided, the substring
is equal to the original string.
Output:
Hello
Llo
Note that index value starts from 0, so start_pos 2 refers to the third
character in the string.
We can reverse a string using slicing by providing the step value as -1.
s = 'HelloWorld'
reverse_str = s[::-1]
print(reverse_str)
Output:
dlroWolleH
Let’s look at some other examples of using steps and negative index
values.
s1 = s[2:8:2]
print(s1)
Output:
loo
63
Output:
lroWoll
You will get a mistake message when you need to change the substance of
the string.
Traceback (latest call last):
Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in
<module>
name_1[0] = 'T'
TypeError: 'str' object doesn't uphold thing task
Arrangement
One potential arrangement is to make another string object with vital
alterations:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("name_1 = ", name_1, "and name_2 = ", name_2)
64
name_1 = Aarun and name_2 = Tarun
To watch that they are various strings, check with the id() work:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_2 = 2342565669888
To see more about the idea of string permanence, think about the
accompanying code:
name_1 = "Aarun"
name_2 = "Aarun"
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_1 with new value = 2342565668656
5.5 SEARCHING
Linear Search:
Example
def linear_search(values, search_for):
search_at = 0
search_res = False
65
# Match the value with each data element
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = True
else:
search_at = search_at + 1
return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91))
Output:
When the above code is executed, it produces the following result −
True
False
Interpolation Search:
Example
There is a specific formula to calculate the middle position which is
indicated in the program below −
def intpolsearch(values,x ):
idx0 = 0
idxn = (len(values) - 1)
while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:
# Find the mid point
mid = idx0 +\
int(((float(idxn - idx0)/( values[idxn] - values[idx0]))
* ( x - values[idx0])))
# Compare the value at mid point with search value
if values[mid] == x:
66
return "Found "+str(x)+" at index "+str(mid)
if values[mid] < x:
idx0 = mid + 1
return "Searched element not in the list"
l = [2, 6, 11, 19, 27, 31, 45, 121]
print(intpolsearch(l, 2))
Output:
Found 2 at index 0
The following program counts the number of times the letter “r” appears
in a string:
word = 'raspberry'
count = 0
for letter in word:
if letter == 'r':
count = count + 1
print(count)
Output:
The letter t appears 3 times in "peanut butter".
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the
original string.
67
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in
a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the
position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the
position of where it was found
isalpha() Returns True if all characters in the string are in the
alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower
case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isupper() Returns True if all characters in the string are upper
case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three
parts
replace() Returns a string where a specified value is replaced with
a specified value
rfind() Searches the string for a specified value and returns the
last position of where it was found
rindex() Searches the string for a specified value and returns the
last position of where it was found
rjust() Returns a right justified version of the string
rsplit() Splits the string at the specified separator, and returns a
list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
68
swapcase() Swaps cases, lower case becomes upper case and vice
versa
Note: All string methods returns new values. They do not change the
original string.
Here “x” is the element and “y” is the sequence where membership is
being checked.
We can use the “in” operator with Strings and Tuples too because they are
sequences.
>>> name='JournalDev'
>>> 'D' in name
True
>>> 'x' in name
False
>>> primes=(2,3,5,7,11)
>>> 3 in primes
True
>>> 6 in primes
False
It looks like the Python “in” operator looks for the element in the
dictionary keys.
70
3. Comparing two strings using the sorted() method:
If we wish to compare two strings and check for their equality even if the
order of characters/words is different, then we first need to use sorted()
method and then compare two strings.
str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if sorted(str1) == sorted(str2):
print ("First and second strings are equal.")
else:
print ("First and second strings are not the same.")
Output:
Enter the first String: Engineering Discipline
Enter the second String: Discipline Engineering
First and second strings are equal.
Output:
True
Comparision result = False
In the above example, str1 is str3 returns False because object str3 was
created differently.
Example
"Python" or 'Python'
Code
SingleQuotes ='Python in Single Quotes'
DoubleQuotes ="Python in Double Quotes"
print(SingleQuotes)
print(DoubleQuotes)
Output:
Python in Single Quotes
Python in Double Quotes
This function is used for displaying the output or result on the user screen.
Syntax
print('Text or Result') or print("Text or Result')
Indexing in String
It returns a particular character from the given string.
Syntax
getChar = a[index]
message = "Hello, Python!"
If I want to fetch the characters of the 7th index from the given string.
Syntax
print(string[index])
Code
print(message[7])
72
Output:
P
5.11 SUMMARY
5.12 QUESTIONS
73
Sample String given: 'reboot'
1. Write a Python program to change a given string to a new string where
the first and last chars have been exchanged.
2. Write a Python program to count the occurrences of each word in a
given sentence
3. Write Python program to Check all strings are mutually disjoint
4. Write a program to find the first and the last occurence of the letter 'o'
and character ',' in "Good, Morning".
5. Write a program to check if the word 'open' is present in the "This is
open source software".
6. Write a program to check if the letter 'e' is present in the word
'Welcome'.
5.13 REFERENCES
1. https://developers.google.com/edu/python/strings
2. https://docs.python.org/3/library/string.html
3. https://www.programiz.com/python-programming/string
4. http://ww2.cs.fsu.edu/~nienaber/teaching/python/lectures/sequence-
string.html
5. https://www.tutorialsteacher.com/python/python-string
6. https://techvidvan.com/tutorials/python-strings/
7. http://anh.cs.luc.edu/handsonPythonTutorial/objectsummary.html
8. https://docs.python.org/3/library/stdtypes.html
9. https://www.programiz.com/python-programming/methods/string
10. https://www.w3schools.com/python/python_ref_string.asp
11. https://www.tutorialspoint.com/python_text_processing/python_string
_immutability.htm
12. https://web.eecs.utk.edu/~azh/blog/pythonstringsaremutable.html
*****
74
UNIT III
6
LIST
Unit structure
6.1 Objectives
6.2 Values and Accessing Elements
6.3 Lists are mutable
6.4 Traversing a List
6.5 Deleting elements from List
6.6 Built-in List Operators
6.7 Concatenation
6.8 Repetition
6.9 In Operator
6.10 Built-in List functions and methods
611 Summary
6.12 Exercise
6.13 References
6.1 OBJECTIVES
The list is most likely versatile data type available in the Python
which is can be written as a list of comma-separated values between
square brackets. The Important thing about a list is that items in the list
need not be of the same type.
75
Similar to a string indices, A list indices start from 0, and lists can
be sliced, concatenated.
To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index. For
example –
list1 =['jack','nick',1997,5564];
list2 =[1,2,3,4,5,6,7];
print"list1[0]: ", list1[0]
print"list2[1:5]: ", list2[1:5]
output −
list1[0]: jack
list2[1:5]: [2, 3, 4, 5]
Example:
Output:.
The mostly common way to traverse the elements of list with for loop. The
syntax is the same as for strings:
76
for color in cheeses:
print(color)
This works well if you only need to read the element of list. But if you
want to do write or update the element, you need the indices. A common
way to do that is to combine the functions range and len:
for i in range(len(number)):
output −
red
white
blue
green
To delete a list element, you can use either the del statement, del removes the
item at a specific index, if you know exactly which element(s) you are deleting
or the remove() method if you do not know. For example –
print(list1)
del list[2]
print(list1)
output −.
Example2:
Output:
[50, 70, 80]
77
One other method from removing elements from a list is to take a slice
of the list, which excludes the index or indexes of the item or items
you are trying to remove. For instance, to remove the first two items of
a list, you can do
list = list[2:]
Concatenation
Indexing Repetition
List Operation
Membership
Slicing
Testing
1. Concatenation:
Example:
print(list1 + list2)
Output:
Example:
print(list1 * list2
Output:
3. Membership Operator:
Example:
Output:
False
True
True
False
4. Indexing:
Indexing is nothing but there is an index value for each tem present
in the sequence or list.
79
Example:
print(list1[4])
Output:
50
5. Slicing operator:
Syntax: list1[start:stop:step]
Example:
list1 = [10, 20, 30, 40, 50, 60, 70]
print(list1[3:7])
Output:
6.7 CONCATENATION
print(str(result))
Output:
Naive method:
In the Naive method, a for loop is used to be traverse the second list.
After this, the elements from the second list will get appended to the first
list. The first list of results out to be the concatenation of the first and the
second list.
Example:
for x in list2 :
list1.append(x)
Output:
Before Concatenation:
After Concatenation:
List comprehension:
It uses the for loop to process and traverses a list in the element-wise
fashion. The below inline is for-loop is equivalent to a nested for loop.
81
Example:
Output:
Concatenated list:
Extend() method:
Syntax:
list.extend(iterable)
Example:
list1.extend(list2)
All the elements of the list2 get appended to list1 and thus the list1 gets
updated and results as output.
Output:
‘*’ operator:
Python’s '*' operator can be used for easily concatenate the two lists in
Python.
82
The ‘*’ operator in Python basically unpacks the collection of items at
the index arguments.
The statement *list would replace by the list with its elements on the index
positions. So, it unpacks the items of the lists.
Example:
Output:
Output:
Concatenated list:
Itertools.chain() method:
Example:
import itertools
83
list2 = [20, 30, 42]
Output:
Concatenated list:
6.8 REPETITION
Example:
number = (0,) * 5 # we use the comma to denote that this is a single valued tuple
and not an ‘#’expression
Output
print numbers
(0, 0, 0, 0, 0)
[0] is a tuple with one element, 0. Now repetition of the operator it will
makes 5 copies of this tuple and joins them all together into a single tuple.
Another example using multiple elements in the tuple.
Example:
numbers = (0, 1, 2) * 3
Output
print numbers
(0, 1, 2, 0, 1, 2, 0, 1, 2)
6.9 IN OPERATOR
84
Example:
my_list = [5, 1, 8, 3, 7]
print(8 in my_list)
print(0 in my_list)
Output:
True
False
Note: Note that in operator against dictionary checks for the presence of
key.
Example:
my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}
print('name' in my_dict)
Output:
True
1. Built-in function:
85
2. Built-in methods:
6.11 SUMMARY
86
6.12 QUESTIONS
6.13 REFERENCES
1. https://python.plainenglish.io/python-list-operation-summary-
262f40a863c8?gi=a4f7ce4740e9
2. https://howchoo.com/python/how-to-use-list-comprehension-in-python
3. https://intellipaat.com/blog/tutorial/python-tutorial/python-list-
comprehension/
4. https://programmer.ink/think/summary-of-python-list-method.html
5. https://www.geeksforgeeks.org/python-list/
6. https://enricbaltasar.com/python-summary-methods-lists/
7. https://developpaper.com/super-summary-learn-python-lists-just-this-
article-is-enough/
8. https://www.programiz.com/python-programming/methods/list
9. https://www.hackerearth.com/practice/python/working-with-
data/lists/tutorial/
10. https://data-flair.training/blogs/r-list-tutorial/
*****
87
7
TUPLES AND DICTIONARIES
Unit Structure
7.1 Objectives
7.2 Tuples
7.2 Accessing values in Tuples
7.3 Tuple Assignment
7.4 Tuples as return values
7.5 Variable-length argument tuples
7.6 Basic tuples operations
7.7 Concatenation
7.8 Repetition
7.9 In Operator
7.10 Iteration
7.11 Built-in Tuple Functions
7.12 Creating a Dictionary
7.13 Accessing Values in a dictionary
7.14 Updating Dictionary
7.15 Deleting Elements from Dictionary
7.16 Properties of Dictionary keys
7.17 Operations in Dictionary
7.18 Built-In Dictionary Functions
7.19 Built-in Dictionary Methods
7.20 Summary
7.21 Exercise
7.22 References
7.1 OBJECTIVES
88
7.2 TUPLES
Creating a Tuple:
A tuple can have any number of the items and they may be a
different types (integer, float, list, string, etc.).
Example:
# Empty tuple
tuple = ()
print(tuple)
tuple = (1, 2, 3)
print(tuple)
print(tuple)
# nested tuple
print(tuple)
89
Output:
()
(1, 2, 3)
print(tuple)
a, b, c = tuple
print(a) #3
print(b) # 4.6
print(c) # dog
Output:
( 3, 2.6, 'color')
2.6
color
There are various ways in which we can access the elements of a tuple.
1. Indexing:
90
The index must be an integer, so we cannot use float or other
types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.
tuple = ('a','b','c','d','e','f')
print(tuple[0]) # 'a'
print(tuple[5]) # 'f'
# print(tuple[6])
# tuple[2.0]
# nested tuple
# nested index
print(tuple[0][3]) # 'o'
print(tuple[1][1]) #4
Output:
a
2. Negative Indexing:
The index of -1 refers to the last item, -2 to the second last item and so on.
Example:
tuple = ('a','b','c','d','e','f')
91
# Output: 'f'
print(tuple[-1])
# Output: 'a'
print(tuple[-6])
Output:
3. Slicing:
We can access the range of items from the tuple by using the
slicing operator colon:
Example:
tuple = ('a','b','c','d','e','f','g','h','i')
print(tuple[1:4])
print(tuple[:-7])
print(tuple[7:])
# Output: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
print(tuple[:])
Output:
('b', 'c', 'd')
('a', 'b')
92
('h', 'i')
Example:
x, y = tuple
Output:
x
'red'
'blue'
m = [ 'red', 'blue' ]
x = m[0]
y = m[1]
Output:
x
'red'
'blue'
For example, we could write a function that returns both the area and the
circumference of a circle of radius.
Example:
def cirlce_info(r):
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(cirlce_info(10))
Output:
(62.8318, 314.159)
print args
The gather parameter can have any name you like, but args is
conventional. Here’s how the function works:
t = (7, 3)
divmod(t)
max(1,2sum(1,2,3)
1. Membership:
We can apply the ‘in’ and ‘not in’ operator on the items. This tells us whether
they belong to the tuple.
'a' in tuple("string")
Output:
False
Output:
True
2. Concatenation:
(1,2,3)+(4,5,6)
Output:
(1, 2, 3, 4, 5, 6)
3. Logical:
(1,2,3)>(4,5,6)
95
Output:
False
(1,2)==('1','2')
Output:
False
4. Identity:
Remember the ‘is’ and ‘is not’ operators we discussed about in our
tutorial on Python Operators? Let’s try that on tuples.
a=(1,2)
(1,2) is a
Output:
That did not make sense, did it? So what really happened? Now, in
Python, two tuples or lists don't have the same identity. In other words,
they are two different tuples or lists. As a result, it returns False.
7.8 CONCATENATION
In our first example, we will use the sum() function to concatenate two
tuples and result in a single tuple.Let us jump to example:
tupleint= (1,2,3,4,5,6)
langtuple = ('C#','C++','Python','Go')
Output:
concatenate of tuples
96
= (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go')
tupleint= (1,2,3,4,5,6),
langtuple = ('C#','C++','Python','Go'),
Output:
concatenate of tuples
tupleint= (1,2,3,4,5,6)
langtuple = ('C#','C++','Python','Go')
tuples_concatenate = tupleint+langtuple
Output:
This example, we have the two tuple tuple int and lang tuple. Now
We are using the comma(,) end of the each tuple to the concatenate them
97
into a nested tuple. We are concatenating these tuples into a nested tuple
as we can see in the resulting output.
tupleint= (1,2,3,4,5,6),
langtuple = ('C#','C++','Python','Go'),
tuples_concatenate = tupleint+langtuple
Output:
concatenate of tuples
7.9 REPETITION
Syntax:
<tuple_variable_name1> * N
N * <tuple_variable_name1>
Input Parameters:
Example:
data=(1,2,3,'a','b')
98
Output:
7.10 IN OPERATOR
The Python in operator lets you loop through all to the members of
the collection and check if there's a member in the tuple that's equal to the
given item.
Example:
my_tuple = (5, 1, 8, 3, 7)
print(8 in my_tuple)
print(0 in my_tuple)
Output:
True
False
Example:
Output:
True
Example:
print("sample" in string)
Output:
True
It can be uses in the many of other places and how it works in the
those scenarios of varies a lot. This is the how in works in tuples. It start
99
the comparing references of the objects from the first one till it either finds
that the object in the tuple or reaches in the end of the tuple.
7.11 ITERATION
There are many ways to iterate through the tuple object. For
statement in Python has a variant which traverses a tuple till it is
exhausted. It is equivalent to for each statement in Java. Its syntax is –
for var in tuple:
stmt1
stmt2
Example:
T = (10,20,30,40,50)
for var in T:
print (T.index(var),var)
Output:
0 10
1 20
2 30
3 40
4 50
Comparison:
100
If we reached to the end of one of the lists, the longer list is a
"larger." If both are list are same it returns 0.
tuple2 = ('1','2','3')
cmp(tuple1, tuple2)
Out: 1
cmp(tuple2, tuple1)
Out: -1
cmp(tuple1, tuple3)
Out: 0
Tuple Length:
len(tuple1)
Out: 5
Max of a tuple:
The function min returns the item from the tuple with the min value:
min(tuple1)
Out: 'a'
min(tuple2)
Out: '1'
list = [1,2,3,4,5]
tuple(list)
Out: (1, 2, 3, 4, 5)
Tuple concatenation:
tuple1 + tuple2
Creating a Dictionary:
The values can belong to the any of data type and they can repeat,
but the keys are must remain the unique.
To print the dictionary contents, we can use the Python's print() function
and pass the dictionary name as the argument to the function. For
example:
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
print(dict_sample)
Output:
{'Company': 'Toyota', 'model': 'Premio', 'year': 2012}
102
7.14 ACCESSING VALUES IN A DICTIONARY
"Company": "Toyota",
"model": "Premio",
"year": 2012
x = dict_sample["model"]
print(x)
Output:
Premio
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
dict_sample["year"] = 2014
print(dict_sample)
Output:
In this example you can see that we have updated the value for the key
"year" from the old value of 2012 to a new value of 2014.
103
7.16 DELETING ELEMENTS FROM DICTIONARY
The del keyword can be used to remove the element with the
specified key. For example:
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
del dict_sample["year"]
print(dict_sample)
Output:
Output:
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
dict_sample.pop("year")
print(dict_sample)
"Company": "Toyota",
"model": "Premio",
"year": 2012
dict_sample.popitem()
print(dict_sample)
Output:
The last entry into the dictionary was "year". It has been removed
after calling the popitem() function.
"Company": "Toyota",
"model": "Premio",
"year": 2012
del dict_sample
print(dict_sample)
Output:
The code returns an error. The reason is we are trying to access the
an dictionary which is doesn't exist since it is has been deleted.
105
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
dict_sample.clear()
print(dict_sample)
Output:
{}
The code is returns an empty dictionary since all the dictionary elements
have been removed.
(a)More than one of the entry per key not allowed. Which means that no
duplicate key isallowed. When the duplicate keys are encountered during
the assignment, And, the last assignment wins.
For example:
Output:
dict[‘Name’]: Manni
(b) Keys must be immutable. Which mean by you can use strings, And the
numbers or tuples as dictionary keys but something like [‘key’] is not
allowed. Following is a simple:
106
Output:
x = {}
access an element
x['two']
x.keys()
x.values()
add an entry
x["four"]=4
change an entry
x["one"] = "uno"
delete an entry
del x["four"
make a copy
y = x.copy()
107
x.clear()
number of items
z = len(x)
z = x.has_key("one")
if "two" not in x:
print "Two not found"
if "three" in x:
del x['three']
1. len():
len(dict4)
Output
3
len({})
any({False:False,'':''})
108
2. any():
Output:
False
Output:
any({True:False,"":""})
True
3
. all():
Unlike the any() function, all() returns True only if all the keys in the
dictionary have a Boolean value of True.
Output:
all({1:2,2:'',"":3})
False
4. sorted():
Like it is with lists and tuples, the sorted() function returns a sorted
sequence of the keys in the dictionary. The sorting is in ascending order,
and doesn’t modify the original Python dictionary.
dict4={3:3,1:1,4:4}
Output:
[1, 3, 4]
This function returns the keys in a sorted list. To prove this, let’s see what
the type() function returns.
109
This proves that sorted() returns a list.
{3: 3, 1: 1, 4: 4}
dict4
type(sorted(dict4))
1. keys():
dict_keys([3, 1, 4])
Output:
2. values():
Likewise, the values() method returns a list of values in the dictionary.
Output:
dict_values([3, 1, 4])
3. items()
This method returns a list of key-value pairs.
Output:
dict_items([(3, 3), (1, 1), (4, 4)])
7.20 SUMMARY
Tuples: In Python, tuples are structured and accessed based on
position. A Tuple is a collection of Python objects separated by commas.
In some ways a tuple is similar to a list in terms of indexing, nested
objects and repetition but a tuple is absolute unlike lists that are variable.
In Python it is an unordered collection of data values, used to store data
values like a map, which unlike other data types that hold only single
value as an element. Tuples are absolute lists. Elements of a list can be
modified, but elements in a tuple can only be accessed, not modified. The
110
name tuple does not mean that only two values can be stored in this data
structure.
Dictionaries: Dictionaries in Python are structured and accessed using
keys and values. Dictionaries are defined in Python with curly braces { } .
Commas separate the key-value pairs that make up the dictionary.
Dictionaries are made up of key and/or value pairs. In Python, tuples are
organized and accessed based on position. The location of a pair of keys
and values stored in a Python dictionary is unrelated. Key value is
provided in the dictionary to make it more optimized. A Python
dictionary is basically a hash table. In some languages, they might be
mentioned to an associative arrays. They are indexed with keys, which
can be any absolute type.
7.21 QUESTIONS
1. Let list = [’a’, ’b’, ’c’,’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:]
2. State the difference between lists and dictionary
3. What is the benefit of using tuple assignment in Python?
4. Define dictionary with an example
5. Write a Python program to swap two variables
6. Define Tuple and show it is immutable with an example
7. Create tuple with single element
8. How can you access elements from the dictionary
9. Write a Python program to create a tuple with different data types.
10. Write a Python program to unpack a tuple in several variables
7.22 REFERENCES
1. https://www.geeksforgeeks.org/differences-and-applications-of-list-
tuple-set-and-dictionary-in-python/
2. https://problemsolvingwithpython.com/04-Data-Types-and-
Variables/04.05-Dictionaries-and-Tuples/
3. https://problemsolvingwithpython.com/04-Data-Types-and-
Variables/04.05-Dictionaries-and-Tuples/
4. https://ncert.nic.in/textbook/pdf/kecs110.pdf
5. https://python101.pythonlibrary.org/chapter3_lists_dicts.html
6. https://www.programmersought.com/article/26815189338/
7. https://www.javatpoint.com/python-tuples
8. https://cloudxlab.com/assessment/displayslide/873/python-
dictionaries-and-tuples
9. https://medium.com/@aitarurachel/data-structures-with-lists-tuples-
dictionaries-and-sets-in-python-612245a712af
10. https://www.w3schools.com/python/python_tuples.asp
*****
111
8
FILES AND EXCEPTIONS
Unit Structure
8.1 Objective
8.2 Text Files
8.3 The File Object Attributes
8.4 Directories
8.5 Built-in Exceptions
8.6 Handling Exceptions
8.7 Exception with Arguments
8.8 User-defined Exceptions
8.9 Summary
8.10 Exercise
8.11 References
8.1 OBJECTIVE
Now we will learn about various ways to read text files in Python.
The following shows how to read all texts from the readme.txt file into a
string:
with open('readme.txt') as f:
lines = f.readlines()
To read the text file in the Python, you have to follow these steps:
112
Firstly, you have to open the text file for reading by using the
open() method.
Second, you have to read the text from the text file using the file
read(), readline(), or readlines() method of the file object.
Third, you have to close the file using the file close() method.
1) open() function
The open() function has many parameters but you’ll be focusing on the
first two.
open(path_to_file, mode)
The path to the file parameter is specifies the path to the text file.
If the file is in the same folder as is program, you have just need to
specify the file name. Otherwise, you have need to specify the path to the
file.
Specify the path to the file, you have to use the forward-slash ('/')
even if you are working in Windows.
The following table shows available modes for opening a text file:
Mode Description
'r' Open for text file for reading text
'w' Open a text file for writing text
'a' Open a text file for appending text
f = open('the-zen-of-python.txt','r')
The open() function returns a file object which you will use to read
text from a text file.
The file object provides you with three methods for reading text from a
text file:
113
read() – read all text from a file into a string. This method is useful if you
have a small file and you want to manipulate the whole text of that file.
readline() – read the text file line by line and return all the lines as strings.
readlines() – read all the lines of the text file and return them as a list of
strings.
3) close() method:
The file that you open will remain open until you close it using the
close() method.
It’s important to close the file that is no longer in use. If you don’t
close the file, the program may crash or the file would be corrupted.
The following shows how to call the close() method to close the file:
f.close()
The following example illustrates how to use the read() method to read all
the contents of the the-zen-of-python.txt file into a string:
with open('the-zen-of-python.txt') as f:
contents = f.read()
print(contents)
Output:
...
114
The following example uses the readlines() method to read the text file
and returns the file contents as a list of strings:
lines = []
with open('the-zen-of-python.txt') as f:
lines = f.readlines()
count = 0
count += 1
Output:
...
Once a file is opened and you have one file object, you can get
various information related to that file. Here is a list of all attributes
related to file object:
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true
otherwise.
Example
# Open a file
fo = open(“foo.txt”, “wb”)
115
This produces the following result:
Opening mode : wb
Softspace flag : 0
8.4 DIRECTORIES
To find out which directory in python you are currently in, use the
getcwd() method.
os.getcwd()
Output:
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’
Cwd is for current working directory in python. This returns the path of
the current python directory as a string in Python.
Output:
b’C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32′
type(os.getcwd())
<class 'str'>
To render it properly, use the Python method with the print statement.
print(os.getcwd())
116
Output:
This takes one argument- the path to the directory to which to change.
Output:
Output:
We can also create new python directories with the mkdir() method. It
takes one argument, that is, the path of the new python directory to create.
os.mkdir('Christmas Photos')
os.listdir()
Output:
os.listdir()
Output:
[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘Christmas
2017’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse
117
Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for
trip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’,
‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]
os.chdir('C:\\Users\\lifei\\Desktop\\Christmas 2017')
os.listdir()
Output:
[‘Readme.txt’]
print(dir(locals()['__builtins__']))
follows:
118
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or
global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system
related error.
OverflowError Raised when the result of an arithmetic
operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to
access a garbage collected referent.
RuntimeError Raised when an error does not fall under any
other category.
StopIteration Raised by next() function to indicate that there
is no further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is
encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent
tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied
to an object of incorrect type.
UnboundLocalError Raised when a reference is made to a local
variable in a function or method, but no value
has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or
decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs
during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs
during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs
during translating.
ValueError Raised when a function gets an argument of
correct type but improper value
ZeroDivisionError Raised when the second operand of division or
modulo operation is zero.
If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of
code which handles the problem as elegantly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:
119
try:
......................
except ExceptionI:
except ExceptionII:
......................
else:
You can also provide a generic except clause, which handles any
exception.
The else-block is a good place for code that does not need the try:
block's protection.
Example:
This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all:
try:
fh = open("testfile", "w")
except IOError:
else:
120
print "Written content in the file successfully"
fh.close()
Example 1:
try:
b = float(100 + 50 / 0)
Output:
division by zero
class MyError(Exception):
# Constructor or Initializer
self.value = value
def __str__(self):
return(repr(self.value))
try:
Output:
'This is the Argument
'Some Error data'
class MyError(Exception):
# Constructor or Initializer
122
self.value = value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
Ouput:
8.9 SUMMARY
Files: Python supports file handling and allows users to handle files for
example, to read and write files, along with many other file handling
options, to operate on files. The concept of file handling has justified by
various other languages, but the implementation is either difficult.
Python delights file differently as text or binary and this is significant.
Each line of code includes a sequence of characters and they form text
file. Each line of a file is ended with a special character like comma {,}.
It ends the current line and expresses the interpreter a new one has
started. In Python a file is a contiguous set of bytes used to store data.
This data is organized in a precise format and can be anything as simple as
a text file. In the end, these byte files are then translated into
binary 1 and 0 for simple for processing. In Python, a file operation takes
place in the order like Open a file then Read or write and finally close the
file.
123
8.10 QUESTIONS
8.11 REFERENCES
1. https://www.learnpython.org/
2. https://www.packtpub.com/tech/python
3. https://www.softcover.io/read/e4cd0fd9/conversational-
python/ch6_files_excepts
4. https://docs.python.org/3/library/exceptions.html
5. https://www.tutorialspoint.com/python/python_exceptions.htm
6. https://www.w3schools.com/python/python_try_except.asp
7. https://www.geeksforgeeks.org/python-exception-handling/
8. https://www.analyticsvidhya.com/blog/2020/04/exception-handling-
python/
9. https://www.programiz.com/python-programming/file-operation
10. https://www.geeksforgeeks.org/file-handling-python/
11. https://realpython.com/read-write-files-python/
12. https://www.guru99.com/reading-and-writing-files-in-python.html
*****
124