0% found this document useful (0 votes)
10 views58 pages

Python Programming Material

The document is a course material for Python programming at Mangayarkarasi College of Arts and Science for Women, detailing objectives, course units, and outcomes. It covers fundamental concepts of Python including syntax, data types, control statements, functions, and file handling. Additionally, it provides an introduction to Python, its features, and rules for variables and identifiers.

Uploaded by

kirubhacsmcw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views58 pages

Python Programming Material

The document is a course material for Python programming at Mangayarkarasi College of Arts and Science for Women, detailing objectives, course units, and outcomes. It covers fundamental concepts of Python including syntax, data types, control statements, functions, and file handling. Additionally, it provides an introduction to Python, its features, and rules for variables and identifiers.

Uploaded by

kirubhacsmcw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Mangayarkarasi College of Arts and Science for Women

Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

PYTHON PROGRAMMING

COURSE MATERIAL

DEPARTMENT OF COMPUTER SCIENCE


& APPLICATIONS
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Objectives
 Describe the core syntax and semantics of Python programming language.
 Discover the need for working with the strings and functions.
 Illustrate the process of structuring the data using lists, dictionaries, tuples and sets.
 Understand the usage of packages and Dictionaries

UNIT I
Basics of Python Programming: History of Python-Features of Python-Literal-Constants-Variables -
Identifiers–Keywords-Built-in Data Types-Output Statements – Input Statements-Comments –
Indentation- Operators-Expressions-Type conversions. Python Arrays: Defining and Processing Arrays
– Array methods.
UNIT II
Control Statements: Selection/Conditional Branching statements: if, if-else, nested if and if-elif-else
statements. Iterative Statements: while loop, for loop, else suite in loop and nested loops. Jump
Statements: break, continue and pass statements.
UNIT III
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-Return Statement.
Function Arguments: Required Arguments, Keyword Arguments, Default Arguments and Variable
Length Arguments- Recursion. Python Strings: String operations- Immutable Strings - Built-in String
Methods and Functions - String Comparison.Modules: import statement- The Python module – dir()
function – Modules and Namespace – Defining our own modules.
UNIT IV
Lists: Creating a list -Access values in List-Updating values in ListsNested lists -Basic list operations-
List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple – Nested tuples–
Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating and Deleting Elements
in a Dictionary – Dictionary Functions and Methods - Difference between Lists and Dictionaries.
UNIT V
Python File Handling: Types of files in Python - Opening and Closing files-Reading and Writing files:
write() and writelines() methods- append() method – read() and readlines() methods – with keyword –
Splitting words – File methods - File Positions- Renaming and deleting files.
Course Outcomes

 Develop and execute simple Python programs.


 Write simple Python programs using conditionals and looping for solving problems.
 Decompose a Python program into functions.
 Represent compound data using Python lists, tuples, dictionaries, etc.

TEXT BOOK
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

1. ReemaThareja, “Python Programming using problem solving approach”, First Edition, 2017,
Oxford University Press.
2. Dr. R. NageswaraRao, “Core Python Programming”, First Edition, 2017, Dream tech
Publishers.

Introduction
What is a Programming Language?
A Programming language is a Computer Language. Programming is giving a set of
instructions to a computer to execute.
Programming Languages are used in Computer Programming to solve real time
problems, implement algorithms, create applications & produce various kinds of
output.
There are two types of Programming Languages( High level /Low Level)
Examples: C,C++, Java, Python etc.
What is Python?
Python is a general-purpose interactive, interpreted, object oriented and High Level
programming Language. It was created by Guido Van Rossum during 1985- 1990.
How to Install?
Visit the official download page for Python on the Windows operating system
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-
Introduction to Python:
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

 Web development (server-side),


 Software development,
 Mathematics,
 System scripting.

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-
Features of Python:
1. Simple
Python is a simple and minimalistic language. Reading a good Python program feelsalmost like reading
English language.
2. Easy to learn
Python uses very few keywords. Python has an extraordinarily simple syntax and simple program
structure.
3. Open Source: There is no need to pay for Python software. Python is FLOSS (Free/Library and Open
Source Software). Its source can be read, modified and used in programs as desired by the programmers.
4. High level language
When you write programs in Python, you never need to bother aboutthe lowlevel details such as
managing the memory used by your program, etc.
5. Dynamically typed
Python provides IntelliSense. IntelliSense to make writing your code easier and more error-free.
IntelliSense option includes statement completion, which provides quick access to valid member
function or variables, including global,via the member list. Selecting from the list inserts the member
into your code.
6. Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many
platforms. All your Python programs can work on any of these platforms without requiring any changes
at all if you are careful enough to avoid any system-dependent features.
7. Platform independent
When a Python program is compiled using a Python compiler, it generates byte code. Python’s byte
code represents a fixed set of instructions that run on all operating systems and hardware. Using a
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Python Virtual Machine (PVM), anybody can run these byte code instructions on any computer system.
Hence, Python programs are not dependent on any specific operating system.
8. Procedure and Object Oriented
Python supports procedure-oriented programming as well as object-oriented programming. In rocedure-
oriented languages, the program is built around procedures or functions which are nothing but reusable
pieces of programs. In object- oriented languages, the program is built around objects which combine
data and functionality.

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-
What is a Literals?

