Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
78 views

PythonProgrammingNotes Unit1&2

The document discusses the basics of the Python programming language including its history, features, installation, running programs, debugging syntax errors and more. It provides details on how to execute Python code using the command prompt, interactive mode and IDLE GUI. The document also differentiates between brackets, braces and parentheses.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

PythonProgrammingNotes Unit1&2

The document discusses the basics of the Python programming language including its history, features, installation, running programs, debugging syntax errors and more. It provides details on how to execute Python code using the command prompt, interactive mode and IDLE GUI. The document also differentiates between brackets, braces and parentheses.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

UNIT I

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

After reading through this chapter, you will be able to –


 To understand and use the basic of python.
 To understand the history and features of python programming.
 To understand the installation of python.
 To handle the basis errors in python.
 To understand the difference between brackets, braces and
parenthesis.

1.1 INTRODUCTION: THE PYTHON


PROGRAMMING LANGUAGE

 Python is an object-oriented, high level language, interpreted,


dynamic and multipurpose programming language.
 Python is not intended to work on special area such as web
programming. That is why it is known as multipurpose because it
can be used with web, enterprise, 3D CAD etc.

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

 Python was first introduced by Guido Van Rossum in 1991 at the


National Research Institute for Mathematics and Computer
Science, Netherlands.
 Though the language was introduced in 1991, the development
began in the 1980s. Previouslyvan Rossum worked on the ABC
language at CentrumWiskunde & Informatica (CWI) in
the Netherlands.
 The ABC language was capable of exception handling and
interfacing with the Amoeba operating system. Inspired by the
language, Van Rossum first tried out making his own version of it.
 Python is influenced by programming languages like: ABC
language, Modula-3, Python is used for software development at
companies and organizations such as Google, Yahoo, CERN,
Industrial Light and Magic, and NASA.
 Why the Name Python?
 Python developer, Rossum always wanted the name of his new
language to be short, unique, and mysterious.
 Inspired by Monty Python’s Flying Circus, a BBC comedy series,
he named it Python.

1.3 FEATURES

There are a lot of features provided by python programming language


as follows

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.

2. Open Source and Free:


 Python is an open-source programming language which means that
anyone can create and contribute to its development.
 Python has an online forum where thousands of coders gather daily
to improve this language further. Along with this Python is free to
download and use in any operating system, be it Windows, Mac or
Linux.
2
3. Support for GUI:
 GUI or Graphical User Interface is one of the key aspects of any
programming language because it has the ability to add flair to
code and make the results more visual.
 Python has support for a wide array of GUIs which can easily be
imported to the interpreter, thus making this one of the most
favorite languages for developers.

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.

7. Large Standard Library:


 Out of the box, Python comes inbuilt with a large number
of libraries that can be imported at any instance and be used in a
specific program.
 The presence of libraries also makes sure that you don’t need to
write all the code yourself and can import the same from those that
already exist in the libraries.

1.4 INSTALLING PYTHON

 To install Python, firstly download the Python distribution from


official website of python (www.python.org/ download).
 Having downloaded the Python distribution now execute it.
 Setting Path in Python:

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.

1.5 RUNNING PYTHON PROGRAM:

There are different ways of working in Python:

1) How to Execute Python Program Using Command Prompt:


If you want to create a Python file in .py extension and run. You can
use the Windows command prompt to execute the Python code.

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.

 To execute the Python file, you have to use the keyword


‘Python’ followed by the file name with extension.py See the
example given in the screen above with the output of the 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

 Debugging means the complete control over the program


execution. Developers use debugging to overcome program from
any bad issues.
 debugging is a healthier process for the program and keeps the
diseases bugs far away.
 Python also allows developers to debug the programs using pdb
module that comes with standard Python by default.
 We just need to import pdb module in the Python script. Using pdb
module, we can set breakpoints in the program to check the current
status

7
 We can Change the flow of execution by using jump, continue
statements.

1.6.1 Syntax Error:


 Errors are the mistakes or faults performed by the user which
results in abnormal working of the program.
 However, we cannot detect programming errors before the
compilation of programs. The process of removing errors from a
program is called Debugging.
 A syntax error occurs when we do not use properly defined syntax
in any programming language. For example: incorrect arguments,
indentation, use of undefined variables etc.

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

1.6.2 Runtime Errors:


 The second type of error is a runtime error, so called because the
error does not appear until after the program has started running.
 These errors are also called exceptions because they usually
indicate that something exceptional (and bad) has happened.
 Some examples of Python runtime errors:
 division by zero
 performing an operation on incompatible types
 using an identifier which has not been defined
 accessing a list element, dictionary value or object attribute
which doesn’t exist
 trying to access a file which doesn’t exist

1.6.3 Semantic Errors:


 The third type of error is the semantic error. If there is a semantic
error in your program, it will run successfully in the sense that the
computer will not generate any error messages, but it will not do
the right thing. It will do something else.
 The problem is that the program you wrote is not the program you
wanted to write. The meaning of the program (its semantics) is
wrong.
 Identifying semantic errors can be tricky because it requires you to
work backward by looking at the output of the program and trying
to figure out what it is doing.

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.

1.7 FORMAL AND NATURAL LANGUAGES

 Natural languages are the languages people speak, such as English,


Spanish, and French. They were not designed by people (although
people try to impose some order on them); they evolved naturally.
 Formal languages are languages that are designed by people for
specific applications.
 For example, the notation that mathematicians use is a formal
language that is particularly good at denoting relationships among
numbers and symbols. Chemists use a formal language to represent
the chemical structure of molecules.
 Programming languages are formal languages that have been
designed to express computations.
 Formal languages tend to have strict rules about syntax. For
example, 3 + 3 = 6 is a syntactically correct mathematical
statement.
 Syntax rules come in two flavors, pertaining to tokens and
structure. Tokens are the basic elements of the language, such as
words, numbers, and chemical elements.
 The second type of syntax rule pertains to the structure of a
statement; that is, the way the tokens are arranged. The statement
3+ = 3 is illegal because even though + and = are legal tokens, you
can’t have one right after the other.

1.8 THE DIFFERENCE BETWEEN BRACKETS,


BRACES, AND PARENTHESES:

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

 Brackets can be used for indexing and lookup of elements


Example:
>>>L1[1] = 40
>>>L1
[10,40,30]
Example: To lookup the element of list L1
>>> L1[0]
10

 Brackets can be used to access the individual characters of a string


or to make string slicing

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

 Brackets can be used to access the value of dictionary element by


specifying the key.
>>> d1[‘rollno’]
101
10
Parentheses ( )
 Parentheses can be used to create immutable sequence data type
tuple.

Example: Create a tuple named ‘t1’ with elements 10,20,30


>>> t1= (10,20,30)
>>> type(t1)
<class ‘tuple’>
 Parentheses can be used to define the parameters of function
definition and function call.
Example:
Multiply two numbers using a function
def mul(a,b):
returns a*b
x=2
y=3
z=mul (2,3)
print(x,’*’,y,’=’z)

 In the function definition def mul(a,b) formal parameters are


specified using parentheses
 In the function call z=mul (2,3) actual values are specified using
parenthesis.

1.9 SUMMARY

 In this chapter we studied Introduction, history, features of Python


Programming Language.
 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.
 In this chapter we are more focused on types of errors in python
like syntax error, runtime error, semantic error and experimental
debugging.
 Execution of Python Program Using Command Prompt and
Interactive Mode to Execute Python Program.
 Also, we studied Difference between Brackets, Braces, and
Parentheses in python.

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.

1.11 UNIT END EXERCISE

1. Use a web browser to go to the Python website http: // python.org.


This page contains information about Python and links to Python-
related pages, and it gives you the ability to search the Python
documentation.
For example, if you enter print in the search window, the first link
that appears is the documentation of the print statement. At this
point, not all of it will make sense to you, but it is good to know
where it is.
2. Start the Python interpreter and type help () to start the online help
utility. Or you can type help ('print') to get information about the
print statement.

*****

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

After reading through this chapter, you will be able to –


 To understand and use the basic datatypes of python.
 To understand the type conversion of variables in python
programming.
 To understand the operators and operands in python.
 To understand the interactive mode and script mode in python.
 To understand the order of operations in python.

2.1 INTRODUCTION

 Variables in a computer program are not quite like mathematical


variables. They are placeholders for locations in memory.
 Memory values consists of a sequence of binary digits (bits) that can
be 0 or 1, so all numbers are represented internally in base 2.
 Names of variables are chosen by the programmer.

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.

2.2 VALUES AND TYPES

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

2.2.2 Variable Names and Keywords:


 Programmers generally choose names for their variables that are
meaningful they document what the variable is used for.
 Variable names can be arbitrarily long. They can contain both letters
and numbers, but they have to begin with a letter. It is legal to use
uppercase letters, but it is a good idea to begin variable names with a
lowercase letter.
 The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as my_name or
airspeed_of_unladen_swallow.
 If you give a variable an illegal name, you get a syntax error:
>>> 76mumbai= 'big city'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced python'
SyntaxError: invalid syntax
 76mumbai is illegal because it does not begin with a letter. more@ is
illegal because it contains an illegal character, @. But what’s wrong
with class?
 It turns out that class is one of Python’s keywords. The interpreter uses
keywords to recognize the structure of the program, and they cannot be
used as variable names.
 Python has a lot of keywords. The number keeps on growing with the
new features coming in python.
 Python 3.7.3 is the current version as of writing this book. There are
35 keywords in Python 3.7.3 release.
 We can get the complete list of keywords using python interpreter help
utility.
 $ python3.7
>>> help ()
help> keywords

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.

2.3 TYPE CONVERSION

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.

2.3.1 Implicit Type Conversion:


 In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
 example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.

Example 1: Converting integer to float


num_int = 123
num_flo = 1.23
num_new = num_int + num_flo

