Python Programming Material
Python Programming Material
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
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
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
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.
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)
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.
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.
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
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
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
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
# 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))
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.
•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.
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 (*).
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
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
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
Python Input
While programming, we might want to take the input from the user. In Python, we can use the
input() function.
input(prompt)
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'>.
The data type of the user input is converted from string to integer
• 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:
// 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
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:
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.
== 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
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.
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:
Identity Operators
Operator Precedence
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
x=5y
= 2.3
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
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
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
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
Output
Number is positive.
The if statement is easy
if condition:
# block of code if condition is True
else:
# block of code if condition is False
Positive number
This statement is always executed
Here,
# 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')
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.
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
Output:
2
3
Output:
Hello Hi
Hello Hi
Hello
Hi
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.
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
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
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
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
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
Output:
The sum is 25
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.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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.
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
if x == 1:
return 1
else:
return (x * factorial(x
-1))
num = 3
print("The factorialof", num, "is", factorial(num))
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
print("\nConverted String:")
print(text.upper())
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
print("\nConverted String:")
print(text.title())
print("\nConverted String:")
print(text.swapcase())
print("\nConverted String:")
print(text.capitalize())
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:
suffix
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
Example:
The Pythoncode for a module named aname normally resides ina file named aname.py. Here's
anexample of a
return
You canuse any Pythonsource file as a module by executing animport statementinsome other
Pythonsource
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 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
support.print_func("Zara")
Hello : Zara
A module is loaded only once, reg ardless of the number of times itis imported. This prevents the
module
Python's from statementlets you import specific attributes froma module into the current namespace.
The
For example, to importthe functionfibonaccifromthe module fib, use the following statement:
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.
Itis also possible to import allnames froma module into the current namespace by using the following
import
statement:
This provides aneasy way to import allthe items froma module into the current namespace; however,
this
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
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
set PYTHONPATH=c:\python20\lib;
set PYTHONPATH=/usr/local/lib/python
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names
(keys) and
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
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
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
#!/usr/bin/python
Money = 2000
def AddMoney():
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
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 math
content = dir(math)
print content;
Here, the special string variable __name__ is the module's name, and __file__ is the filename
fromwhichthe
The globals() and locals() functions canbe used to returnthe names inthe g lobal and localnamespaces
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.
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.
reload(hello)
Packages in Python:
Consider a file Pots.py available inPhone directory. This file has following line of source code:
#!/usr/bin/python
def Pots():
Similar way, we have another two files having differentfunctions withthe same name as above:
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 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
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
I'm 3G 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")
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
pattern = re.compile(string2)
if match:
else:
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
str1 = "Geek"
str2 = "Geek"
str3 = str1
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
str1 += "s"
str4 = "Geeks"
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
count1 = 0
count2 = 0
for i in range(len(str1)):
count1 += 1
for i in range(len(str2)):
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
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Output
False
False
True