These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals, floating
point literals, and imaginary literals.
A literal is a sequence of one or more characters that stands for itself.

Python has different types of literal such as:

1. String literals
2. Numeric literals
3. Boolean literals

String literals
A string is literal and can be created by writing a text(a group of Characters ) surrounded by a
single(”), double(“), or triple quotes. By using triple quotes we can write multi-line strings or
display them in the desired way.

a) Single-line String- Strings that are terminated within a single-line are known as Single line
Strings.

x='hello'
A multiline string can be defined by enclosing characters expanding to multiple lines in triple quotes as
follows.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

myString="""This is a
multiline string.
"""

Numeric literals

Numeric literals are used to represent numbers in a program. In python we have different types of
numeric literals such as integers, floating point numbers and complex numbers. # Python int Literal val1
= 25 print(val1)

# Python float Literal val2 =


11.89 print(val2)

# Python complex Literal val3 =


6+2.9j print(val3)

# Python hexadecimal Literal val4 =


0x12d print(val4)

# Python octal literal val5 = o021


print(val5)

Output
25
11.89
(6+2.9j)
301
17

Boolean literals

Boolean has two values i.e. True and False. True is for 1 and False 0.

a = (1 == True)
= (1 == False)
b

print(a)
print(b)

Output
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

True
False

Indentation in Python
Indentation in Python is used to create a group of statements that are executed as a block. Many
popular languages such as C, and Java uses braces ({ }) to define a block of code, and Python uses
indentation.

What is Indentation in Python?


Indentation in Python refers to the whitespaces at the start of the line to indicate a block of code. We
can create an indentation using space or tabs. When writing Python code, we have to define a group
of statements for functions and loops. This is done by properly indenting the statements for that
block.

The leading whitespaces (space and tabs) at the start of a line are used to determine the indentation
level of the line. We have to increase the indent level to group the statements for that code block.
Similarly, reduce the indentation to close the grouping.

if pwd == 'apple':
print('Logging on ...')
else:

print('Incorrect
password.')

print('All done!')
What is a variable?

Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store integers, decimals or characters in these
variables.

Rules for Python variables:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

(A-z, 0-9, and _ )


• Variable names are case-sensitive (age, Age and AGE are three different variables)

Assigning Values to Variables:

Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable

For example

a= 100 # An integer assignment


b = 1000.0 # A floating point
c = "John" # A string
print (a) print (b)
print (c)

Output
100
1000.0
John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables.
a,b,c = 1,2,"mcw“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "mcw" is assigned to the variable c
Variables do not need to be declared with any particular type and can even change type after
they have been set.

Example

x = "awesome" print("Python is " +


x)
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Output
Python is awesome

Example

x = "Python is " y =
"awesome"
z = x + y print(z)

Output
Python is awesome
What are keywords?
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function
name or any other identifier. They are used to define the syntax and structure of the Python language
In Python, keywords are case sensitive. There are 33 keywords in Python

What are Identifiers?


Python Identifier is the name we give to identify a variable, function, class, module or other object.
That means whenever we want to give an entity a name, that’s called identifier.

Rules for Identifiers?

• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen, all
are valid example.
• An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
Keywords cannot be used as identifiers.  We cannot use special symbols like !, @, #, $, %
etc. in our  Identifier. Identifier can be of any length.

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-

o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-
Python Numeric Data Type
Python numeric data types store numeric values. Number objects are created when you assign a value
to them.

var1 = 1 var2 = 10
var3 = 10.023

Python supports four different numerical types −


• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))

# complex variable. c=10+3j


print("The type of variable having value", c, " is ", type(c))
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Sequence Type

In Python, the sequence data-type is an ordered or paired collection of similar or different data
values. The sequence data-type allows us to store multiple object values in an efficient and
organized manner.

• Variables with sequence data-type in Python are used to store values with characters, alphabets,
words, lists etc.

• Like numeric data-type, sequence data-type also has three further datatypes.

Following are the three types of sequence data-type present in Python:

•String
•List
•Tuple
Python String Data Type

Python Strings are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the
slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator in Python.

str = 'Hello World!'


print (str) # Prints complete string
print (str[0]) # Prints first character of the string print (str[2:5]) #
Prints characters starting from 3rd to 5th print (str[2:]) # Prints string
starting from 3rd character print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

This will produce the following result

Hello World!
H
llo llo
World!
Hello World!Hello World! Hello
World!TEST
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

List Datatype

Lists in Python are like arrays in C, but lists can contain data of different types. The things put away
in the rundown are isolated with a comma (,) and encased inside square sections [].

To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings,
the list is handled by the concatenation operator (+) and the repetition operator (*).

lis = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