print ("datatype of num_int:”, type(num_int))


print ("datatype of num_flo:”, type(num_flo))
print ("Value of num_new:”, num_new)
print ("datatype of num_new:”, type(num_new))

When we run the above program, the output will be:


datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
16
 In the above program, we add two variables num_int and num_flo,
storing the value in num_new.
 We will look at the data type of all three objects respectively.
 In the output, we can see the data type of num_int is an integer while
the data type of num_flo is a float.
 Also, we can see the num_new has a float data type because Python
always converts smaller data types to larger data types to avoid the
loss of data.

Example 2: Addition of string(higher) data type and integer(lower)


datatype
num_int = 123
num_str = “456”
print (“Data type of num_int:”, type(num_int))
print (“Data type of num_str:”, type(num_str))
print(num_int+num_str)

When we run the above program, the output will be:


Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
 In the above program, we add two variables num_int and num_str.
 As we can see from the output, we got TypeError. Python is not able to
use Implicit Conversion in such conditions.
 However, Python has a solution for these types of situations which is
known as Explicit Conversion.

2.3.2Explicit Type Conversion:


 In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.
 This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.

Syntax:
<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to


the expression

17
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"

print (“Data type of num_int:”, type(num_int))


print (“Data type of num_str before Type Casting:”, type(num_str))
num_str = int(num_str)
print (“Data type of num_str after Type Casting:”, type(num_str))

num_sum = num_int + num_str

print (“Sum of num_int and num_str:”, num_sum)


print (“Data type of the sum:”, type(num_sum))

When we run the above program, the output will be:


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


 In the above program, we add num_str and num_int variable.
 We converted num_str from string(higher) to integer(lower) type
using int() function to perform the addition.
 After converting num_str to an integer value, Python is able to add
these two variables.
 We got the num_sum value and data type to be an integer.

2.4 OPERATORS AND OPERANDS:

 Operators are particular symbols which operate on some values and


produce an output.
 The values are known as Operands.

Example:
4+5=9
Here 4 and 5 are Operands and (+), (=) signs are the operators.
They produce the output 9

 Python supports the following operators:


Arithmetic Operators.
18
Relational Operators.
Logical Operators.
Membership Operators.
Identity Operators

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

 Arithmetic Operator Examples:


>>> 10+20
30
>>> 20-10
10
>>> 10*2
20
>>> 10/2
5
>>> 10%3
1
>>> 2**3
8
>>> 10//3
3

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

Logical Operators Examples:


a=5>4 and 3>2
print(a)
True
b=5>4 or 3<2
print(b)
True
c=not(5>4)
print(c)
False

Membership Operators:

Operators Description

in Returns true if a variable is in sequence of another


variable, else false.
not in Returns true if a variable is not in sequence of
another variable, else false.

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.

Identity operators Examples


a=20
b=20
if (a is b):
print (“a, b has same identity”)
else:
print (“a, b is different”)
b=10
if (a is not b):
print (“a, b has different identity”)
else:
print (“a, b has same identity”)
>>>
a, b has same identity
a, b has different identity

21
2.5 EXPRESSIONS

 An expression is a combination of values, variables, and operators.


 A value all by itself is considered an expression, and so is a variable,
so the following are all legal expressions (assuming that the variable x
has been assigned a value):
17
x
x + 17
A statement is a unit of code that the Python interpreter can execute. We
have seen two kinds of statement: print and assignment.

 Technically an expression is also a statement, but it is probably


simpler to think of them as different things. The important difference
is that an expression has a value; a statement does not.

2.6 INTERACTIVE MODE AND SCRIPT MODE:

 One of the benefits of working with an interpreted language is that you


can test bits of code in interactive mode before you put them in a
script. But there are differences between interactive mode and script
mode that can be confusing.
 For example, if you are using Python as a calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182

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.7 ORDER OF OPERATIONS

 When more than one operator appears in an expression, the order of


evaluation depends on the rules of precedence. For mathematical
operators, Python follows mathematical convention. The acronym
PEMDAS is a useful way to remember the rules:
 Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first,
 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to
make an expression easier to read, as in (minute * 100) / 60, even if it
doesn’t change the result.
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4,
and 3*1**3 is 3, not 27.
 Multiplication and Division have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right
(except exponentiation). So, in the expression degrees / 2 * pi, the
division happens first and the result is multiplied by pi. To divide by
2π, you can use parentheses or write degrees / 2 / pi.
 Example for Operator Precedence
>>> 200/200+(100+100)
201.0
>>>
>>> a=10
>>> b=20
>>> c=15
>>> (a+b)*(c+b)-150
900
>>> (a+b)*c+b-150
320
>>> a+b**2
410
23
>>> a or b + 20
10
>>> c or a + 20
15
>>> c and a + 20
30
>>> a and b + 20
40
>>> a>b>c
False
>>>

2.8 SUMMARY

 In this chapter we studied how to declare variables, expression and


types of variables in python.
 We are more focuses on type conversion of variables in this chapter
basically two types of conversion are implicit type conversion and
explicit type conversion.
 Also studied types of operators available in python like arithmetic,
logical, relational and membership operators.
 Focuses on interactive mode and script mode in python and order of
operations.

2.9 UNIT END EXERCISE

1. Assume that we execute the following assignment statements:


width = 17
height = 12.0
delimiter = '.'

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. Type the following statements in the Python interpreter to see what


they do:
5
x=5
x+1
Now put the same statements into a script and run it. What is the
output? Modify the script by transforming each expression into a print
statement and then run it again.

3. Write a program add two numbers provided by the user.


4. Write a program to find the square of number.
5. Write a program that takes three numbers and prints their sum. Every
number is given on a separate line.

2.9 REFERENCES

 Think Python by Allen Downey 1st edition.


 Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
 https://learning.rc.virginia.edu/
 www.programiz.com
 www.itvoyagers.in

*****

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

After reading through this chapter, you will be able to –


 To understand and use the conditional statementsin python.
 To understand the loop control in python programming.
 To understand the control statements in python.
 To understand the concepts of python and able to apply it for
solving the complex problems.

3.1 INTRODUCTION

 In order to write useful programs, we almost always need the


ability to check conditions and change the behavior of the program
accordingly. Conditional statements give us this ability.
 The simplest form is the if statement:
if x > 0:
print 'x is positive'

26
The boolean expression after if is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.

 if statements have the same structure as function definitions: a


header followed by an indented body. Statements like this are
called compound statements.

 There is no limit on the number of statements that can appear in the


body, but there has to be at least one. Occasionally, it is useful to
have a body with no statements. In that case, you can use the pass
statement, which does nothing.
if x < 0:
pass # need to handle negative values!

3.2 CONDITIONAL STATEMENTS

Conditional Statement in Python perform different


computations or actions depending on whether a specific Boolean
constraint evaluates to true or false. Conditional statements are handled
by IF statements in Python.

Story of Two if’s:


Consider the following if statement, coded in a C-like language:
if (p > q)
{ p = 1;
q = 2;
}
Now, look at the equivalent statement in the Python language:
if p > q:
p=1
q=2
 what Python adds
 what Python removes

1) Parentheses are optional


if (x < y) ---> if x < y

2) End-of-line is end of statement


C-like languages Python language
x = 1; x=1

3) End of indentation is end of block


Why Indentation Syntax?
A Few Special Cases
a = 1; b = 2; print (a + b)

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.

Example: Python if Statement


# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print (num, "is a positive number.")
print ("This is always printed.")

num = -1
if num > 0:
print (num, "is a positive number.")
print ("This is also always printed.")

When you run the program, the output will be:


3 is a positive number.
This is always printed.

This is also always printed.


 In the above example, num > 0 is the test expression.
 The body of if is executed only if this evaluates to True.
 When the variable num is equal to 3, test expression is true and
statements inside the body of if are executed.
 If the variable num is equal to -1, test expression is false and
statements inside the body of if are skipped.
 The print() statement falls outside of the if block (unindented).
Hence, it is executed regardless of the test expression.

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.

3.2.3 if...elif...else Statement:


Syntax
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
29
 The elif is short for else if. It allows us to check for multiple
expressions.
 If the condition for if is False, it checks the condition of the
next elif block and so on.
 If all the conditions are False, the body of else is executed.
 Only one block among the several if...elif...else blocks is executed
according to the condition.
 The if block can have only one else block. But it can have
multiple elif blocks.

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

 When variable num is positive, Positive number is printed.


 If num is equal to 0, Zero is printed.
 If num is negative, Negative number is printed.

3.2.4 nested if –else:


 We can have a if...elif...else statement inside
another if...elif...else statement. This is called nesting in computer
programming.
 Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting. They
can get confusing, so they must be avoided unless necessary.

Python Nested if Example


'''In this program, we input a number
check if the number is positive or
negative or zero and display

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

3.3 LOOPING STATEMENTS

 In general, statements are executed sequentially: The first


statement in a function is executed first, followed by the second,
and so on. There may be a situation when you need to execute a
block of code several number of times.
 Programming languages provide various control structures that
allow for more complicated execution paths.
 A loop statement allows us to execute a statement or group of
statements multiple times.

3.3.1 for loop:

 The for loop in Python is used to iterate over a sequence


(list, tuple, string) or other iterable objects. Iterating over a
sequence is called traversal.
 Syntax of for Loop
for val in sequence:
Body of for

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: Python for Loop


# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print ("The sum is", sum)

When you run the program, the output will be:


The sum is 48

The range () function:


 We can generate a sequence of numbers using range
() function. range (10) will generate numbers from 0 to 9 (10
numbers).
 We can also define the start, stop and step size as range (start,
stop,step_size). step_size defaults to 1, start to 0 and stop is end of
object if not provided.
 This function does not store all the values in memory; it would be
inefficient. So, it remembers the start, stop, step size and generates
the next number on the go.
 To force this function to output all the items, we can use the
function list().

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

for loop with else:


 A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts.
 The break keyword can be used to stop a for loop. In such cases,
the else part is ignored.
 Hence, a for loop's else part runs if no break occurs.

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.

3.3.2 while loop:


 The while loop in Python is used to iterate over a block of code as
long as the test expression (condition) is true.
 We generally use while loop when we don't know the number of
times to iterate beforehand.
 Syntax of while Loop in Python
while test_expression:
Body of while
 In the while loop, test expression is checked first. The body of the
loop is entered only if the test_expression evaluates to True.
 After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False.
 In Python, the body of the while loop is determined through
indentation.
 The body starts with indentation and the first unindented line marks
the end.
 Python interprets any non-zero value as True. None and 0 are
interpreted as False.

Example: Python while Loop


# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int (input ("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
34
# print the sum
print ("The sum is", sum)
When you run the program, the output will be:
Enter n: 10
The sum is 55
 In the above program, the test expression will be True as long as
our counter variable i is less than or equal to n (10 in our program).
 We need to increase the value of the counter variable in the body of
the loop. This is very important. Failing to do so will result in an
infinite loop (never-ending loop).

While loop with else:


 Same as with for loops, while loops can also have an
optional else block.
 The else part is executed if the condition in the while loop
evaluates to False.
 The while loop can be terminated with a break statement. In such
cases, the else part is ignored. Hence, a while loop's else part runs
if no break occurs and the condition is false.
 Example:
'''Example to illustrate
the use of else statement
with the while loop'''
counter = 0
while counter < 3:
print ("Inside loop")
counter = counter + 1
else:
print ("Inside else")
Output:
Inside loop
Inside loop
Inside loop
Inside else

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

3.3.3 Nested Loops:


 Loops can be nested in Python similar to nested loops in
other programming languages.
35
 Nested loop allows us to create one loop inside another loop.
 It is similar to nested conditional statements like nested if
statement.
 Nesting of loop can be implemented on both for loop and while
loop.
 We can use any loop inside loop for example, for loop can have
while loop in it.

Nested for loop:


 For loop can hold another for loop inside it.
 In above situation inside for loop will finish its execution first and
the control will be returned back to outside for loop.

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.

Example1: of nested for loop in python:


for i in range (1,11):
for j in range (1,11):
m=i*j
print (m, end=' ')
print (“Table of “, i)

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

Example2: of nested for loop in python:


for i in range (10):
for j in range(i):
print ("*”, end=' ')
print (" ")

Output:

*
**
***
****
*****
******
*******
********
*********

Nested while loop:


 While loop can hold another while loop inside it.
 In above situation inside while loop will finish its execution first
and the control will be returned back to outside while loop.
Syntax
while expression:
while expression2:
statement(s) of inside while loop
statement(s) of outside while loop

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

Example1: Program to show nested while loop


p=1
37
while p<10:
q=1
while q<=p:
print (p, end=" ")
q+=1
p+=1
print (" ")

Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999

Exampleb2: Program to nested while loop


x=10
while x>1:
y=10
while y>=x:
print (x, end=" ")
y-=1
x-=1
print(" ")

Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222

38
3.4 CONTROL STATEMENTS:

 Control statements in python are used to control the order of


execution of the program based on the values and logic.
 Python provides us with three types of Control Statements:
Continue
Break

3.4.1 Terminating loops:


 The break statement is used inside the loop to exit out of the loop.
It is useful when we want to terminate the loop as soon as the
condition is fulfilled instead of doing the remaining iterations.
 It reduces execution time. Whenever the controller encountered a
break statement, it comes out of that loop immediately.
 Syntax of break statement
for element in sequence:
if condition:
break

Example:
for num in range (10):
if num > 5:
print ("stop processing.")
break
print(num)

Output:
0
1
2
3
4
5
stop processing.

3.4.2 skipping specific conditions:


 The continue statement is used to skip the current iteration
and continue with the next iteration.
 Syntax of continue statement:
for element in sequence:
if condition:
continue

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

 In this chapter we studied conditional statements like if, if-else, if-


elif-else and nested if-else statements for solving complex
problems in python.
 More focuses on loop control in python basically two types of
loops available in python like while loop, for loop and nested loop.
 Studied how to control the loop using break and continue
statements in order to skipping specific condition and terminating
loops.

3.6 UNIT END EXERCISE


1. Print the squares of numbers from 1 to 10 using loop control.
2. Write a Python program to print the prime numbers of up to a
given number, accept the number from the user.
3. Write a Python program to print the following pattern
1
23
456
78910
1112131415

4. Write a Python program to construct the following pattern, using a


nested for loop.
*
**
***
****
*****
****
***
**
*
40
5. Write a Python program to count the number of even and odd
numbers from a series of numbers.
Sample numbers: numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Expected Output:
Number of even numbers: 5
Number of odd numbers: 4

6. Write a Python program that prints all the numbers from 0 to 6


except 3 and 6
Note: Use 'continue' statement.
Expected Output: 0 1 2 4 5

7. Print First 10 natural numbers using while loop


8. Print the following pattern
1
12
123
1234
12345
9. Display numbers from -10 to -1 using for loop
10. Print the following pattern
*
**
***
*****
******

3.7 REFERENCES

 Think Python by Allen Downey 1st edition.


 Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
 www.programiz.com
 https://itvoyagers.in
 https://www.softwaretestinghelp.com
 https://pynative.com

*****

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

After reading through this chapter, you will be able to –


 To understand and use the function calls.
 To understand the type conversion functions.
 To understand the math function.
 To adding new function.
 To understand the Parameters and Arguments.
 To understand the fruitful functions and void functions.
 To understand the boolean functions, Recursion, checking types
etc.

4.1 INTRODUCTION

 One of the core principles of any programming language is, "Don't


Repeat Yourself". If you have an action that should occur many
42
times, you can define that action once and then call that code
whenever you need to carry out that action.

 We are already repeating ourselves in our code, so this is a good


time to introduce simple functions. Functions mean less work for
us as programmers, and effective use of functions results in code
that is less error.

4.2 FUNCTION CALLS

What is a function in Python?


 In Python, a function is a group of related statements that performs
a specific task.
 Functions help break our program into smaller and modular
chunks. As our program grows larger and larger, functions make it
more organized and manageable.
 Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition that consists of the following


components.
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function
naming follows the same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a
function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the
function does.
6. One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
7. An optional return statement to return a value from the function.

Example:
def greeting(name):
"""
This function greets to
the person passed in as
43
a parameter
"""
print ("Hello, " + name + ". Good morning!")

How to call a function in python?


 Once we have defined a function, we can call it from another
function, program or even the Python prompt.
 To call a function we simply type the function name with
appropriate parameters.
>>> greeting('IDOL')
Hello, IDOL. Good morning!

4.3 TYPE CONVERSION FUNCTIONS

 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.
1. Implicit Type Conversion
2. Explicit Type Conversion

1. Implicit Type Conversion:


 In Implicit type conversion, Python automatically converts one
data type to another data type. This process doesn't need any user
involvement.
 Let's see an example where Python promotes the conversion of the
lower data type (integer) to the higher data type (float) to avoid
data loss.

Example 1: Converting integer to float


num_int = 123
num_float = 1.23
num_new = num_int + num_float
print (“datatype of num_int:”, type(num_int))
print (“datatype of num_float:” type(num_float))
print (“Value of num_new:”, num_new)
print (“datatype of num_new:”, type(num_new))
Output:
datatype of num_int: <class 'int'>
datatype of num_float: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
44
Example 2: Addition of string(higher) data type and integer(lower)
datatype
num_int = 123
num_str = "456"

print ("Data type of num_int:”, type(num_int))


print ("Data type of num_str:”, type(num_str))
print(num_int+num_str)
Output:
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'


 In the above program,
 We add two variables num_int and num_str.
 As we can see from the output, we got TypeError. Python is not
able to use Implicit Conversion in such conditions.
 However, Python has a solution for these types of situations which
is known as Explicit Conversion.

2. Explicit Type Conversion:


 In Explicit Type Conversion, users convert the data type of an
object to required data type. We use the predefined functions like
int(), float(), str(), etc to perform explicit type conversion.
 This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax:
<required_datatype>(expression)
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
print ("Data type of num_int:”, type(num_int))
print ("Data type of num_str before Type Casting:”, type(num_str))
num_str = int(num_str)
print ("Data type of num_str after Type Casting:”, type(num_str))
num_sum = num_int + num_str
45
print ("Sum of num_int and num_str:”, num_sum)
print ("Data type of the sum:”, type(num_sum))

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

 Type Conversion is the conversion of object from one data type to


another data type.
 Implicit Type Conversion is automatically performed by the
Python interpreter.
 Python avoids the loss of data in Implicit Type Conversion.
 Explicit Type Conversion is also called Type Casting, the data
types of objects are converted using predefined functions by the
user.
 In Type Casting, loss of data may occur as we enforce the object to
a specific data type.

4.4 MATH FUNCTIONS

 The math module is a standard module in Python and is always


available. To use mathematical functions under this module, you
have to import the module using import math.
 For example
# Square root calculation
import math
math.sqrt(4)
 Functions in Python Math Module
Pi is a well-known mathematical constant, which is defined as the
ratio of the circumference to the diameter of a circle and its value is
3.141592653589793.
>>> import math
>>>math.pi
3.141592653589793
 Another well-known mathematical constant defined in the math
module is e. It is called Euler's number and it is a base of the
natural logarithm. Its value is 2.718281828459045.
>>> import math
>>>math.e
2.718281828459045
46
 The math module contains functions for calculating various
trigonometric ratios for a given angle. The functions (sin, cos, tan,
etc.) need the angle in radians as an argument. We, on the other
hand, are used to express the angle in degrees. The math module
presents two angle conversion functions: degrees () and radians (),
to convert the angle from degrees to radians and vice versa.
>>> import math
>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)
29.999999999999996
 math.log()
The math.log() method returns the natural logarithm of a given
number. The natural logarithm is calculated to the base e.
>>> import math
>>>math.log(10)
2.302585092994046
 math.exp()
The math.exp() method returns a float number after raising e to the
power of the given number. In other words, exp(x) gives e**x.
>>> import math
>>>math.exp(10)
22026.465794806718
 math.pow()
The math.pow() method receives two float arguments, raises the first to
the second and returns the result. In other words, pow(4,4) is
equivalent to 4**4.
>>> import math
>>>math.pow(2,4)
16.0
>>> 2**4
16
 math.sqrt()
The math.sqrt() method returns the square root of a given number.
>>> import math
>>>math.sqrt(100)
10.0
47
>>>math.sqrt(3)
1.7320508075688772

4.5 ADDING NEW FUNCTIONS


 So far, we have only been using the functions that come with
Python, but it is also possible to add new functions.
 A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
 Example:
def print_lyrics():
print ("I'm a lumberjack, and I'm okay.")
print ("I sleep all night and I work all day.")
 def is a keyword that indicates that this is a function definition. The
name of the function is print_lyrics. The rules for function names
are the same as for variable names: letters, numbers and some
punctuation marks are legal, but the first character can’t be a
number. You can’t use a keyword as the name of a function, and
you should avoid having a variable and a function with the same
name.
 The empty parentheses after the name indicate that this function
doesn’t take any arguments.
 The first line of the function definition is called the header; the rest
is called the body. The header has to end with a colon and the body
has to be indented.
 By convention, the indentation is always four spaces .The body can
contain any number of statements.
 The strings in the print statements are enclosed in double quotes.
Single quotes and double quotes do the same thing; most people
use single quotes except in cases like this where a single quote
appears in the string.
 Once you have defined a function, you can use it inside another
function. For example, to repeat the previous refrain, we could
write a function called repeat_lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
48
4.6 DEFINITIONS AND USES

 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.")

def repeat_lyrics ():


print_lyrics ()
print_lyrics ()

repeat_lyrics ()

 This program contains two function


definitions: print_lyrics and repeat_lyrics. Function definitions get
executed just like other statements, but the effect is to create
function objects.
 The statements inside the function do not get executed until the
function is called, and the function definition generates no output.

4.6.1 Flow of Execution:

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

4.6.2 Parameters and Arguments:

 Some of the built-in functions we have seen require arguments. For


example, when you call math.sin you pass a number as an
argument. Some functions take more than one
argument: math.pow takes two, the base and the exponent.

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

 The same rules of composition that apply to built-in functions also


apply to user-defined functions, so we can use any kind of
expression as an argument for print_twice.
>>> print_twice ('Spam '*4)
Spam SpamSpamSpam
Spam SpamSpamSpam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
The argument is evaluated before the function is called, so in the
examples the expressions 'Spam '*4 and math.cos(math.pi) are only
evaluated once.

4.6.3 Variables and Parameters Are Local:

 When you create a variable inside a function, it is local, which


means that it only exists inside the function.

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

 When cat_twice terminates, the variable cat is destroyed. If we try


to print it, we get an exception:
>>> print cat
NameError: name 'cat' is not defined

 Parameters are also local. For example, outside print_twice, there is


no such thing as bruce.

4.6.4 Stack Diagrams:


 To keep track of which variables can be used where, it is
sometimes useful to draw a stack diagram. Like state diagrams,
stack diagrams show the value of each variable, but they also show
the function each variable belongs to.
 Each function is represented by a frame. A frame is a box with the
name of a function beside it and the parameters and variables of the
function inside it. The stack diagram for the previous example is
shown in Figure.

Fig. Stack Diagram


 The frames are arranged in a stack that indicates which function
called which, and so on. In this example, print_twice was called
by cat_twice, and cat_twice was called by __main__, which is a
special name for the topmost frame. When you create a variable
outside of any function, it belongs to __main__.

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

4.7 FRUITFUL FUNCTIONS AND VOID FUNCTIONS

 Some of the functions we are using, such as the math functions,


yield results; for lack of a better name, I call them fruitful
functions. Other functions, like print_twice, perform an action but
don’t return a value. They are called void functions.
 When you call a fruitful function, you almost always want to do
something with the result; for example, you might assign it to a
variable or use it as part of an expression:
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays
the result:
>>>math.sqrt(5)
2.2360679774997898
 But in a script, if you call a fruitful function all by itself, the return
value is lost forever
math.sqrt(5)
This script computes the square root of 5, but since it doesn’t store or
display the result, it is not very useful.
 Void functions might display something on the screen or have
some other effect, but they don’t have a return value. If you try to
assign the result to a variable, you get a special value called None.
>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
The value None is not the same as the string 'None'. It is a special
value that has its own type:
>>> print type(None)
<type 'NoneType'>
 The functions we have written so far are all void.

52
4.8 WHY FUNCTIONS?

 It may not be clear why it is worth the trouble to divide a program


into functions. There are several reasons:
 Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read and debug.
 Functions can make a program smaller by eliminating repetitive
code. Later, if you make a change, you only have to make it in one
place.
 Dividing a long program into functions allows you to debug the
parts one at a time and then assemble them into a working whole.
 Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.

4.9 IMPORTING WITH FROM, RETURN VALUES,


INCREMENTAL DEVELOPMENT

 Importing with from:


Python provides two ways to import modules, we have already seen
one:
>>> import math
>>> print math
<module 'math' (built-in)>
>>> print math.pi
3.14159265359
 If you import math, you get a module object named math. The
module object contains constants like pi and functions
like sin and exp.
But if you try to access pi directly, you get an error.
>>> print pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
 As an alternative, you can import an object from a module like this:
>>> from math import pi
Now you can access pi directly, without dot notation.
>>> print pi
3.14159265359
Or you can use the star operator to import everything from the module:
>>> from math import *

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.

4.10 BOOLEAN FUNCTIONS


 Syntax for boolean function is as follows
Bool([value])
 As we seen in the syntax that the bool() function can take a single
parameter (value that needs to be converted). It converts the given
value to True or False.
 If we don’t pass any value to bool() function, it returns False.
 bool() function returns a boolean value and this function
returns False for all the following values
1. None
2. False
3. Zero number of any type such as int, float and complex. For
example: 0, 0.0, 0j
4. Empty list [], Empty tuple (), Empty String ”.
5. Empty dictionary {}.
6. objects of Classes that implements __bool__() or __len()__
method, which returns 0 or False
 bool() function returns True for all other values except the values
that are mentioned above.
 Example: bool() function
In the following example, we will check the output of bool() function
for the given values. We have different values of different data
types and we are printing the return value of bool() function in the
output.
# empty list
lis = []
print(lis,'is',bool(lis))
# empty tuple
t = ()
print(t,'is',bool(t))
# zero complex number
54
c = 0 + 0j
print(c,'is',bool(c))
num = 99
print(num, 'is', bool(num))
val = None
print(val,'is',bool(val))
val = True
print(val,'is',bool(val))
# empty string
str = ''
print(str,'is',bool(str))
str = 'Hello'
print(str,'is',bool(str))
Output:
[] is False
() is False
0j is False
99 is True
None is False
True is True
is False
Hello is True

4.11 MORE RECURSION, CHECKING TYPES:


 What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors
facing each other. Any object in between them would be reflected
recursively.
 In Python, we know that a function can call other functions. It is
even possible for the function to call itself. These types of construct
are termed as recursive functions.

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

"""This is a recursive function

to find the factorial of an integer"""

if x == 1:

return 1

else:

return (x * factorial(x-1))

num = 3

print("The factorial of", num, "is", factorial(num))

Output:

The factorial of 3 is 6

 In the above example, factorial () is a recursive function as it calls


itself. When we call this function with a positive integer, it will
recursively call itself by decreasing the number.
 Each function multiplies the number with the factorial of the
number below it until it is equal to one. This recursive call can be
explained in the following steps.
factorial (3) # 1st call with 3
3 * factorial (2) # 2nd call with 2

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

 In this chapter we studied function call, type conversion functions


in Python Programming Language.
 In this chapter we are more focused on math function and adding
new function in python.
 Elaborating on definitions and uses of function, parameters and
arguments in python.
 Also studied fruitful functions and void functions, importing with
from, boolean functions and recursion in python.

4.14 UNIT END EXERCISE

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

 To learn how to crate string in Python


 To study looping and counting in Python
 To write programs for creating string methods in Python
 To understand various operators and string operation of Python
 To learn the string traversal with a for loop in Python

5.1 A STRING IS A SEQUENCE

There are numerous types of sequences in Python. Strings are a


special type of sequence that can only store characters, and they have a
special notation. Strings are sequences of characters and are immutable.

A string is a sequence of characters. We can access the characters


one at a time with the bracket operator:

>>>food = 'roti'
>>>letter = food[1]

The second statement retrieves the character at index position one


from the food variable and assigns it to the letter variable.The expression

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.

Declaring Python String


String literals in Python
String literals are surrounded by single quotes or double-quotes.
‘I want to read book’
“I want to read book’”

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 ’

This statement causes a SyntaxError:


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

Common escape sequences:


 \\ Backslash
 \n Linefeed
 \t Horizontal tab
 \’ Single quotes
 \” Double quotes

We can assign a string to a variable.


60
name=’Sunil’

You can also create a string with the str() function.

>>> str(567)

Output:
‘567’

>>> str('Shri')

Output:
‘Shri’

5.2. TRAVERSAL AND THE FOR LOOP: BY ITEM

A lot of computations involve processing a collection one item at a


time. For strings this means that we would like to process one character at
a time. Often we start at the beginning, select each character in turn, do
something to it, and continue until the end. This pattern of processing is
called a traversal.

We have previously seen that the for statement can iterate over the
items of a sequence (a list of names in the case below).

for aname in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi",


"Paris"]:
invitation = "Hi " + aname + ". Please come to my party on Saturday!"
print(invitation)

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.

for avalue in range(10):


print(avalue)

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.

Check your understanding

strings-10-4: How many times is the word HELLO printed by the


following statements?

s = "python rocks"
for ch in s:
print("HELLO")
Ans - Yes, there are 12 characters, including the blank.

strings-10-5: How many times is the word HELLO printed by the


following statements?

s = "python rocks"
for ch in s[3:8]:
print("HELLO")
Ans - Yes, The blank is part of the sequence returned by slice

5.3. STRING SLICES

Python slice string syntax is:


str_object[start_pos:end_pos:step]

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

All these parameters are optional – start_pos default value is 0, the


end_pos default value is the length of string and step default value is 1.

Let’s look at some simple examples of string slice function to create


substring.

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.

Let’s look at some more examples of slicing a string.


s = 'HelloWorld'
first_five_chars = s[:5]
print(first_five_chars)
third_to_fifth_chars = s[2:5]
print(third_to_fifth_chars)

Output:
Hello
Llo

Note that index value starts from 0, so start_pos 2 refers to the third
character in the string.

Reverse a String using Slicing

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

Here the substring contains characters from indexes 2,4 and 6.


s1 = s[8:1:-1]
print(s1)

63
Output:
lroWoll

5.4 STRINGS ARE IMMUTABLE

The standard wisdom is that Python strings are immutable. You


can't change a string's value, only the reference to the string. Like so:
x = "hello"
x = "goodbye" # New string!

Which implies that each time you make a change to a string


variable, you are actually producing a brand new string. Because of this,
tutorials out there warn you to avoid string concatenation inside a loop and
advise using join instead for performance reasons. Even the official
documentation says so!

This is wrong. Sort of.

There is a common case for when strings in Python are actually


mutable. I will show you an example by inspecting the string object's
unique ID using the builtin id() function, which is just the memory
address. The number is different for each object. (Objects can be shared
though, such as with interning.)

An unchanging article alludes to the item which is once made can’t


change its worth all its lifetime. Attempt to execute the accompanying
code:
name_1 = "Aarun"
name_1[0] = 'T'

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

Searching is a very basic necessity when you store data in different


data structures. The simplest approach is to go across every element in the
data structure and match it with the value you are searching for.This is
known as Linear search. It is inefficient and rarely used, but creating a
program for it gives an idea about how we can implement some advanced
search algorithms.

Linear Search:

In this type of search, a sequential search is made over all items


one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of
the data structure.

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:

This search algorithm works on the probing position of the


required value. For this algorithm to work properly, the data collection
should be in a sorted form and equally distributed. Initially, the probe
position is the position of the middle most item of the collection. If a
match occurs, then the index of the item is returned. If the middle item is
greater than the item, then the probe position is again calculated in the
sub-array to the right of the middle item. Otherwise, the item is searched
in the subarray to the left of the middle item. This process continues on the
sub-array as well until the size of subarray reduces to zero.

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

5.6 LOOPING AND COUNTING

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)

This program demonstrates another pattern of computation called a


counter. The variable count is initialized to 0 and then incremented each
time an “r” is found. When the loop exits, count contains the result: the
total number of r’s.
s = "peanut butter"
count = 0
for char in s:
if char == "t":
count = count + 1
print(count)

Output:
The letter t appears 3 times in "peanut butter".

5.7 STRING METHODS

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.

5.8. THE IN OPERATOR

Not let us take an example to get a better understanding of the in operator


working.
x in y

Here “x” is the element and “y” is the sequence where membership is
being checked.

Let’s implement a simple Python code to demonstrate the use of the in


operator and how the outputs would look like.
vowels = ['A', 'E', 'I', 'O', 'U']
ch = input('Please Enter a Capital Letter:\n')
if ch in vowels:
print('You entered a vowel character')
else:
print('You entered a consonants character')

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

Can we use Python “in” Operator with a Dictionary?


Let’s see what happens when we use “in” operator with a dictionary.
dict1 = {"name": "Pankaj", "id": 1}
print("name" in dict1) # True
69
print("Pankaj" in dict1) # False

It looks like the Python “in” operator looks for the element in the
dictionary keys.

5.9 STRING COMPARISON

The following are the ways to compare two string in Python:


1. By using == (equal to) operator
2. By using != (not equal to) operator
3. By using sorted() method
4. By using is operator
5. By using Comparison operators

1. Comparing two strings using == (equal to) operator


str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if str1 == str2:
print ("First and second strings are equal and same")
else:
print ("First and second strings are not same")
Output:
Enter the first String: AA
Enter the second String: AA
First and second strings are equal and same

2. Comparing two strings using != (not equal to) operator


str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if str1 != str2:
print ("First and second strings are not equal.")
else:
print ("First and second strings are the same.")
Output:
Enter the first String: ab
Enter the second String: ba
First and second strings are not equal.

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.

4. Comparing two strings using ‘is’ operator


Python is Operator returns True if two variables refer to the same object
instance.
str1 = "DEED"
str2 = "DEED"
str3 = ''.join(['D', 'E', 'E', 'D'])
print(str1 is str2)
print("Comparision result = ", str1 is str3)

Output:
True
Comparision result = False

In the above example, str1 is str3 returns False because object str3 was
created differently.

5. Comparing two strings using comparison operators


input = 'Engineering'
print(input < 'Engineering')
print(input > 'Engineering')
print(input <= 'Engineering')
print(input >= 'Engineering')
Output:
False
71
False
True
True

5.10 STRING OPERATIONS

String is an array of bytes that represent the Unicode characters in


Python. Python does not support character datatype. A single character
also works as a string.Python supports writing the string within a single
quote('') and a double quote("").

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

A single character is simply a string with a length of 1. The square


brackets can be used to access the elements from the string.
print()

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

A Python String is an array of bytes demonstrating Unicode


characters. Since there is no such data type called character data type in
python, A single character is a string of length one. String handling is one
of those activities in coding that programmers, use all the time.
In Python, we have numerous built-in functions in the standard library to
assist you manipulate. If the string has length one, then the indices start
from 0 for the preliminary character and go to L-1 for the rightmost
character. Negative indices may be used to count from the right end, -
1(minus one) for the rightmost character through -L for the leftmost
character. Strings are immutable, so specific characters could be read, but
not set. A substring of 0 or more successive characters of a string may be
referred to by specifying a starting index and the index one earlier the last
character of the substring. If the starting and/or ending index is left out
Python uses 0 and the length of the string correspondingly. Python
assumes indices that would be beyond an end of the string essentially say
the end of the string. String formatting is the way we form instructions so
that Python can recognize how to integrate data in the creation of strings.
How strings are formatted determines the presentation of this data. The
basis of string formatting is its use of the formatting directives.Logical
operators return true or false values. Comparison operators (==, !=, <>, >,
>=, <, <=) compare two values.Any value in Python equates to a Boolean
true or false. A false can be equal to none, a zero of numeric type (0, 0l,
0.0), an empty sequence ('', (), []), or an empty dictionary ({}). All other
values are reflected true. Sequences, tuples, lists, and strings can be added
and/or multiplied by a numeric type with the addition and multiplication
operators (+, *), correspondingly. Strings should be formatted with tuples
and dictionaries using the format directives %i, %d, %f, and %e.
Formatting flags should be used with these directives.

5.12 QUESTIONS

1. Find the index of the first occurrence of a substring in a string.


2. How would you check if each word in a string begins with a capital
letter?
3. Write a Python program to calculate the length of a string
4. Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first
char itself.

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

1. To learn how python uses lists to store various data values.


2. To study usage of the list index to remove, update and add items from
python list.
3. To understand the abstract data types queue, stack and list.
4. To understand the implementations of basic linear data structures.
5. To study the implementation of the abstract data type list as a linked
list using the node.

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.

Creating a list is as very simple as putting up different comma-


separated by values between square brackets. For example –

list1 = ['jack', 'nick', 1997, 5564];


list2 = [1, 2, 3, 4];
list3 = ["a", "b", "c", "d"];

75
Similar to a string indices, A list indices start from 0, and lists can
be sliced, concatenated.

6.2 VALUES AND ACCESSING ELEMENTS

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]

6.3 LISTS ARE MUTABLE:

lists is mutable. This means we can change a item in a list by


accessing it directly as part of the assignment pf statement. Using the
indexing operator (square brackets) on the left of side an assignment, we
can update one of the list item.

Example:

color = ["red", "white", "black"]


print(color)

color [0] = "orange"


color [-1] = "green"
print(color)

Output:.

["red", "white", "black"]

["orange ", "white", "green "]

6.4 TRAVERSING A LIST

The mostly common way to traverse the elements of list with for loop. The
syntax is the same as for strings:

color = ["red", "white", "blue", "green"]

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

number [i] = number[i] * 2

output −
red
white
blue
green

6.5 DELETING ELEMENTS FROM LIST

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 –

list1 = [‘red’, ‘green’, 5681, 2000,];

print(list1)

del list[2]

print(“After deleting element at index 2 :”);

print(list1)

output −.

[‘red’, ‘green’, 5681, 2000,]

After deleting element at index 2 :

[‘red’, ‘green’ , 2000,]

Example2:

numbers = [50, 60, 70, 80]


del numbers[1:2]
print(numbers)

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

6.6 BUILT-IN LIST OPERATORS

In this lesson we will learn about built-in list operators:

Concatenation

Indexing Repetition

List Operation

Membership
Slicing
Testing

1. Concatenation:

Concatenation or joining is a process in which multiple sequence / lists


can be combined together. ‘+’ is a symbol concatenation operator.

Example:

list1 = [10, 20, 30]

list2 = [40, 50, 60]

print(list1 + list2)

Output:

[10, 20, 30, 40, 50, 60]


78
2. Repetition / Replication / Multiply:

This operator replication the list for a specified number of times


and creates a new list. ‘*’ is a symbol of repletion operator.

Example:

list1 = [10, 20, 30]

list2 = [40, 50, 60]

print(list1 * list2

Output:

[10, 20, 30,10, 20, 30,10, 20, 30,])

3. Membership Operator:

This operator used to check or test whether a particular element or


item is a member of any list or not. ‘in’ And ‘not in’ are the operators for
membership operator.

Example:

list1 = [10, 20, 30]

list2 = [40, 50, 60]

print(50 in list1) #false

print(20 in list1) #true

print(50 not in list1) #true

print(20 not in list1) #false

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:

list1 = [10, 20, 30, 40, 50, 60, 70]

print(list1[4])

Output:

50

5. Slicing operator:

This operator used to slice a particular range of a list or a sequence.


Slice is used to retrieve a subset of values.

Syntax: list1[start:stop:step]

Example:
list1 = [10, 20, 30, 40, 50, 60, 70]

print(list1[3:7])

Output:

[40, 50, 60, 70]

6.7 CONCATENATION

In this we will learn different methods to concatenate lists in


python. Python list server the purpose of storing homogenous elements
and perform manipulations on the same.

In general, Concatenation is the process of joining the elements of


a particular data-structure in an end-to-end manner.

The following are the 4 ways to concatenate lists in python.

 Concatenation (+) operator:


The '+' operator can be used to concatenate two lists. It appends one list at
the end of the other list and results in a new list as output.
80
Example:

list1 =[10, 11, 12, 13, 14]


list2 =[20, 30, 42]

result =list1 +list2

print(str(result))

Output:

[10, 11, 12, 13, 14, 20, 30, 42]

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

list1 = [10, 11, 12, 13, 14]

list2 = [20, 30, 42]

print(“Before Concatenation:” + str(list1))

for x in list2 :

list1.append(x)

print (“After Concatenation:” + str(list1))

Output:

Before Concatenation:

[10, 11, 12, 13, 14]

After Concatenation:

[10, 11, 12, 13, 14, 20, 30, 42]

List comprehension:

Python list comprehension is an the alternative method to concatenate


two lists in python. List comprehension is basically the process of building
/ generating a list of elements based on an existing list.

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:

list1 = [10, 11, 12, 13, 14]

list2 = [20, 30, 42]

result = [j for i in [list1, list2] for j in i]

print ("Concatenated List:\n"+ str(result))

Output:

Concatenated list:

[10, 11, 12, 13, 14, 20, 30, 42]

Extend() method:

Python extend() method can be used to concatenate two lists in


python. The extend() function does iterate over the password parameter
and add the item to the list, extending the list in a linear fashion.

Syntax:
list.extend(iterable)

Example:

list1 = [10, 11, 12, 13, 14]

list2 = [20, 30, 42]

print("list1 before concatenation:\n" + str(list1))

list1.extend(list2)

print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1))

All the elements of the list2 get appended to list1 and thus the list1 gets
updated and results as output.

Output:

list1 before concatenation:

[10, 11, 12, 13, 14]

Concatenated list i.e ,ist1 after concatenation:

[10, 11, 12, 13, 14, 20, 30, 42]

 ‘*’ 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.

For example: Consider a list list = [1, 2, 3, 4].

The statement *list would replace by the list with its elements on the index
positions. So, it unpacks the items of the lists.

Example:

list1 = [10, 11, 12, 13, 14]

list2 = [20, 30, 42]

res = [*list1, *list2]

print ("Concatenated list:\n " + str(res))

Output:

In the above snippet of code, the statement res = [*list1, *list2]


replaces the list1 and list2 with the items in the given order i.e. elements of
list1 after elements of list2. This performs concatenation and results in the
below output.

Output:

Concatenated list:

[10, 11, 12, 13, 14, 20, 30, 42]

 Itertools.chain() method:

Python itertools modules’ itertools.chain() function can also be used to


concatenate lists in Python.

The itertools.chain() function accepts different iterables such as lists,


string, tuples, etc as parameters and gives a sequence of them as output.

It results out to be a linear sequence. The data type of the elements


doesn’t affect the functioning of the chain() method.

For example: The statement itertools.chain([1, 2], [‘John’,


‘Bunny’]) would produce the following output: 1 2 John Bunny

Example:

import itertools

list1 = [10, 11, 12, 13, 14]

83
list2 = [20, 30, 42]

res = list(itertools.chain(list1, list2))

print ("Concatenated list:\n " + str(res))

Output:

Concatenated list:

[10, 11, 12, 13, 14, 20, 30, 42]

6.8 REPETITION

Now, we are accustomed to using the '*' symbol to represent the


multiplication, but when the operand on the left of side of the '*' is a tuple,
it becomes the repetition operator. And The repetition of the operator it
will makes the multiple copies of a tuple and joins them all together.
Tuples can be created using the repetition operator, *.

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

Python's in operator lets you loop through all the members of a


collection (such as a list or a tuple) and check if there's a member in the
list that's equal to the given item.

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:

This will give the output −

True

6.10 BUILT-IN LIST FUNCTIONS AND METHODS

1. Built-in function:

Sr. No. Function with Description


1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.

85
2. Built-in methods:

Sr. Methods with Description


No.
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given

6.11 SUMMARY

Python lists are commanding data structures, and list


understandings are one of the furthermost convenient and brief ways to
create lists. In this chapter, we have given some examples of how you can
use list comprehensions to be more easy-to-read and simplify your code.
The list is the common multipurpose data type available in Python. A list is
an ordered collection of items. When it comes to creating lists, Python list
are more compressed and faster than loops and other functions used such
as, map(), filter(), and reduce().Every Python list can be rewritten in for
loops, but not every complex for loop can be rewritten in Python list
understanding. Writing very long list in one line should be avoided so as
to keep the code user-friendly. So list looks just like dynamic sized
arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python. A single list may
contain Datatype’s like Integers, Strings, and Objects etc. List loads all
the elements into memory at one time, when the list is too long, it will
reside in too much memory resources, and we usually only need to use a
few elements. A list is a data-structure that can be used to store multiple
data at once. The list will be ordered and there will be a definite count of
it. The elements are indexed allowing to a sequence and the indexing is
done with 0 as the first index. Each element will have a discrete place in
the sequence and if the same value arises multiple times in the sequence.

86
6.12 QUESTIONS

1. Explain List parameters with an example.


2. Write a program in Python to delete first and last elements from a list
3. Write a Python program to print the numbers of a specified list after
removing even numbers from it.
4. Write a python program using list looping
5. Write a Python program to check a list is empty or not
6. Write a Python program to multiplies all the items in a list
7. Write a Python program to remove duplicates from a list
8. Write a Python program to append a list to the second list
9. Write a Python program to find the second smallest number in a list.
10. Write a Python program to find common items from two lists

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

1. To understand when to use a dictionary.


2. To study how a dictionary allows us to characterize attributes with
keys and values
3. To learn how to read a value from a dictionary
4. To study how in python to assign a key-value pair to a dictionary
5. To understand how tuples returns values

88
7.2 TUPLES

A tuple in the Python is similar to the list. The difference between


the two is that we cannot change the element of the tuple once it is
assigned to whereas we can change the elements of a list

The reasons for having immutable types apply to tuples: copy


efficiency: rather than copying an immutable object, you can alias it (bind
a variable to a reference) ... interning: you need to store at most of one
copy of any immutable value. There’s no any need to synchronize access
to immutable objects in concurrent code.

Creating a Tuple:

A tuple is created by the placing all the elements inside


parentheses '()', separated by commas. The parentheses are the optional
and however, it is a good practice to use them.

A tuple can have any number of the items and they may be a
different types (integer, float, list, string, etc.).

Example:

# Different types of tuples

# Empty tuple

tuple = ()

print(tuple)

# Tuple having integers

tuple = (1, 2, 3)

print(tuple)

# tuple with mixed datatypes

tuple = (1, "code", 3.4)

print(tuple)

# nested tuple

tuple = ("color ", [6, 4, 2], (1, 2, 3))

print(tuple)

89
Output:
()
(1, 2, 3)

(1, 'code', 3.4)

('color', [6, 4, 2], (1, 2, 3))

A tuple can also be created without using parentheses. This is known as


tuple packing.

tuple = 3, 2.6, "color"

print(tuple)

# tuple unpacking is also possible

a, b, c = tuple

print(a) #3

print(b) # 4.6

print(c) # dog

Output:

( 3, 2.6, 'color')

2.6

color

7.3 ACCESSING VALUES IN TUPLES

There are various ways in which we can access the elements of a tuple.

1. Indexing:

We can use the index operator [] to access an item in a tuple,


where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying


to access an index outside of the tuple index range(6,7,... in this example)
will raise an IndexError.

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.

# Accessing tuple elements using indexing

tuple = ('a','b','c','d','e','f')

print(tuple[0]) # 'a'

print(tuple[5]) # 'f'

# IndexError: list index out of range

# print(tuple[6])

# Index must be an integer

# TypeError: list indices must be integers, not float

# tuple[2.0]

# nested tuple

tuple = ("color", [6, 4, 2], (1, 2, 3))

# nested index

print(tuple[0][3]) # 'o'

print(tuple[1][1]) #4

Output:
a

2. Negative Indexing:

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

Example:

# Negative indexing for accessing tuple elements

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:

# Accessing tuple elements using slicing

tuple = ('a','b','c','d','e','f','g','h','i')

# elements 2nd to 4th

# Output: ('b', 'c', 'd')

print(tuple[1:4])

# elements beginning to 2nd

# Output: ('a', 'b')

print(tuple[:-7])

# elements 8th to end

# Output: ('h', 'i')

print(tuple[7:])

# elements beginning to end

# Output: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')

print(tuple[:])

Output:
('b', 'c', 'd')

('a', 'b')

92
('h', 'i')

('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')

7.4 TUPLE ASSIGNMENT

One of the unique syntactic features of the Python language is the


ability to have a tuple on the left side of an assignment statement. This
allows you to assign more than one variable at a time when the left side is
a sequence.

In this example we have a two-element list (which is a sequence)


and assign the first and second elements of the sequence to the variables x
and y in a single statement.

Example:

tuple = [ 'red', 'blue' ]

x, y = tuple

Output:
x

'red'

'blue'

It is not magic, Python roughly translates the tuple assignment


syntax to be the following:

m = [ 'red', 'blue' ]

x = m[0]

y = m[1]

Output:
x

'red'

'blue'

7.5 TUPLES AS RETURN VALUES


Functions can return tuples as return values. Now we often want to
know some batsman’s highest and lowest score or we want to know to
93
find the mean and the standard deviation, or we want to know the year, the
month, and the day, or if we’re doing some ecological modeling we may
want to know the number of rabbits and the number of wolves on an island
at a given time. In each case, a function (which can only return a single
value), can create a single tuple holding multiple elements.

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

#Return (circumference, area) of a circle of radius r

c = 2 * 3.14159 * r

a = 3.14159 * r * r

return (c, a)

print(cirlce_info(10))

Output:

(62.8318, 314.159)

7.6 VARIABLE-LENGTH ARGUMENT TUPLES

Functions can take a variable number of arguments. The parameter


name that begins with the * gather the argument into the tuple. For
example, the print all take any number of the arguments and print them:
def printall(*args):

print args

The gather parameter can have any name you like, but args is
conventional. Here’s how the function works:

The complement of gather is scatter. If you have the sequence of


values and you want to pass it to the function as multiple as arguments,
you can use the * operator. For example, divmod take exactly two
arguments it doesn’t work with the tuple:

t = (7, 3)

divmod(t)

TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:


divmod(*t)
94
(2, 1)

Example -Many of the built-in functions are use variable-length argument


tuples. For example, max and min it can take any of number arguments:

max(1,2sum(1,2,3)

TypeError: sum expected at most 2 arguments, got 3,3)

But sum does not.

7.7 BASIC TUPLES OPERATIONS

Now, we will learn the operations that we can perform on tuples in


Python.

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

'x' not in tuple("string")

Output:
True

2. Concatenation:

Like we’ve previously discussed on several occasions,


concatenation is the act of joining. We can join two tuples using the
concatenation operator ‘+’.

(1,2,3)+(4,5,6)

Output:

(1, 2, 3, 4, 5, 6)

Note: Other arithmetic operations do not apply on a tuple.

3. Logical:

All the logical operators (like >,>=,..) can be applied on a tuple.

(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

Now, we will learn 2 different ways to concatenate or join tuples in


the python language with code example. We will use ‘+” operator and a
built-in sum() function to concatenate or join tuples in python.

 How to concatenate tuples into single/nested Tuples using sum():

2.1 Sum() to concatenate tuples into a single tuple:

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

#concatenate the tuple

tuples_concatenate = sum((tupleint, langtuple), ())

print('concatenate of tuples \n =',tuples_concatenate)

Output:

concatenate of tuples

96
= (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go')

Sum() to concatenate tuple into a nested tuple:

Now let us understand how we can sum tuples to make a nested


tuple.In this program we will use two tuples which are nested tuples,
please note the ‘,’ at the end of each tuples tupleint and langtuple.

let us understand example:

tupleint= (1,2,3,4,5,6),

langtuple = ('C#','C++','Python','Go'),

#concatenate the tuple

tuples_concatenate = sum((tupleint, langtuple), ())

print('concatenate of tuples \n =',tuples_concatenate)

Output:

concatenate of tuples

= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))


Concatenate tuple Using ‘+’ operator:

2.1 ‘+’ operator to concatenate two tuples into a single tuple:

In our first example, we will use the “+” operator to concatenate


two tuples and result in a single tuple.In this example we have two tuple
tupleint and langtuple,We are the concatenating these tuples into the single
tuple as we can see in output.

tupleint= (1,2,3,4,5,6)

langtuple = ('C#','C++','Python','Go')

#concatenate the tuple

tuples_concatenate = tupleint+langtuple

print('concatenate of tuples \n =',tuples_concatenate)

Output:

2.2 ‘+’ operator with a comma(,) to concatenate tuples into nested


Tuples:

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.

# comma(,) after tuple to concatenate nested tuple

tupleint= (1,2,3,4,5,6),

langtuple = ('C#','C++','Python','Go'),

#concatenate the tuple into nested tuple

tuples_concatenate = tupleint+langtuple

print('concatenate of tuples \n =',tuples_concatenate)

Output:
concatenate of tuples

= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))

7.9 REPETITION

Now, we are going to explain how to use Python tuple repetition


operator with basic syntax and many examples for better understanding.

Python tuple repetition operator (*) is used to the repeat a tuple,


number of times which is given by the integer value and create a new tuple
values.

Syntax:

<tuple_variable_name1> * N
N * <tuple_variable_name1>

Input Parameters:

 tuple_variable_name1 : The tuples that we want to be repeated.


 N : where is the number of times that we want that tuple to be repeated
ex: 1,2,3,……..n

Example:

data=(1,2,3,'a','b')

# tuple after repetition

print('New tuple:', data* 2)

98
Output:

New tuple: [1, 2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’, ‘b’]

In the above Example, using repetition operator (*), we have


repeated ‘data’ tuple variable 2 times by ‘data* 2’ in print statement and
created new tuple as [1, 2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’, ‘b’].

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

Note that in operator against dictionary checks for the presence of


key.

Example:

Output:
True

It can also be used to check the presence of a sequence or substring


against string.

Example:

my_str = "This is a sample string"

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

7.12 BUILT-IN TUPLE FUNCTIONS

Tuples support the following build-in functions:

Comparison:

If the elements are of the same type, python performs the


comparison and returns the result. If elements are different types, it checks
whether they are numbers.

If numbers, perform comparison.

If either the element is an number, then the other element is a


returned.

Otherwise, types are sorted alphabetically.

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.

tuple1 = ('a', 'b', 'c',’d’, 'e')

tuple2 = ('1','2','3')

tuple3 = ('a', 'b', 'c', 'd', 'e')

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'

Convert a list into tuple:

The built-in function tuple converts a list into a tuple:

list = [1,2,3,4,5]

tuple(list)

Out: (1, 2, 3, 4, 5)

Tuple concatenation:

Use + to concatenate two tuples:

tuple1 + tuple2

Out: ('a', 'b', 'c',’d’, 'e', '1', '2', '3')


101
7.13 CREATING A DICTIONARY

Creating a Dictionary:

To create the Python dictionary, we need to pass the sequence of


the items inside curly braces {}, and to separate them using a comma (,).
Each item has a key and a value expressed as an "key:value" pair.

The values can belong to the any of data type and they can repeat,
but the keys are must remain the unique.

The following examples are demonstrate how to create the Python


dictionaries:

Creating an empty dictionary:


dict_sample = {}

Creating a dictionary with integer keys:


dict_sample = {1: 'mango', 2: 'pawpaw'}

Creating a dictionary with mixed keys:


dict_sample = {'fruit': 'mango', 1: [4, 6, 8]}

We can also create a dictionary by explicitly calling the Python's dict()


method:
dict_sample = dict({1:'mango', 2:'pawpaw'})

A dictionary can also be created from a sequence as shown below:


Dictionaries can also be nested, which means that we can create a
dictionary inside another dictionary. For example:

dict_sample = {1: {'student1' : 'Nicholas', 'student2' : 'John', 'student3' : 'Mercy'},


2: {'course1' : 'Computer Science', 'course2' : 'Mathematics',
'course3' : 'Accounting'}}

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

To access the dictionary items, we need to pass the key inside


square brackets []. For example:
dict_sample = {

"Company": "Toyota",

"model": "Premio",

"year": 2012

x = dict_sample["model"]

print(x)

Output:

Premio

We created a dictionary named dict_sample. A variable named x is


then created and its value is set to be the value for the key "model" in the
dictionary.

7.15 UPDATING DICTIONARY

After adding a value to a dictionary we can then modify the


existing dictionary element. You use the key of the element to change the
corresponding value. For example:

dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}

dict_sample["year"] = 2014

print(dict_sample)

Output:

{'year': 2014, 'model': 'Premio', 'Company': 'Toyota'}

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 removal of an element from a dictionary can be done in


several ways, which we'll discuss one-by-one in this section:

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:

{'Company': 'Toyota', 'model': 'Premio'}

We called the del keyword followed by the dictionary name. Inside


the square brackets that follow the dictionary name, we passed the key of
the element we need to delete from the dictionary, which in this example
was "year". The entry for "year" in the dictionary was then deleted.

Another type to delete a key-value pair is to use the pop() method


and pass the key of the entry to be deleted as the argument to the function.
For example:

Output:
dict_sample = {

"Company": "Toyota",

"model": "Premio",

"year": 2012

dict_sample.pop("year")

print(dict_sample)

We invoked that pop() method by appending it with the dictionary


name. And, in this example the entry for "year" in the dictionary will be
deleted.
104
The popitem() method removes the last item of inserted into the
dictionary, without needing to specify the key. Take a look at the
following example:
dict_sample = {

"Company": "Toyota",

"model": "Premio",

"year": 2012

dict_sample.popitem()

print(dict_sample)

Output:

{'Company': 'Toyota', 'model': 'Premio'}

The last entry into the dictionary was "year". It has been removed
after calling the popitem() function.

But what if you want to delete the entire dictionary? It would be


difficult and cumbersome to use one of these methods on every single key.
Instead, you can use the del keyword to delete the entire dictionary. For
example:
dict_sample = {

"Company": "Toyota",

"model": "Premio",

"year": 2012

del dict_sample

print(dict_sample)

Output:

NameError: name 'dict_sample' is not defined

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.

However, your use-case may require you to just remove all


dictionary elements and be left with an empty dictionary. This can be
achieved by calling the clear() function on the dictionary:

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.

7.17 PROPERTIES OF DICTIONARY KEYS

Dictionary values have no restrictions. These can be any of


erratically Python object, either they standard objects or user-defined
objects. However, similar is not true for the keys.

There are two important points to be remember about the


dictionary keys:

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

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Name’: ‘Manni’};

print “dict[‘Name’]: “, dict[‘Name’];

Output:

dict[‘Name’]: Manni

dict = {[‘Name’]: ‘Zara’, ‘Age’: 7};

print “dict[‘Name’]: “, dict[‘Name’];

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

Traceback (most recent call last):

File “test.py”, line 3, in<module>

dict = {[‘Name’]: ‘Zara’, ‘Age’: 7};

TypeError: list objects are unhashable

7.18 OPERATIONS IN DICTIONARY

Below is a list of common dictionary operations:

create an empty dictionary

x = {}

create a three items dictionary

x = {"one":1, "two":2, "three":3}

access an element

x['two']

get a list of all the keys

x.keys()

get a list of all the value

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

remove all items

107
x.clear()

number of items
z = len(x)

test if has key

z = x.has_key("one")

looping over keys


for item in x.keys(): print item

looping over values

for item in x.values(): print item

using the if statement to get the values


if "one" in x:
print x['one']

if "two" not in x:
print "Two not found"

if "three" in x:
del x['three']

7.18 BUILT-IN DICTIONARY FUNCTIONS

A function is a procedure that can be applied on a construct to get a


value. Furthermore, it doesn’t modify the construct. Python gives us a few
functions that we can apply on a Python dictionary. Take a look.

1. len():

The len() function returns the length of the dictionary in Python.


Every key-value pair adds 1 to the length.

len(dict4)

Output
3
len({})

any({False:False,'':''})

An empty Python dictionary has a length of 0.

108
2. any():

Like it is with lists an tuples, the any() function returns True if


even one key in a dictionary has a Boolean value of True.

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}

But to see its effect, let’s first modify dict4.


Now, let’s apply the sorted() function on it.

Output:

[1, 3, 4]

As you can see, the original Python dictionary wasn’t modified.


dict4

This function returns the keys in a sorted list. To prove this, let’s see what
the type() function returns.

Output: <class ‘list’>

109
This proves that sorted() returns a list.

{3: 3, 1: 1, 4: 4}

dict4

type(sorted(dict4))

7.19 BUILT-IN DICTIONARY METHODS

A method is a set of the instructions to execute on the construct,


and it may be modify the construct. To do this, the method must be called
on the construct, let’s look at the available the methods for dictionaries.
dict4.keys()

Let’s use dict4 for this example.

1. keys():
dict_keys([3, 1, 4])

The keys() method returns a list of keys in a Python dictionary.


dict4.values()

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

1. To understand how python will raise an exception.


2. To create program to catch an exception using a try/except block.
3. To study the Python errors and exceptions.
4. To study creation and use of read and write commands for files.in
python
5. To understand how to open, write and close files in python

8.2 TEXT FILES

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

Steps for reading a text file in Python:

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.

Example, if the file is in the readme.txt stored in the sample folder


as the program, you have need to specify the path to the file as
c:/sample/readme.txt

A mode is in the optional parameter. This is the string that is


specifies the mode in which you want to open the file.

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

For example, to open a file whose name is the-zen-of-python.txt stored in


the same folder as the program, you use the following code:

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.

2) Reading text methods:

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

To close the file automatically without calling the close() method,


you use the with statement like this:
with open(path_to_file) as f:
contents = f.readlines()

In practice, you’ll use the with statement to close the file


automatically.

Reading a text file examples:

We’ll use the-zen-of-python.txt file for the demonstration.

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:

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

...

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

for line in lines:

count += 1

print(f'line {count}: {line}')

Output:

line 1: Beautiful is better than ugly.

line 2: Explicit is better than implicit.

line 3: Simple is better than complex.

...

8.3 THE FILE OBJECT ATTRIBUTES

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

print “Name of the file: “, fo.name

print “Closed or not : “, fo.closed

print “Opening mode : “, fo.mode

print “Softspace flag : “, fo.softspace

115
This produces the following result:

Name of the file: foo.txt

Closed or not : False

Opening mode : wb

Softspace flag : 0

8.4 DIRECTORIES

In this Python Directory tutorial, we will import the OS module to


be able to access the methods we will apply.
import os

How to Get Current Python Directory?

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.

To get it as a bytes object, we use the method getcwdb().


os.getcwdb()

Output:

b’C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32′

Here, we get two backslashes instead of one. This is because the


first one is to escape the second one since this is a string object.

type(os.getcwd())

<class 'str'>

To render it properly, use the Python method with the print statement.

print(os.getcwd())

116
Output:

Changing Current Python Directory


To change our current working directories in python, we use the chdir()
method.

This takes one argument- the path to the directory to which to change.

Output:

‘unicodeescape’ code can’t decode bytes in position 2-3: truncated


\UXXXXXXXX escape

But remember that when using backward slashes, it is


recommended to escape the backward slashes to avoid a problem.

Output:

How to Create Python Directory?

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:

[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘Christmas


Photos’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse
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’]

How to Rename Python Directory?:

To rename directories in python, we use the rename() method. It


takes two arguments- the python directory to rename, and the new name
for it.

os.rename('Christmas Photos','Christmas 2017')

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

How to Remove Python Directory?

We made a file named ‘Readme.txt’ inside our folder Christmas


2017. To delete this file, we use the method remove().

os.chdir('C:\\Users\\lifei\\Desktop\\Christmas 2017')

os.listdir()

Output:

[‘Readme.txt’]

8.5 BUILT-IN EXCEPTIONS

Illegal operations can raise exceptions. There are plenty of built-in


exceptions in Python that are raised when corresponding errors occur. We
can view all the built-in exceptions using the built-in local() function as

print(dir(locals()['__builtins__']))

follows:

locals()['__builtins__'] will return a module of built-in exceptions,


functions, and attributes. dir allows us to list these attributes as strings.
Some of the common built-in exceptions in Python programming along
with the error that cause them are listed below:

Exception Cause of Error


AssertionError fails. Raised when an assert statement

AttributeError Raised when attribute assignment or reference


fails.
EOFError Raised when the input() function hits end-of-file
condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is
called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of
range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits the interrupt key
(Ctrl+C or Delete).

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.

8.6 HANDLING EXCEPTIONS

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:

You do your operations here;

......................

except ExceptionI:

If there is ExceptionI, then execute this block.

except ExceptionII:

If there is ExceptionII, then execute this block.

......................

else:

If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −

A single try statement can have multiple except statements. This is


useful when the try block contains statements that may throw different
types of exceptions.

You can also provide a generic except clause, which handles any
exception.

After the except clause(s), you can include an else-clause. The


code in the else-block executes if the code in the try: block does not raise
an 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")

fh.write("This is my test file for exception handling!!")

except IOError:

print "Error: can\'t find file or read data"

else:
120
print "Written content in the file successfully"

fh.close()

This produces the following result:

Written content in the file successfully

8.7 EXCEPTION WITH ARGUMENTS

Why use Argument in Exceptions?

Using arguments for Exceptions in Python is useful for the


following reasons:

It can be used to gain additional information about the error encountered.

As contents of an Argument can vary depending upon different


types of Exceptions in Python, Variables can be supplied to the Exceptions
to capture the essence of the encountered errors. Same error can occur of
different causes, Arguments helps us identify the specific cause for an
error using the except clause.

It can also be used to trap multiple exceptions, by using a variable


to follow the tuple of Exceptions.

Arguments in Buil-in Exceptions:

The below codes demonstrates use of Argument with Built-in Exceptions:

Example 1:

try:

b = float(100 + 50 / 0)

except Exception as Argument:

print( 'This is the Argument\n', Argument)

Output:

This is the Argument

division by zero

Arguments in User-defined Exceptions:

The below codes demonstrates use of Argument with User-defined


Exceptions:
121
Example 1:

# create user-defined exception

# derived from super class Exception

class MyError(Exception):

# Constructor or Initializer

def __init__(self, value):

self.value = value

# __str__ is to print() the value

def __str__(self):

return(repr(self.value))

try:

raise(MyError("Some Error Data"))

# Value of Exception is stored in error

except MyError as Argument:

print('This is the Argument\n', Argument)

Output:
'This is the Argument
'Some Error data'

8.8 USER-DEFINED EXCEPTIONS

Creating User-defined Exception

Programmers may name their own exceptions by creating a new


exception class. Exceptions need to be derived from the Exception class,
either directly or indirectly. Although not mandatory, most of the
exceptions are named as names that end in “Error” similar to naming of
the standard exceptions in python. For example:
# A python program to create user-defined exception

# class MyError is derived from super class Exception

class MyError(Exception):

# Constructor or Initializer

def __init__(self, value):

122
self.value = value

# __str__ is to print() the value

def __str__(self):

return(repr(self.value))

try:

raise(MyError(3*2))

# Value of Exception is stored in error

except MyError as error:

print('A New Exception occured: ',error.value)

Ouput:

('A New Exception occured: ', 6)

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.

Exceptions: Python provides two important features to handle any


unexpected error in Python programs and to add debugging capabilities in
them .In Python, all exceptions must be occurrences of a class that arises
from BaseException. In a try statement with an except clause that
references a particular class, that clause further handles any exception
classes derived from that class .Two exception classes that are not
connected via sub classing are never equal, even if they have the same
name. User code can advance built-in exceptions. This can be used to test
an exception handler and also to report an error condition.

123
8.10 QUESTIONS

1. Write a Python program to read an entire text file


2. Write a Python program to append text to a file and display the text
3. Write a Python program to read a file line by line store it into a
variable
4. Write a Python program to count the number of lines in a text file
5. Write a Python program to write a list to a file
6. Write a Python program to extract characters from various text files
and puts them into a list.
7. What are exceptions in Python?
8. When would you not use try-except?
9. When will the else part of try-except-else be executed?
10. How can one block of except statements handle multiple exception? ...

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

You might also like