t
tinylist = [123, 'john']
list
list ) # Prints complete list
( list
list
( [0]) # Prints first element of the list
print
print ( [1: 3
]) # Prints elements starting from 2nd till 3rd
print [2 :])
print ( # Prints elements starting from 3rd element
print
print 2
tin ylist * # Prints list two times
)
(
# Prints concatenated lists
list + tinylist )
(

['abcd', 786, 2.23, 'john', 70.2] abcd


[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Tuple
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as readonly lists.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123,


'john')
print (tuple) # Prints the complete tuple print (tuple[0]) # Prints first element of the
tuple
print (tuple[1:3])# Prints elements of the tuple starting from 2nd till 3rd print (tuple[2:])#
Prints elements of the tuple starting from 3rd element print (tinytuple * 2) # Prints the
contents of the tuple twice print (tuple + tinytuple) # Prints concatenated tuples

('abcd', 786, 2.23, 'john', 70.2) abcd


(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Python Basic Input and Output

Python Output
In Python, we can simply use the print() function to print output. For example,

print('Good Morning!')
print('It is rainy today')

Good Morning!
It is rainy today

print('Good Morning!', end= ' ')


print('It is rainy today')

Good Morning! It is rainy today

number = -10.6 name =


"PythonProgramming"
print(5) print(number)
print(name)
print(' PythonProgramming is ' + 'awesome.')

5
-10.6
PythonProgramming is awesome

Output formatting
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method.

x = 5 y = 10

print('The value of x is {} and y is {}'.format(x,y))

Python Input

While programming, we might want to take the input from the user. In Python, we can use the
input() function.

input(prompt)

Python User Input

# using input() to take user input


num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))

Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>

It is important to note that the entered value 10 is a string, not a number. So, type(num) returns <class
'str'>.

num = int(input('Enter a number: '))

The data type of the user input is converted from string to integer

Operators in Python programming


An operator is a symbol that operates on one or more operands. An operand is a value or a variable
on which we perform the operation. Consider the example 6+9, Here 6 and 9 are called operands
and + is called operator. Python provides many operators described as follows:
• Arithmetic Operators
• Assignment Operators
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

• Comparison Operators
• Logical Operators
• Membership Operators
• Bitwise Operators
• Identity Operators

Arithmetic Operator

The Python Arithmetic operators are used to perform basic mathematical operations. The Arithmetic
operators are given in below list. Suppose x and y are two variable with values x=30 and y=10 and
the result of the operation is also given in below list:

Operators Description Example

+ (Addition) It is used to add two operands. x + y =40

It is used to subtract two operands. It will give


- (Subtraction) the negative value if the first operand is less than x – y =20 or y – x = -20
the second operand.

* It is used to multiply the value on either side of


x * y = 300
(Multiplication) operators.

It divides the first operand by the second


/ (Divide) x/y = 3.0
operand and returns the quotient.

// It is used to divide and returns the integer value x//y=3 or x=30 y=7 then
(Floor Division) of the quotient. x//y=4

% (Modulus) It returns reminder after division. x//y = 0

It is used to calculate the power of the first x = 5, y = 2 then x ** 2 =


**(Exponent)
operand. 25

Assignment Operators
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

The assignment operator is used to assign the value of the right operand to the left operand. The list
of assignment operators is given below. Suppose we provide x = 20 and y = 10 then results are
following:

Operator Description Examples

Assigns value of the right expression to the left


= x = 20
operand.

It is used to add the value on either side and assign


x+=y is equal to x=x +
+= expression on the left side. Result is assigned to the
y therefore x = 30
right operand.

It is used to subtract the value on either side and


assign expression on the left side. Result is assigned x-=y is equal to x=x - y
-=
to the right operand. therefore x = 10

It multiplies the operands and modifies value x*=y is equal to x =


*=
assigned to right operand. x*y therefore x = 200

It divides the operands and modifies value x/=y is equal to x =


/=
assigned to right operand. x/y therefore x = 2.0

It calculates the modulus of the values on either


x%=y is equal to x =
%= side. And assigns result to the expression on the
x% y therefore x = 0
left.
x=20,y=2 x**=2 is
It evaluates exponential (power) calculation on
**= equal to x=x**y
operators and assigns value to the left operand
therefore x=400

It performs floor division on operators and assign x//=y is equal to x =


//=
value to the left operand x//y therefore x = 2
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Comparison operators
Python provides a few comparison operators which are commonly used to compare the value of the
two operands. The comparison of these value returns Boolean true or false. These operators are
described in the below table. We have assigned x=10 and y= 15.

Operators Description Examples

== It returns true if the values of the two operands are equal. x==y is False

!= It returns false if the values of the two operands are not equal. x!=y is True

If the left operand is less than or equal to the right operand, then
<= x<=y is True
it will evaluate True

If the left operand is greater than or equal to the right operand,


>= x>=y is False
then it evaluates True

<> This operator is similar to !=(not equal) x<>y is True

If the left operand is greater than the right operand, then it


> x>y is False
evaluates True

If the right operand is greater than the left operand, then it


< x<y is True
evaluates True

Logical Operators
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

There are three logical operators and, or and not which are used in the conditional statement.

Operators Description Examples

The condition becomes true if both expressions are


and true. True and False= False

The condition becomes true if any expression is


or True or False= True
true.

If an expression x is true then not(x) will be false


not not(True)= False
or vica versa.

Membership Operators
Membership operators are used to check whether a particular element is a member of a sequence
such as string, list, tuple etc. There are two membership operators described in the below table:

Operator Description Examples

It is evaluated to be true if an element on left side present in


in 3 in [1,3,4]=True
the given right side sequence

It is evaluated to be false if an element on the left side is 3 not in


not in
present in the given right side sequence [1,3,5]=False
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Identity Operators

The identity operators are following

Operator Description Examples

If the both operators are referred to same object then it a = 5, b=5 a is b


is
evaluates true. =True
a = [1,2,3], b
If the both operators are referred to same object then it
is not =[1,2,3] a is not b
evaluates false.
=True

Operator Precedence

Operator Precedence (Decreasing


Description
Order)

** The Exponential have the highest priority

~+- Complement, unary plus and minus

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction


>> << Right and left bitwise shift

& Bitwise 'AND'


^| Bitwise `OR' and regular `OR'

<= < > >= Comparison operators


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Logical operators

not or and Logical operators

what are expressions?

An expression is a combination of values, variables, operators, and calls to functions. If you type an
expression at the Python prompt, the interpreter evaluates it and displays the result:

>>> 1 + 1=2

Conditional expressions
Syntax: true value if Condition else false value
>>> x = "1" if True else "2"
>>> x
'1'
What is a statement in Python?
A statement is an instruction that a Python interpreter can execute.
Python statement ends with the token NEWLINE character. It means each line in a Python script is a
statement. A Python script usually contains a sequence of statements. If there is more than one
statement, the result appears only one time when all statements execute.
# Statement 1
print ('Hello') l =
10; b = 5
print('Area of rectangle:', l * b)

# Statement 2
x = 20
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

# Statement 3 print(x)
Output

Hello
50
20
Multiple statements
Python statement ends with the token NEWLINE character. But we can extend the statement over
multiple lines using line continuation character (\ ).
addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
print(addition) #
Output: 280

The type() function


Python also enables us to check the data-type of the variables through which we can know which
data-type value the variable is holding in the program. We need to use the type() function inside
Python to check the data-type of the variable. When we run the type() function, it will return us the
data-type of the variable we wrote inside the function.

x=5y
= 2.3

z = 'Hello Python Developers'


#check the data-type of these variables
print(type(x)) print(type(y)) print(type(z))

Output
<class 'int'>

<class 'float'>

<class 'str'>
What is an Array in Python?
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together. This makes it easier to calculate the position of each element by
simply adding an offset to a base value, i.e., the memory location of the first element of the array
(generally denoted by the name of the array).
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Create an Array in Python


Array in Python can be created by importing an array module. array(data_type, value_list) is used to
create array in Python with data type and value list specified in its arguments.

import array as arr


a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
output:
The new created array is : 1 2 3

The new created array is : 2.5 3.2 3.3

Accessing Elements from the Array


In order to access the array items refer to the index number. Use the index operator [ ] to access an
item in a array in Python. The index must be an integer. Below, code shows first how to Python
import array and use of indexing to access elements in arrays. The a[0] expression accesses the first
element of the array a, which is 1. The a[3] expression accesses the fourth element of the array a,
which is 4. Similarly, the b[1] expression accesses the second element of the array b, which is 3.2, and
the b[2] expression accesses the third element of the array b, which is 3.3.
Python3
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Output :
Access element is: 1
Access element is: 4
Access element is: 3.2
Access element is: 3.3
Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

UNIT II

1. Python if statement
The syntax of if statement in Python is:
if condition:

# body of if statement
Example 1: Python if Statement

number = 10

# check if number is greater than 0 if number


> 0:
print('Number is positive.')
print('The if statement is easy')

Output

Number is positive.
The if statement is easy

2. Python if...else Statement


An if statement can have an optional else clause.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

if condition:
# block of code if condition is True
else:
# block of code if condition is False

The if...else statement evaluates the given condition:


If the condition evaluates to True,
• the code inside if is executed
• the code inside else is skipped
If the condition evaluates to False,
• the code inside else is executed
• the code inside if is skipped

Example 2. Python if...else Statement


number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement is always executed')
Output

The i statement evaluates condition.


1. If condition is evaluated to True, the code inside the body of i is executed.
2. If condition is evaluated to False , the code inside the body of if is skipped
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Positive number
This statement is always executed

Python if...elif...else Statement


The if...else statement is used to execute a block of code among two alternatives. However, if we need
to make a choice between more than two alternatives, then we use the if...elif...else statement.
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

Here,

1. If condition1 evaluates to true , code block 1 is executed.


2. If condition1 evaluates to false, then condition2 is evaluated.
 If condition2 is true , code block 2 is executed.
 If condition2 is false , code block 3 is execute

Python Nested if statements(MULTIWAY SELECTION)


We can also use an if statement inside of an if statement. This is known as a nested if statement.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

# outer if statement if
condition1:
# statement(s)

# inner if statement if
condition2: #
statement(s)

number = 5
# outer if statement if
(number >= 0): #
inner if statement if
number == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')
# outer else statement else:
print('Number is negative')

# Output: Number is positive


number = 5
# outer if statement if
(number >= 0): #
inner if statement if
number == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')
# outer else statement else:
print('Number is negative')

# Output: Number is positive


Looping Statements in Python(ITERATION CONTROL)

The flow of the programs written in any programming language is sequential by default. The first
statement in a function is executed first, followed by the second, and so on. In a programming
language, a looping statement contains instructions that continually repeat until a certain condition is
reached.

Types of Loops
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

In Python, there are three different types of loops: for loop, while loop, and nested loop.

For Loop (FINITE LOOP)


The for loop is used in the case where a programmer needs to execute a part of the code until the
given condition is satisfied. The for loop is also called a pre-tested loop. It is best to use for loop if
the number of iterations is known in advance.
Syntax:
for variable in sequence:
statements(s) Input: a
= 5 for i in range(0, a):
print(i)
Output:
0
1
2
3
4
Example1

languages = ['Swift', 'Python', 'Go', 'JavaScript']

# run a loop for each item of the list for language


in languages:
print(language)

Output:
Swift
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Python
Go
JavaScript

Example2

Python for Loop with Python range()

# use of range() to define a range of values values = range(4)

# iterate from i = 0 to i = 3 for i in


values:
print(i)

Output:
2
3

Using a for Loop Without Accessing Items


languages = ['Swift', 'Python', 'Go']
for language in languages:
print('Hello') print('Hi')

Output:

Hello Hi
Hello Hi
Hello
Hi

Python for loop with else

A for loop can have an optional else block. The else part is executed when the loop is exhausted (after
the loop iterates through every item of a sequence).

digits = [0, 1, 5]
for i in digits:
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

print(i) else:
print("No items left.")

Output:

5
No items left.

While Loop (INDEFINITE LOOP)

In Python, the while loop executes the statement or group of statements repeatedly while the given
condition is True. And when the condition becomes false, the loop ends and moves to the next
statement after the loop.
Syntax:
While condition: statement(s)
Input: count = 0 while
(count < 5): count =
count + 1 print("I CA A")
Output: I CA A
I CA A
I CA A
I CA A
I CA A

Example: Python while Loop


# program to display numbers from 1 to 5
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

# initialize the variable i = 1 n


=5

# while loop from i = 1 to 5 while


i <= n: print(i) i = i + 1

1
2
3
4
5
Infinite while Loop in Python
If the conditio of a loop is always Tru , the loop runs for infinite times (until the
n e
memory is full). For example,

age = 32

# the test condition is always True while age >


18:
print('You can vote')

Python While loop with else


In whi loop may have an el blo
Python, a le optional se ck.
counter = 0

w
h
i
l
e

c
o
u
n
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

t
e
r

<

3
:

prin
t('I
nsi
de
loo
p')
cou
nter
=
cou
nter
+1
else
:
print('Inside else')

Output

Inside loop
Inside loop
Inside loop
Inside else

Nested Looping statements in Python


The Python programming language allows programmers to use one looping statement inside another
looping statement.

Syntax:
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

#for loop statement for variable in


sequence: for variable in
sequence: statement(s)
statement(s)

#while loop statement while


condition: while condition:
statement(s) statement(s)
Input: for i in range(1, 7):
for j in range(i): print(i,
end=' ') print()

Output:
1
22
333
4444
55555
666666

UNIT III
Functions:
Functions and its use: Function is a group of related statements that perform a specific task.
Basically, we can divide functions into the following two types:
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

1. Built-in functions - Functions that are built into Python. Ex: abs(), all().ascii(), bool()………so
on….
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.


def add (x,y): sum = x + y return sum
print("The sum is", add (5, 20))

Output:
The sum is 25

Parameters and Arguments:


Parameters are passed during the definition of function while Arguments are passed during the
function call.
Example:
a and b are parameters
def add(a,b):
return a+b
result=add(12,13)
print(result)
There are two types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments

Syntax:
def function name():
statements
...
Function name()

1. add_number(2, 3)
Sum: 5
Mangayarkarasi College of Arts and Science for Women
Sum: 10
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Sum: 15 Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Both values are passed during the function call. Hence, these values are used instead of the default
Keyword
values. Argument
In keyword arguments, arguments are assigned based on the name of arguments.
2. add_number(2)
def ICA(firstname, lastname):
Only one value is passed during the function call. So, according to the positional argument 2 is
print
('FirstName:' , firstname)
assigned to argument a, and the default value is used for parameter b.
print
('LastName:', lastname)
3. add_number()
No value is passed during the function call. Hence, default value is used for both parameters a and b
ICA(lastname
= 'DEVI'
, firstname
= 'UMA'
)

Output

FirstName:UMA
LastName:DEVI

Hence, firstname in the function call is assigned to firstname in the function definition.
Similarly, lastname in the function call is assigned to lastname in the function definition.

xxxxxxxxxxxxxxxxxxxxx Variable scope:


In Python, we can declare variables in three different scopes: local scope, global, and nonlocal scope.
A variable scope specifies the region where we can access a variable.
Based on the scope, we can classify Python variables into three types:
• Local Variables
• Global Variables
• Nonlocal Variables
Python Local Variables
When we declare variables inside a function, these variables will have a local scope
(within the function). We cannot access them outside the function.

These types of variables are called local variables. For example,


defgreet():
# localvariable
message = 'Hello'
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Python Global Variables


In Python, a variable declared outside of the function or in global scope is known as a global variable.
This means that a global variable can be accessed inside or outside of the function.
# declare global variable message =
'Hello'
Output
def greet():
Local Hello
# declare
Global local variable
Hello print('Local', message)
greet() print('Global',
message)
Python Nonlocal Variables
In Python, nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.

# outside function def


outer():
message = 'local'

# nested function def


inner():

# declare nonlocal variable nonlocal


message
message = 'nonlocal'
print("inner:", message)
inner() print("outer:",
message)
outer()

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Types of Functions in Python


1. With no argument and no return value.
2. With no argument and with a Return value.
3. Argument and No Return Value.
4. With argument and return value.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Calling non value with a Return function


In this type of function in Python, We won’t pass any arguments to it while defining, declaring, or
calling it. When we call this type of function, it returns some value.

def Multiplication():
a = 10 b =
25 Multi = a
* b return
Multi
print("After Calling the Multiplication : ", Multiplication())

Within the Multiplication (), We haven’t passed any arguments /parameters. Next, We declared the
integer variables of Multi, a, b, and we assigned 10 to a, and 25 to b. In the next line, we Multiplied
both a and b using an Arithmetic operator ( * ).
Calling Value with Return Statement
This type of Python function allows us to pass the arguments to it while calling it. This type of
function returns some value when we call them. This type of userdefined method called a fully
dynamic, means it provides maximum control to the end-user.

def Addition(a, b):


Sum = a + b return
Sum
print("After Calling :", Addition(25, 45))

Within the Addition(a, b), We declared the variables of Sum, and also, we also had (a, b) arguments
in it. It means this allows the user to pass two values.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Python Recursion
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

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.
def factorial(x):
"""This is a recursivefunction
to find the factorialof an integer"""

if x == 1:
return 1
else:
return (x * factorial(x
-1))
num = 3
print("The factorialof", num, "is", factorial(num))

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.
factorial(3) # 1st call with 3 3 * factorial(2)
# 2nd call with 2
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

Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems using recursion.
•  Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
• Recursive functions are hard to debug.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

String operation is a sequence of Unicode characters that is enclosed in quotation marks. In this
article, we will discuss the in-built string functions i.e. the functions provided by Python to operate on
strings.
Case Changing of Python String Methods
The below Python functions are used to change the case of the strings. Let’s look at some Python
string methods with examples:
 lower(): Converts all uppercase characters in a string into lowercase
 upper(): Converts all lowercase characters in a string into uppercase
 title(): Convert string to title case
 swapcase(): Swap the cases of all characters in a string
 capitalize(): Convert the first character of a string to uppercase
Example: Changing the case of Python String Methods
 Python3

# Python3 program to show the

# working of upper() function

text = 'geeKs For geEkS'

# upper() function to convert

# string to upper case

print("\nConverted String:")

print(text.upper())

# lower() function to convert

# string to lower case

print("\nConverted String:")

print(text.lower())
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

# converts the first character to

# upper case and rest to lower case

print("\nConverted String:")

print(text.title())

# swaps the case of all characters in the string

# upper case character to lowercase and viceversa

print("\nConverted String:")

print(text.swapcase())

# convert the first character of a string to uppercase

print("\nConverted String:")

print(text.capitalize())

# original string never changes

print("\nOriginal String")

print(text)

Output
Converted String:
GEEKS FOR GEEKS
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Converted String:
GEEkS fOR GEeKs

Original String
geeKs For geEkS
Time complexity: O(n) where n is the length of the string ‘text’
Auxiliary space: O(1)
List of String Methods in Python
Here is the list of in-built Python string methods, that you can use to perform actions on string:

Function Name Description

Converts the first character of the string to a


capitalize()
capital (uppercase) letter

casefold() Implements caseless string matching

center() Pad the string with the specified character.

Returns the number of occurrences of a


count()
substring in the string.

Encodes strings with the specified encoded


encode()
scheme

endswith() Returns “True” if a string ends with the given


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Function Name Description

suffix

Specifies the amount of space to be substituted


expandtabs()
with the “\t” symbol in the string

Returns the lowest index of the substring if it is


find()
found

format() Formats the string for printing it to console

Formats specified values in a string using a


format_map()
dictionary

Returns the position of the first occurrence of a


index()
substring in a string

Checks whether all the characters in a given


isalnum()
string is alphanumeric or not

Returns “True” if all characters in the string are


isalpha()
alphabets

Returns true if all characters in a string are


isdecimal()
decimal

Returns “True” if all characters in the string are


isdigit()
digits

Check whether a string is a valid identifier or


isidentifier()
not
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Function Name Description

Checks if all characters in the string are


islower()
lowercase

Returns “True” if all characters in the string are


isnumeric()
numeric characters

Returns “True” if all characters in the string are


isprintable()
printable or the string is empty

Returns “True” if all characters in the string are


isspace()
whitespace characters

Returns “True” if the string is a title cased


istitle()
string

Checks if all characters in the string are


isupper()
uppercase

join() Returns a concatenated String

Left aligns the string according to the width


ljust()
specified

Converts all uppercase characters in a string


lower()
into lowercase

Returns the string with leading characters


lstrip()
removed

maketrans() Returns a translation table


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Function Name Description

Splits the string at the first occurrence of the


partition()
separator

Replaces all occurrences of a substring with


replace()
another substring

rfind() Returns the highest index of the substring

Returns the highest index of the substring inside


rindex()
the string

Right aligns the string according to the width


rjust()
specified

rpartition() Split the given string into three parts

Split the string from the right by the specified


rsplit()
separator

rstrip() Removes trailing characters

splitlines() Split the lines at line boundaries

Returns “True” if a string starts with the given


startswith()
prefix

Returns the string with both leading and trailing


strip()
characters

swapcase() Converts all uppercase characters to lowercase


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Function Name Description

and vice versa

title() Convert string to title case

Modify string according to given translation


translate()
mappings

Converts all lowercase characters in a string


upper()
into uppercase

Returns a copy of the string with ‘0’ characters


zfill()
padded to the left side of the string

String comparison is a fundamental operation in any programming language, including Python. It


enables us to ascertain strings’ relative positions, ordering, and equality. Python has a number of
operators and techniques for comparing strings, each with a specific function. We will examine
numerous Python string comparison methods in this article and comprehend how to use them.
Input: "Geek" == "Geek"
"Geek" < "geek"
"Geek" > "geek"
"Geek" != "Geek"
Output: True
True
False
False
Explanation: In this, we are comparing two strings if they are equal to each other.
Python String Comparison
 Using Relational Operators
 Using Regular Expression
 Using Is Operator
 Creating a user-defined function.
Equal to String Python using Relational Operators
The relational operators compare the Unicode values of the characters of the strings from the zeroth
index till the end of the string. It then returns a boolean value according to the operator used. It checks
Python String Equivalence.

PYTHON MODULES
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

A module allows you to log ically org anize your Pythoncode. Grouping related code into a module
makes the

code easier to understand and use. A module is a Pythonobject witharbitrarily named attributes that
you canbind

and reference.

Simply, a module is a file consisting of Pythoncode. A module candefine functions, classes and
variables. A

module canalso include runnable code.

Example:

The Pythoncode for a module named aname normally resides ina file named aname.py. Here's
anexample of a

simple module, support.py

def print_func( par ):

print "Hello : ", par

return

The import Statement:

You canuse any Pythonsource file as a module by executing animport statementinsome other
Pythonsource

file. The import has the following syntax:

import module1[, module2[,... moduleN]

Whenthe interpreter encounters animport statement, itimports the module if the module is presentinthe
search

path. A searchpathis a list of directories thatthe interpreter searches before importing a module. For
example,

to importthe module hello.py, youneed to putthe following command atthe top of the script:

#!/usr/bin/python

# Import module support

import support
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

# Now you can call defined function that module as follows

support.print_func("Zara")

Whenthe above code is executed, it produces the following result:

Hello : Zara

A module is loaded only once, reg ardless of the number of times itis imported. This prevents the
module

executionfromhappening over and over ag ainif multiple imports occur.

The from...import Statement

Python's from statementlets you import specific attributes froma module into the current namespace.
The

from...import has the following syntax:

from modname import name1[, name2[, ... nameN]]

For example, to importthe functionfibonaccifromthe module fib, use the following statement:

from fib import fibonacci

This statement does notimportthe entire module fib into the current namespace; itjustintroduces the
item

fibonaccifromthe module fib into the g lobal symboltable of the importing module.

The from...import * Statement:

Itis also possible to import allnames froma module into the current namespace by using the following
import

statement:

from modname import *

This provides aneasy way to import allthe items froma module into the current namespace; however,
this

statement should be used sparing ly.

Locating Modules:

Whenyou import a module, the Pythoninterpreter searches for the module inthe following sequences:
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

The current directory.

If the module isn'tfound, Pythonthensearches eachdirectory inthe shell variable PYTHONPATH.

If all else fails, Pythonchecks the default path. OnUNIX, this default pathis normally

/usr/local/lib/python/.

The module searchpathis stored inthe systemmodule sys as the sys.path variable. The sys.pathvariable

contains the current directory, PYTHONPATH, and the installation-dependent default.

The PYTHONPATH Variable:

The PYTHONPATH is anenvironment variable, consisting of a list of directories. The syntax of


PYTHONPATH

is the same as that of the shell variable PATH.

Here is a typicalPYTHONPATH froma Windows system:

set PYTHONPATH=c:\python20\lib;

And here is a typicalPYTHONPATH froma UNIX system:

set PYTHONPATH=/usr/local/lib/python

Namespaces and Scoping:

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names
(keys) and

their corresponding objects (values).

A Pythonstatement canaccess variables ina local namespace and inthe global namespace. If a local and
a g lobal

variable have the same name, the local variable shadows the g lobal variable.

Eachfunctionhas its ownlocalnamespace. Class methods follow the same scoping rule as ordinary
functions.

Pythonmakes educated guesses onwhether variables are local or g lobal. It assumes that any variable
assigned

a value ina functionis local.


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Therefore, inorder to assigna value to a g lobal variable withina function, youmustfirst use the g lobal
statement.

The statement global VarName tells PythonthatVarName is a g lobal variable. Pythonstops searching
the local

namespace for the variable.

For example, we define a variable Money inthe g lobalnamespace. Withinthe functionMoney, we


assignMoney

a value, therefore Pythonassumes Money as a local variable. However, we accessed the value of the
local

variable Money before setting it, so anUnboundLocalError is the result. Uncommenting the g lobal
statement

fixes the problem.

#!/usr/bin/python

Money = 2000

def AddMoney():

# Uncomment the following line to fix the code:

# global Money

Money = Money + 1

print Money

AddMoney()

print Money

The dir( ) Function:

The dir() built-infunctionreturns a sorted list of string s containing the names defined by a module.

The list contains the names of allthe modules, variables and functions that are defined ina module.
Following is a

simple example:

#!/usr/bin/python
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

# Import built-in module math

import math

content = dir(math)

print content;

Whenthe above code is executed, it produces the following result:

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',

'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',

'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',

'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',

'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ is the module's name, and __file__ is the filename
fromwhichthe

module was loaded.

The globals() and locals() Functions:

The globals() and locals() functions canbe used to returnthe names inthe g lobal and localnamespaces

depending onthe locationfromwhere they are called.

If locals() is called fromwithina function, it will returnallthe names that canbe accessed locally
fromthatfunction.

If g lobals() is called fromwithina function, it will returnallthe names that canbe accessed g lobally
fromthat

function.

The returntype of boththese functions is dictionary. Therefore, names canbe extracted using the keys()

function.

The reload() Function:

Whenthe module is imported into a script, the code inthe top-level portionof a module is executed
only once.
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

Therefore, if youwantto reexecute the top-level code ina module, you canuse the reload() function.
The

reload() functionimports a previously imported module ag ain. The syntax of the reload() functionis
this:

reload(module_name)

Here, module_name is the name of the module youwantto reload and notthe string containing the
module name.

For example, to reload hello module, do the following :

reload(hello)

Packages in Python:

A packag e is a hierarchicalfile directory structure that defines a sing le


Pythonapplicationenvironmentthat

consists of modules and subpackag es and sub-subpackag es, and so on.

Consider a file Pots.py available inPhone directory. This file has following line of source code:

#!/usr/bin/python

def Pots():

print "I'm Pots Phone"

Similar way, we have another two files having differentfunctions withthe same name as above:

Phone/Isdn.py file having functionIsdn()

Phone/G3.py file having functionG3()

Now, create one more file __init__.py inPhone directory:

Phone/__init__.py

To make all of your functions available whenyou've imported Phone, youneed to put explicitimport
statements in

__init__.py as follows:

from Pots import Pots

from Isdn import Isdn


Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

from G3 import G3

After you've added these lines to __init__.py, youhave all of these classes available whenyou've
imported the

Phone packag e.

#!/usr/bin/python

# Now import your Phone Package.

import Phone

Phone.Pots()

Phone.Isdn()

Phone.G3()

Whenthe above code is executed, it produces the following result:

I'm Pots Phone

I'm 3G Phone

I'm ISDN Phone

Inthe above example, we have takenexample of a sing le functions ineachfile, but you cankeep
multiple functions

inyour files. You canalso define different Pythonclasses inthose files and thenyou cancreate your
packag es out
of those classes.
Python3

print("Geek" == "Geek")

print("Geek" < "geek")

print("Geek" > "geek")

print("Geek" != "Geek")

Output
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

True
True
False
False
Equal to String Python using Regular Expression
In Python, you can use regular expressions to check Python String Equivalence using
the re module. Regular expressions provide a flexible and powerful way to define patterns and
perform pattern-matching operations on strings.
Python3

import re

def compare_strings(string1, string2):

pattern = re.compile(string2)

match = re.search(pattern, string1)

if match:

print(f"'{string2}' found in '{string1}'")

else:

print(f"'{string2}' not found in '{string1}'")

string1 = "GeeksForGeeks"

string2 = "GeeksFor"

string3 = "Geeks"

compare_strings(string1, string2)

compare_strings(string1, string3)

Output
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

'GeeksFor' found in 'GeeksForGeeks'


'Geeks' found in 'GeeksForGeeks'
String Comparison in Python using Is Operator
The == operator compares the values of both operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same is the
case for != and is not. Let us understand Python String Equivalence with an example.
Python3

str1 = "Geek"

str2 = "Geek"

str3 = str1

print("ID of str1 =", hex(id(str1)))

print("ID of str2 =", hex(id(str2)))

print("ID of str3 =", hex(id(str3)))

print(str1 is str1)

print(str1 is str2)

print(str1 is str3)

str1 += "s"

str4 = "Geeks"

print("\nID of changed str1 =", hex(id(str1)))

print("ID of str4 =", hex(id(str4)))

print(str1 is str4)

Output
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of changed str1 = 0x7f60356137d8
ID of str4 = 0x7f60356137a0
False
The object ID of the strings may vary on different machines. The object IDs of str1, str2, and str3
were the same therefore the result is True in all the cases. After the object id of str1 is changed, the
result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1,
the answer will be false as their object IDs are different. Vice-versa will happen with is not.
String Comparison in Python Creating a User-Defined Function.
By using relational operators we can only check Python String Equivalence by their Unicode. In order
to compare two strings according to some other parameters, we can make user-defined functions . In
the following code, our user-defined function will compare the strings based on the number of digits.
Python3

# function to compare string

# based on the number of digits

def compare_strings(str1, str2):

count1 = 0

count2 = 0

for i in range(len(str1)):

if str1[i] >= "0" and str1[i] <= "9":

count1 += 1

for i in range(len(str2)):

if str2[i] >= "0" and str2[i] <= "9":

count2 += 1
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Re-accredited with ‘A’ Grade by NAAC(3rd Cycle)
Approved by UGC Under Section (2f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402

return count1 == count2

print(compare_strings("123", "12345"))

print(compare_strings("12345", "geeks"))

print(compare_strings("12geeks", "geeks12"))

Output
False
False
True

You might also like