0% found this document useful (0 votes)
19 views

PYTHON_NOTES

The document provides a comprehensive overview of Python programming, covering its history, features, and fundamental concepts such as variables, data types, control statements, functions, and file handling. It details the syntax and rules for defining variables, identifiers, and constants, and explains the use of built-in data types like lists, tuples, and dictionaries. Additionally, it highlights Python's ease of use, cross-platform compatibility, and extensive libraries, making it a popular choice for both beginners and experienced programmers.

Uploaded by

yogeshcsc9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

PYTHON_NOTES

The document provides a comprehensive overview of Python programming, covering its history, features, and fundamental concepts such as variables, data types, control statements, functions, and file handling. It details the syntax and rules for defining variables, identifiers, and constants, and explains the use of built-in data types like lists, tuples, and dictionaries. Additionally, it highlights Python's ease of use, cross-platform compatibility, and extensive libraries, making it a popular choice for both beginners and experienced programmers.

Uploaded by

yogeshcsc9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

PYTHON PROGRAMMING

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 Lists-Nested 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.

1
UNIT-I
Basics of Python Programming
What is Python
Python’s simplicity, readability, and versatility make it an excellent choice for
beginners and experienced programmers alike.
Python History and Versions
 Python laid its foundation in the late 1980s.
 The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
 In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
 In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
 Python 2.0 added new features such as list comprehensions, garbage collection systems.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
 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.
 The following programming languages influence Python:
o ABC language.
o Modula-3

Python Features

Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is


straightforward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.

2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.
2
3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line at a
time. The advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to
develop the software for several competing platforms by writing a program only once.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official website It has
a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source
means, "Anyone can download its source code without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.

7) Extensible

It implies that other languages such as C/C++ can be used to compile the code and thus it
can be used further in our Python code. It converts the program into byte code, and any platform
can use that byte code.

8) Large Standard Library

It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.

9) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.

3
10) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code
line by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable

The code of the other programming language can use in the Python source code. We can
use Python source code in another programming language as well. It can embed other language
into our code.

12. Dynamic Memory Allocation

In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.

Python Literals

 The data which is being assigned to the variables are called as Literal.

 In Python, Literals are defined as raw data which is being assigned to the variables or
constants.
Let us understand this by looking at a simple example,

str = ‘How are you, Sam?’

Here, we have declared a variable ‘str’, and the value assigned to it ‘How are you, Sam?’ is a literal
of type string.

Python supports various different types of Literals.

Numeric Literals

Numeric Literals are values assigned to the Variables or Constants which cannot be changed
i.e., they are immutable. There are a total of 3 categories in Numeric Literals. They are – Integer,
Float, and Complex.

4
Example

# Int Numeric Literal

a = 30

# Float Numeric Literal

b = 40.67

# Complex Numeric Literal

c = 10+4j

print(a)

print(b)

print(c)

print(c.real, c.imag)

Output

30

40.67

(10+4j)

10.0 4.0

String Literals

A string literal is a series of characters surrounded by quotation marks. For a string, we can
use single, double, or triple quotations. We can write multi-line strings or display them in the
desired format by using triple quotes. A single character surrounded by single or double quotations
is also known as a character literal.

Example

string = 'Hello Guys'

multi_line = '''Hey

There!!'''

5
char = 'Z'

print(string)

print(multi_line)

print(char)

Output –

Hello Guys

Hey

There!!

Boolean Literals

A Boolean Literal has either of the 2 values – True or False. Where True is considered as
1 and False is considered as 0.

Example

boolean1 = (1 == True)

boolean2 = (1 == False)

num = 20

age = 20

x = True + 10

y = False + 50

print(boolean1)

print(boolean2)

print(num==age)

print('Value of x:', x)

print('Value of y:', y)

6
Output

True

False

True

Value of x: 11

Value of y: 50

Special Literals

Python provides a special kind of literal known as None. We use this type of Literal in
order to specify the field has not been created. It also denotes the end of a list in Python.

Literal Collections

In Python, there are 4 different types of Literal Collections. They represent more complicated
and complex data and assist Python scripts to be more extensible. Let us look at each one of
them in detail.

1. List Literals

The elements in a list are of many data types. The values in the List are surrounded by square
brackets ([]) and separated by commas (,). List values can be changed i.e., they are mutable.

2. Tuple Literals

Just like a List, a tuple is also a collection of various data types. It is surrounded by parentheses
‘(),’ and each element is separated by a comma (,). It is unchangeable (immutable).

3. Dict Literals

The data is stored in the dictionary as a key-value pair. It is surrounded by curly braces ‘{}‘, and
each pair is separated by commas (,). A dictionary can hold various types of data. Dictionaries
are subject to change.

4. Set Literals

Set is an unordered data set collection. It is surrounded by and each element is separated by a
comma (,).

7
Python Constants

A Python Constant is a variable whose value cannot be changed throughout the program.

Certain values are fixed and are universally proven to be true. These values cannot be
changed over time. Such types of values are called as Constants. We can think of Python
Constants as a bag full of fruits, but these fruits cannot be removed or changed with other fruits.

Rules to be followed while declaring a Constant

1. Python Constants and variable names should contain a combination of lowercase (a-
z) or capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT
= 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized
when declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for
example, makes more sense than V. It simplifies the coding process.

Assigning Values to Constants

Constants are typically declared and assigned in a module in Python. In this case, the
module is a new file containing variables, functions, and so on that is imported into the main file.
Constants are written in all capital letters with underscores separating the words within the
module.

We create a separate file for declaring constants. We then use this file to import the
constant module in the main.py file from the other file.

Example:

PI = 3.14

GRAVITY = 9.8

import constant as const

print('Value of PI:', cons.PI)

print('Value of Gravitational force:', cons.GRAVITY)

Output

Value of PI: 3.14

Value of Gravitational force: 9.8

8
Python Variables
 A Variable is a location that is named in order to store data while the program is being
run.
 In a programming language, Variables are words that are used to store values of any
data type.

In simple words, when you create a variable, it takes up some memory space based on the
value and the type you set to it. The Python interpreter allocates RAM to the variable based on
its data type. The variables’ values can be altered at any time during the program.

An Identifier is a term used in programming language in order to denote unique name given
to these variables.

Syntax
variable_name = data values
where, variable_name = combination of letters, numbers and an underscore

Rules to be followed while declaring a Variable name

1. A Variable’s name cannot begin with a number. Either an alphabet or the underscore
character should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well as the
underscore character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables in
Python.

Assigning values to Variables in Python

There are few different methods to assign data elements to a Variable. The most common ones
are described below –

1. Simple declaration and assignment of a value to the Variable

In this type, the data values are directly assigned to the Variables in the declaration statement.

Example

num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'
print(num)
print(numlist)
print(str)

9
Output

10

[1, 3, 5, 7, 9]

Hello World

Here, we have created 3 variables named as ‘num’, ‘numlist’, and ‘str’. We have assigned all the
3 variables an int value 10, a list of integers, and a string of characters respectively.

2. Changing the value of a Variable

Data values assigned to the variables can be changed at any time. In Layman language, you can
think of a Variable as a bag to store items and these items can be replaced at any time.

Example

val = 50

print("Initial value:", val)

val = 100 # assigning new value

print("Updated value:", val)

Output

Initial value: 50

Updated value: 100

In the above program, initially the value of Variable ‘val’ was 50. Later it was reassigned to a
value of 100.

3. Assign multiple values to multiple Variables

In Python, we can assign multiple values to multiple variables in the same declaration statement
by using the following method –

Example

name, age, city = 'David', 27, 'New York'

print(name)

print(age)

print(city)

10
Output

David

27

New York

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming
practice to give meaningful names to identifiers to make the code understandable.
Rules for Naming Python Identifiers

1. It cannot be a reserved python keyword.


2. It should not contain white space.
3. It can be a combination of A-Z, a-z, 0-9, or underscore.
4. It should start with an alphabet character or an underscore ( _ ).
5. It should not contain any special character other than an underscore ( _ ).
6. Examples of Python Identifiers

Valid identifiers:

 var1
 _var1
 _1_var
 var_1

Invalid Identifiers

 !var1
 1var
 1_var
 var#1
 var 1

Python Keywords and Identifiers Examples

Example 1: Example of and, or, not, True, False keywords.

print("example of True, False, and, or, not keywords")

# compare two operands using and operator

print(True and True)

# compare two operands using or operator


11
print(True or False)

# use of not operator

print(not False)

Output

example of True, False, and, or, not keywords

True

True

True

Keywords in Python
Python Keywords are some predefined and reserved words in Python that have special
meanings. Keywords are used to define the syntax of the coding. The keyword cannot be used as
an identifier, function, or variable name. All the keywords in Python are written in lowercase
except True and False. There are 35 keywords in Python 3.11.

Rules for Keywords in Python

 Python keywords cannot be used as identifiers.


 All the keywords in Python should be in lowercase except True and False.

List of Python Keywords

Keywords Description

This is a logical operator which returns true if both the operands are true else returns
and
false.

This is also a logical operator which returns true if anyone operand is true else returns
or
false.

not This is again a logical operator it returns True if the operand is false else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The elif statement is executed if
elif
the previous conditions were not true.

12
Keywords Description

Else is used with if and elif conditional statements. The else block is executed if the
Else
given condition is not true.

For This is used to create a loop.

While This keyword is used to create a while loop.

Break This is used to terminate the loop.

As This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

This function is used for debugging purposes. Usually used to check the correctness of
assert
code

class It helps us to define a class.

13
Keywords Description

continue It continues to the next iteration of a loop

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is used with exceptions, a block of code that will be executed no matter if there
finally
is an exception or not.

from It is used to import specific parts of any module.

global This declares a global variable.

import This is used to import a module.

in It’s used to check whether a value is present in a list, range, tuple, etc.

is This is used to check if the two variables are equal or not.

This is a special constant used to denote a null value or avoid. It’s important to
none
remember, 0, any empty container(e.g empty list) do not compute to None

nonlocal It’s declared a non-local variable.

raise This raises an exception.

yield It ends a function and returns a generator.

14
Keywords Description

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

Build in data types


A variable can contain a variety of values. On the other hand, a person's id must be stored as an
integer, while their name must be stored as a string.

The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

15
The data types will be briefly discussed in this tutorial section. We will talk about every single
one of them exhaustively later in this instructional exercise.

Numbers

Numeric values are stored in numbers. The whole number, float, and complex qualities
have a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.

When a number is assigned to a variable, Python generates Number objects. For instance,

a=5

print("The type of a", type(a))

b = 40.5

print("The type of b", type(b))

c = 1+3j

print("The type of c", type(c))

print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>

The type of b <class 'float'>

The type of c <class 'complex'>

c is complex number: True

1. Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with
int.
2. Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
3. Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like
2.14j, 2.0 + 2.3j, etc.

16
Sequence Type

String

The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes.

String dealing with Python is a direct undertaking since Python gives worked-in
capabilities and administrators to perform tasks in the string.

When dealing with strings, the operation "hello"+" python" returns "hello python," and
the operator + is used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a


repetition operator.

Example - 1

str = "string using double quotes"

print(str)

s = '''''A multiline

string'''

print(s)

Output:

string using double quotes

A multiline

string

List
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 (*).

Look at the following example.


17
Example:

list1 = [1, "hi", "Python", 2]

#Checking type of given list

print(type(list1))

#Printing the list1

print (list1)

# List slicing

print (list1[3:])

# List slicing

print (list1[0:2])

# List Concatenation using + operator

print (list1 + list1)

# List repetation using * operator

print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]

[2]

[1, 'hi']

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple

In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items
from various data types. A parenthetical space () separates the tuple's components from one
another.

18
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.

Example:

tup = ("hi", "Python", 2)

# Checking type of tup

print (type(tup))

#Printing the tuple

print (tup)

# Tuple slicing

print (tup[1:])

print (tup[0:1])

# Tuple concatenation using + operator

print (tup + tup)

# Tuple repatation using * operator

print (tup * 3)

# Adding value to tup. It will throw an error.

t[2] = "hi"

Output:

<class 'tuple'>

('hi', 'Python', 2)

('Python', 2)

('hi',)

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

19
Dictionary

A dictionary is a key-value pair set arranged in any order. It stores a specific value for
each key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.

The comma (,) and the curly braces are used to separate the items in the dictionary.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary

print (d)

# Accesing value using keys

print("1st name is "+d[1])

print("2nd name is "+ d[4])

print (d.keys())

print (d.values())

Output:

1st name is Jimmy

2nd name is mike

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}

dict_keys([1, 2, 3, 4])

dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

True and False are the two default values for the Boolean type. These qualities are
utilized to decide the given assertion valid or misleading. The class book indicates this. False can
be represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.

# Python program to check the boolean type

print(type(True))

print(type(False))

print(false)

20
Output:

<class 'bool'>

<class 'bool'>

NameError: name 'false' is not defined

Set

The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence.

Either a sequence of elements is passed through the curly braces and separated by a
comma to create the set or the built-in function set() is used to create the set. It can contain
different kinds of values.

set1 = set()

set2 = {'James', 2, 3,'Python'}#Printing Set value

print(set2)

# Adding element to the set

set2.add(10)

print(set2)

#Removing element from the set

set2.remove(2)

print(set2)

Output:

{3, 'Python', 'James', 2}

{'Python', 'James', 3, 2, 10}

{'Python', 'James', 3, 10}

Python output statement


Python | Output using print() function
Python print() function prints the message to the screen or any other standard output device.

Python print() Function Syntax


21
Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
 value(s): Any value, and as many as you like. Will be converted to a string before printed
 sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
 end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
 file : (Optional) An object with a write method. Default :sys.stdout
 flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Return Type: It returns output to the screen.

Though it is not necessary to pass arguments in the print() function, it requires an empty
parenthesis at the end that tells Python to execute the function rather than calling it by name.
Now, let’s explore the optional arguments that can be used with the print() function.
Example
name = "John"

age = 30

print("Name:", name)

print("Age:", age)

Output

Name: John

Age: 30

Python input() Function


How to Take Input from User in Python:
First we can take input from users and second show output to them. To do this Python provides
an input() function. Syntax:
input('prompt')
Integer input in Python
# Taking input from the user as integer
num = int(input("Enter a number: "))
add = num + 1 # Output print(add)
Output:
Enter a number: 25
26
Multiple Inputs in Python :
we can take multiple inputs of the same data type at a time in python, using map() method in
python.
Example:
22
a, b, c = map(int, input("Enter the Numbers : "))
print("The Numbers are : ",a,b,c)
print(a, b, c)
Output:
Enter the Numbers: 2457
The Numbers are: 2 4 5 7
2457
Comments in python
Comments in Python is the inclusion of short descriptions along with the code to increase
its readability. A developer uses them to write his or her thought process while writing the code.
It explains the basic logic behind why a particular line of code was written.\

They are just meant for the coders themselves or other developers to understand a piece
of code, especially since the Python interpreter completely ignores comments in Python.

What Are Comments in Python Used For?

Comments in Python are identified with a hash symbol, #, and extend to the end of the
line. Hash characters in a string are not considered comments, however. There are three ways to
write a comment - as a separate line, beside the corresponding statement of code, or as a multi-
line comment block.

There are multiple uses of writing comments in Python. Some significant uses include:

 Increasing readability
 Explaining the code to others
 Understanding the code easily after a long-term
 Including resources
 Re-using the existing code

What Are the Advantages of Using Comments in Python?

Comments in Python provide numerous advantages. Their primary benefits include:

1. Makes the code easily understandable by other programmers


2. The code becomes self-explanatory
3. Helps remember why we used a specific command, method, or function in the code
4. Enables the interpreter to ignore some part of the code while testing

What Are the Different Types of Comments in Python?

There are three types of comments: single-line, multi-line, and docstring comments.

23
1. Single-Line Comments

Single-line comments begin with the “#” character. Anything that is written in a single line after
‘#’ is considered as a comment. The syntax for writing single-line comments is:

# comments here

There are two ways of using single-line comments in Python. You can use it before the code or
next to the code.

2. Multi-Line Comments

Python does not support multi-line comments. However, there are multiple ways to overcome
this issue. None of these ways are technically multi-line comments, but you can use them as one.
The first way is by using # at the beginning of each line of the comment

The next way is by using string literals but not assigning them to any variables. If you do not
assign a string literal to a variable, the Python interpreter ignores it. Use this to your advantage to
write multi-line comments. You can either use a single (‘’) quotation or double (“”) quotation.

3. Python Docstrings

Python provides an in-built feature called docstrings for commenting on modules, methods,
functions, objects, and classes. They are written in the first line after defining a module, function,
method, etc., using three quotation marks (‘’ or “”). If you do not use it in the first line, the
interpreter will not take it as a docstring. You can also access docstrings using the __doc__
attribute.

Indentation in Python
Indentation is a very important concept of Python because without properly indenting
the Python code, you will end up seeing IndentationError and the code will not get compiled.
Python Indentation
Python indentation refers to adding white space before a statement to a particular block
of code. In another word, all the statements with the same space to the right, belong to the
same code block.

24
Example of Python Indentation

 Statement (line 1), if condition (line 2), and statement (last line) belongs to the same
block which means that after statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the last statement for execution.
 The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.
 Statements inside nested if-else belong to block 3 and only one statement will be
executed depending on the if-else condition.

Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code. A block is a combination of all these statements. Block can
be regarded as the grouping of statements for a specific purpose. Most programming languages
like C, C++, and Java use braces { } to define a block of code. Python uses indentation to
highlight the blocks of code. Whitespace is used for indentation in Python.

Python Operators
The operator is a symbol that performs a specific operation between two operands, according
to one definition. Operators serve as the foundation upon which logic is constructed in a program
in a particular programming language.

1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic Operators

Arithmetic operators used between two operands for a particular operation. There are
many arithmetic operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0

25
* It is used to multiply one operand with the other. For example, if a = 20, b = 4
(Multiplication) => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an
exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two
division) operands.

Program Code:
a = 32 # Initialize the value of a

b=6 # Initialize the value of b

print('Addition of two numbers:',a+b)

print('Subtraction of two numbers:',a-b)

print('Multiplication of two numbers:',a*b)

print('Division of two numbers:',a/b)

print('Reminder of two numbers:',a%b)

print('Exponent of two numbers:',a**b)

print('Floor division of two numbers:',a//b)

Output:

Addition of two numbers: 38

Subtraction of two numbers: 26

Multiplication of two numbers: 192

Division of two numbers: 5.333333333333333

Reminder of two numbers: 2

Exponent of two numbers: 1073741824

Floor division of two numbers: 5

26
Comparison operator

Comparison operators mainly use for comparison purposes. Comparison operators


compare the values of the two operands and return a true or false Boolean value in accordance.
The example of comparison operators are ==, !=, <=, >=, >, <. In the below table, we explain the
works of the operators.

Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.

Program Code:

Now we give code examples of Comparison operators in Python. The code is given below

a = 32 # Initialize the value of a

b=6 # Initialize the value of b


print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)

print('a is less than b:',a<b)

Output:

Two numbers are equal or not: False

Two numbers are not equal or not: True

a is less than or equal to b: False

a is greater than or equal to b: True

a is greater b: True

a is less than b: False


27
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left
operand. There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In
the below table, we explain the works of the operators.

Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left operand, the left
operand receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal
to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal
to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will
be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal
to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to
a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

Program Code:

a = 32 # Initialize the value of a b = 6 # Initialize the value of b

print('a=b:', a==b)

print('a+=b:', a+b)

print('a-=b:', a-b)

print('a*=b:', a*b)

print('a%=b:', a%b)

print('a**=b:', a**b)

print('a//=b:', a//b)

28
Output:

a=b: False

a+=b: 38

a-=b: 26

a*=b: 192

a%=b: 2

a**=b: 1073741824

a//=b: 5

Bitwise Operators

The two operands' values are processed bit by bit by the bitwise operators. The examples
of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>). Consider the case below.

For example,

if a = 7

b=6

then, binary (a) = 0111

binary (b) = 0110

hence, a & b = 0011

a | b = 0111

a ^ b = 0100

~ a = 1000

Let, Binary of x = 0101

Binary of y = 1000

Bitwise OR = 1101

8421

1 1 0 1 = 8 + 4 + 1 = 13

29
Bitwise AND = 0000

0000 = 0

Bitwise XOR = 1101

8421

1 1 0 1 = 8 + 4 + 1 = 13

Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6

~x = -6

Program Code:

a=5 # initialize the value of a

b=6 # initialize the value of b

print('a&b:', a&b)

print('a|b:', a|b)

print('a^b:', a^b)

print('~a:', ~a)

print('a<<b:', a<<b)

print('a>>b:', a>>b)

Output:

a&b: 4

a|b: 7

a^b: 3

~a: -6

a<>b: 0

Logical Operators

The assessment of expressions to make decisions typically uses logical operators. The
examples of logical operators are and, or, and not. In the case of logical AND, if the first one is
0, it does not depend upon the second one.

30
In the case of logical OR, if the first one is 1, it does not depend on the second one.
Python supports the following logical operators. In the below table, we explain the works of the
logical operators.

Operator Description
And The condition will also be true if the expression is true. If the two expressions a and b
are the same, then a and b must both be true.
Or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
Not If an expression a is true, then not (a) will be false and vice versa.

Program Code:

a=5 # initialize the value of a

print(Is this statement true?:',a > 3 and a < 5)

print('Any one statement is true?:',a > 3 or a < 5)

print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))

Output:

Is this statement true?: False

Any one statement is true?: True

Each statement is true then return False and vice-versa: True

Expression in python

In Python, an expression is a combination of values, variables, and operators that


evaluates to a single value. Expression in python can be used in a variety of ways, such as in
assignment statements, function arguments, and conditional statements.

Evaluation of Expression in Python:

When an expression is encountered in Python, the interpreter evaluates it to a single


value. This evaluation process is known as "expression evaluation." The evaluation process
begins with the innermost set of parentheses and works outward.

The interpreter evaluates each operator and operand in the expression based on its
precedence and associativity.

31
For example, in the expression 2 + 3 4, the multiplication operator () has higher
precedence than the addition operator (+), so the interpreter will first evaluate the multiplication
of 3 and 4, resulting in 12, and then add 2 to that result. This results in the final value of 14.

Types of Expression in Python with Examples:

There are several types of expression in Python, but in this article, we will majorly focus on
arithmetic, comparison, and logical expressions.

1. Arithmetic Expression in Python:

In Python expression, arithmetic expressions are used to perform mathematical operations


such as addition, subtraction, multiplication, and division. These expressions can be used in a
variety of ways, such as in assignment statements, function arguments, and conditional
statements. Understanding the basics of arithmetic expressions is essential for writing efficient
and effective code.

2. Comparison Expression in Python:

In Python expression, comparison expressions are used to compare the value of two or more
variables. These expressions return a Boolean value of either True or False, which can be used to
control the flow of a program. Comparison expressions are often used in conjunction with
control flow statements such as if-else and while loops, as well as in conjunction with other
comparison and logical operators.

3. Logical Expression in Python:

In Python, logical expressions are used to combine comparison expressions and other logical
expressions. These expressions return a Boolean value of either True or False, which can be used
to control the flow of a program. Logical expressions are often used in conjunction with control
flow statements such as if-else and while loops, as well as in conjunction with other comparison
and logical operators.

Type Conversion in Python


Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming. This article is aimed at providing
information about certain conversion functions.

There are two types of Type Conversion in Python:

1. Python Implicit Type Conversion


2. Python Explicit Type Conversion

32
Type Conversion in Python

The act of changing an object’s data type is known as type conversion. The Python
interpreter automatically performs Implicit Type Conversion. Python prevents Implicit Type
Conversion from losing data.

The user converts the data types of objects using specified functions in explicit type
conversion, sometimes referred to as type casting. When type casting, data loss could happen if
the object is forced to conform to a particular data type.

Implicit Type Conversion in Python

In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement.

Example

x = 10

print("x is of type:",type(x))

y = 10.6

print("y is of type:",type(y))

z=x+y

print(z)

print("z is of type:",type(z))

Output

x is of type: <class 'int'>

y is of type: <class 'float'>

20.6

z is of type: <class 'float'>

Explicit Type Conversion in Python

In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type.
33
Converting integer to float

int(a, base): This function converts any data type to an integer. ‘Base’ specifies the base in
which the string is if the data type is a string.

float(): This function is used to convert any data type to a floating-point number.

# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:
After converting to integer base 2 : 18

After converting to float : 10010.0

Python Type conversion using ord(), hex(), oct()

ord(): This function is used to convert a character to an integer.

hex(): This function is to convert an integer to a hexadecimal string.

oct(): This function is to convert an integer to an octal string.

Python Arrays

The Array is an idea of storing multiple items of the same type together, making it easier
to calculate the position of each element by simply adding an offset to the base value. A
combination of the arrays could save a lot of time by reducing the overall size of the code.

1. car1 = "Lamborghini"
2. car2 = "Bugatti"
3. car3 = "Koenigsegg"
The Array can be handled in Python by a module named Array. It is useful when we
must manipulate only specific data values.

34
The following are the terms to understand the concept of an array:

Element - Each item stored in an array is called an element.

Index - The location of an element in an array has a numerical index, which is used to identify
the element's position. The index value is very much important in an Array.

Array Representation:

An array can be declared in various ways and in different languages. The important points that
should be considered are as follows:

1. The index starts with 0.


2. We can easily find any elements within this Array using the Index value.
3. The length of the Array defines the capacity to store the elements. It is written like
x[100], which means the length of array x is specified by 100.

Array operations

Some of the basic operations supported by an array are as follows:

o Traverse - It prints all the elements one by one.


o Insertion - It adds an element at the given index.
o Deletion - It deletes an element at the given index.
o Search - It searches an element using the given index or by the value.
o Update - It updates an element at the given index.

Accessing array elements

We can access the array elements using the respective indices of those elements.

Program code:

import array as arr

a = arr.array('i', [2, 4, 5, 6])

print("First element is:", a[0])

print("Second element is:", a[1])

print("Third element is:", a[2])

print("Forth element is:", a[3])

35
print("last element is:", a[-1])

print("Second last element is:", a[-2])

print("Third last element is:", a[-3])

print("Forth last element is:", a[-4])

print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])

Output:

First element is: 2

Second element is: 4

Third element is: 5

Forth element is: 6

last element is: 6

Second last element is: 5

Third last element is: 4

Forth last element is: 2

24566542

Python Array Methods


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

36
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

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

37
UNIT II
Conditional Statements

Conditional statements in Python play a key role in determining the direction of


program execution. Among these, If-Else statements are fundamental, providing a way
to execute different blocks of code based on specific conditions.
Python If Statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not
Flowchart of If Statement

Flowchart of Python if statement


Syntax of If Statement in Python
Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of statements
below it otherwise not.
#if syntax Python

if condition:
# Statements to execute if
# condition is true
Example of Python if Statement
i = 10

if (i > 15):

print("10 is less than 15")

print("I am Not in if")


38
Output:

I am Not in if

Python If Else Statement


The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But if we want to do something else if
the condition is false, we can use the else statement with the if statement Python to
execute a block of code when the Python if condition is false.
Flowchart of If Else Statement
Let’s look at the flow of code in an if else Python statement.

Syntax of If Else in Python


if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Example of Python If Else Statement


# python program to illustrate else if in Python statement

#!/usr/bin/python

i = 20

if (i < 15):
39
print("i is smaller than 15")

print("i'm in if Block")

else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

Output:

i is greater than 15

i'm in else Block


i'm not in if and not in else Block

Python Nested If Statement


A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement.
Yes, Python allows us to nest if statements within if statements. i.e., we can
place an if statement inside another if statement.
Flowchart of Python Nested if Statement

Flowchart of Python Nested if statement


Syntax:
40
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Example of Python Nested If Statement

i = 10

if (i == 10):

# First if statement

if (i < 15):

print("i is smaller than 15")

if (i < 12):

print("i is smaller than 12 too")

else:

print("i is greater than 15")

Output:

i is smaller than 15

i is smaller than 12 too


Python Elif
Here, a user can decide among multiple options. The if statements are executed
from the top down.
As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final “else” statement will be executed.

41
Flowchart of Elif Statement in Python
Let’s look at the flow of control in if-elif-else ladder:

Flowchart of if-elif-else ladder


Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example of Python if-elif-else ladder
i = 25

if (i == 10):

print("i is 10")

elif (i == 15):
42
print("i is 15")

elif (i == 20):

print("i is 20")

else:

print("i is not present")

Output:

i is not present

Loops in Python
Python programming language provides two types of Python loopshecking time.
In this article, we will look at Python loops and understand their working with the help
of examp – For loop and While loop to handle looping requirements. Loops in Python
provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax
and condition-checking time. In this article, we will look at Python loops and
understand their working with the help of examples.

While Loop in Python


In Python, a while loop is used to execute a block of statements repeatedly until
a given condition is satisfied. When the condition becomes false, the line immediately
after the loop in the program is executed.

Python While Loop Syntax:


while expression:
statement(s)

All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Example
count = 0

while (count < 3):

count = count + 1

print("Hello Geek")
43
Output

Hello Geek

Hello Geek

Hello Geek

Using else statement with While Loop in Python


The else clause is only executed when your while condition becomes false. If
you break out of the loop, or if an exception is raised, it won’t be executed.

Syntax of While Loop with else statement:


while condition:
# execute these statements
else:
# execute these statements
Examples

count = 0

while (count < 3):

count = count + 1

print("Hello Geek")

else:

print("In Else Block")

Output

Hello Geek

Hello Geek

Hello Geek

In Else Block

44
For Loop in Python
For loops are used for sequential traversal. For example: traversing
a list or string or array etc. In Python, there is “for in” loop which is similar
to foreach loop in other languages. Let us learn how to use for loops in Python for
sequential traversals with examples.

For Loop Syntax:

for iterator_var in sequence:


statements(s)

It can be used to iterate over a range and iterators.

Example:
n=4

for i in range(0, n):

print(i)

Output

Example with List, Tuple, String, and Dictionary Iteration Using for Loops in
Python
The code showcases different ways to iterate through various data structures in
Python. It demonstrates iteration over lists, tuples, strings, dictionaries, and sets,
printing their elements or key-value pairs.

print("List Iteration")

l = ["geeks", "for", "geeks"]

for i in l:

print(i)
45
print("\nTuple Iteration")

t = ("geeks", "for", "geeks")

for i in t:

print(i)

print("\nString Iteration")

s = "Geeks"

for i in s:

print(i)

print("\nDictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d:

print("%s %d" % (i, d[i]))

print("\nSet Iteration")

set1 = {1, 2, 3, 4, 5, 6}

for i in set1:

print(i),

Output

List Iteration

geeks

for

geeks

46
Tuple Iteration

geeks

for

geeks

String Iteration

Dictionary Iteration

xyz 123

abc 345

Set Iteration

47
Nested Loops in Python
Python programming language allows to use one loop inside another loop which
is called nested loop. Following section shows few examples to illustrate the concept.

Nested Loops Syntax:

for iterator_var in sequence:


for iterator_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in the Python programming
language is as follows:

while expression:
while expression:
statement(s)
statement(s)

A final note on loop nesting is that we can put any type of loop inside of any
other type of loops in Python. For example, a for loop can be inside a while loop or vice
versa.
Example

from __future__ import print_function

for i in range(1, 5):

for j in range(i):

print(i, end=' ')

print()

Output

22

333

4444
48
Loop Control Statements
Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.

Continue Statement

The continue statement in Python returns the control to the beginning of the
loop.
Example: This Python code iterates through the characters of the
string ‘geeksforgeeks’. When it encounters the characters ‘e’ or ‘s’, it uses
the continue statement to skip the current iteration and continue with the next
character. For all other characters, it prints “Current Letter :” followed by the
character. So, the output will display all characters except ‘e’ and ‘s’, each on a separate
line.
Python3

for letter in 'geeksforgeeks':


if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)

Output

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Break Statement

The break statement in Python brings control out of the loop.

49
Example: In this Python code, it iterates through the characters of the
string ‘geeksforgeeks’.
When it encounters the characters ‘e’ or ‘s’, it uses the break statement to exit
the loop. After the loop is terminated, it prints “Current Letter :” followed by the last
character encountered in the loop (either ‘e’ or ‘s’). So, the output will
display “Current Letter :” followed by the first occurrence of ‘e’ or ‘s’ in the string.

for letter in 'geeksforgeeks':


if letter == 'e' or letter == 's':
break

print('Current Letter :', letter)

Output

Current Letter : e

Pass Statement

We use pass statement in Python to write empty loops. Pass is also used for
empty control statements, functions and classes.
Example: This Python code iterates through the characters of the
string ‘geeksforgeeks’ using a ‘for' loop. However, it doesn’t perform any specific
action within the loop, and the ‘pass' statement is used. After the loop, it prints “Last
Letter :” followed by the last character in the string, which is ‘s’.

for letter in 'geeksforgeeks':


pass
print('Last Letter :', letter)

Output

Last Letter : s

50
UNIT-III
Python Functions
Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a function so
that instead of writing the same code again and again for different inputs, we can do
the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Python Function Declaration

The syntax to declare a function is:

Syntax of Python Function Declaration


Types of Functions in Python
Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python that are
available to use.
 User-defined function: We can create our own functions based on our
requirements.

Creating a Function in Python

We can define a function in Python, using the def keyword. We can add any type
of functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python
function definition by using def keyword.

51
Syntax

# An example Python Function


def function_name( parameters ):
# code block

Advantages of Python Functions

o Once defined, Python functions can be called multiple times and from any
location in a program.
o Our Python program can be broken up into numerous, easy-to-follow functions if
it is significant.
o The ability to return as many outputs as we want using a variety of arguments is
one of Python's most significant achievements.
o However, Python programs have always incurred overhead when calling
functions.

Calling a Function in Python


Calling a Function To define a function, use the def keyword to give it a name,
specify the arguments it must receive, and organize the code block.

When the fundamental framework for a function is finished, we can call it from
anywhere in the program. An illustration of how to use the a_function function can be
found below.

# Example Python Code for calling a function

# Defining a function

def a_function( string ):

"This prints the value of length of string"

return len(string)

# Calling the function we defined

print( "Length of the string Functions is: ", a_function( "Functions" ) )

print( "Length of the string Python is: ", a_function( "Python" ) )

52
Output:

Length of the string Functions is: 9

Length of the string Python is: 6

Python Scope of Variables


In Python, variables are the containers for storing data values. Unlike other
languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare
variables before using them or declare their type. A variable is created the moment we
first assign a value to it.

Python Scope variable

The location where we can find a variable and also access it if required is called
the scope of a variable.

Python Local variable

Local variables are those that are initialized within a function and are unique to
that function. It cannot be accessed outside of the function. Let’s look at how to make a
local variable.

def f():

# local variable

s = "I love Geeksforgeeks"

print(s)

# Driver code

f()

Output

I love Geeksforgeeks
If we will try to use this local variable outside the function then let’s see what will
happen.

def f():
# local variable
s = "I love Geeksforgeeks"
53
print("Inside Function:", s)
# Driver code
f()

print(s)

Output:

NameError: name 's' is not defined

Python Global variables

Global variables are the ones that are defined and declared outside any function
and are not specified to any function. They can be used by any part of the program.

Example:

# This function uses global variable s

def f():

print(s)

# Global scope

s = "I love Geeksforgeeks"

f()

Output:

I love Geeksforgeeks

Python return statement


A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword) to the
caller. The statements after the return statements are not executed. If the return
statement is without any expression, then the special value None is
returned. A return statement is overall used to invoke a function so that the passed
statements can be executed.
Note: Return statement can not be used outside the function.

54
Syntax:

def fun():

statements

return [expression]

Example:

def cube(x):

r=x**3

return r

Example:

# Python program to

# demonstrate return statement

def add(a, b):

# returning sum of a and b

return a + b

def is_true(a):

# returning boolean of a

return bool(a)

# calling function

res = add(2, 3)

print("Result of add function is {}".format(res))

res = is_true(2<5)

print("\nResult of is_true function is {}".format(res))

55
Output:

Result of add function is 5

Result of is_true function is True

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number
passed as an argument to the function is even or odd.
# A simple Python function to check

# whether x is even or odd

def evenOdd(x):

if (x % 2 == 0):

print("even")

else:

print("odd")

# Driver code to call the function

evenOdd(2)

evenOdd(3)

Output:

even

odd

Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following function argument types in Python:

 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)

56
1. Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default
arguments to write functions in Python.
# Python program to demonstrate

# default arguments

def myFun(x, y=50):

print("x: ", x)

print("y: ", y)

# Driver code (We call myFun() with only

# argument)

myFun(10)

Output:

x: 10

y: 50

Like C++ default arguments, any number of arguments in a function can have a
default value. But once we have a default argument, all the arguments to its right must
also have default values.
2. Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:

Geeks Practice

Geeks Practice

57
3. Positional Arguments
We used the Position argument during the function call so that the first argument
(or value) is assigned to name and the second argument (or value) is assigned to age.
By changing the position, or if you forget the order of the positions, the values can be
used in the wrong places, as shown in the Case-2 example below, where 27 is assigned
to the name and Suraj is assigned to the age.
def nameAge(name, age):

print("Hi, I am", name)

print("My age is ", age)

# You will get correct output because

# argument is given in order

print("Case-1:")

nameAge("Suraj", 27)

# You will get incorrect output because

# argument is not in order

print("\nCase-2:")

nameAge(27, "Suraj")

Output:

Case-1:

Hi, I am Suraj

My age is 27

Case-2:

Hi, I am 27

My age is Suraj

4. Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special
symbols:

58
*args in Python (Non-Keyword Arguments)

**kwargs in Python (Keyword Arguments)

Required arguments in Python

Required arguments are the arguments passed to a function in correct positional


order. Here, the number of arguments in the function call should match exactly with the
function definition.

To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −

Example

#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()

Output

When the above code is executed, it produces the following result −

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Variable Length Argument in Python
Variable-length arguments refer to a feature that allows a function to accept a
variable number of arguments in Python. It is also known as the argument that can
also accept an unlimited amount of data as input inside the function. There are two
types in Python:
 Non – Keyworded Arguments (*args)
 Keyworded Arguments (**kwargs)

What is Python *args?

59
In Python, *args is used to pass a variable number of arguments to a function. It is
used to pass a variable-length, non-keyworded argument list. These arguments are
collected into a tuple within the function and allow us to work with them.
Feature of Python *args
 To accept a variable number of arguments, use the symbol *; by convention, it is
commonly used with the term args.
 *args enables you to accept more arguments than the number of formal arguments
you previously defined. With *args, you can add any number of extra arguments to
your current formal parameters (including none).
 Using the *, the variable that we associate with the * becomes iterable meaning you
can do things like iterate over it, run some higher-order functions such as map and
filter, etc.
In this example, we define a function sum_all that accepts any number of
arguments. The *args syntax collects all the arguments into a tuple named args. Inside
the function, we iterate through the args tuple and calculate the sum of all the
numbers passed to the function.

def sum_all(*args):

result = 0

for num in args:

result += num

return result

print(sum_all(1, 2, 3, 4, 5))

Output
15

What is Python **kwargs?

In Python, **kwargs is used to pass a keyworded, variable-length argument list.


We call kwargs with a double star. The reason for this is that the double star allows us to
pass over keyword arguments (in any order). Arguments are collected into a dictionary
within the function that allow us to access them by their keys.

Feature of Python **kwargs

A keyword argument is when you give the variable a name as you provide it into
the function.

60
Consider the kwargs to be a dictionary that maps each keyword to the value we
pass beside it. As a result, when we iterate through the kwargs, there appears to be no
sequence in which they were printed.

In this example, the display_info function accepts a variable number of keyword


arguments. Inside the function, we iterate through the kwargs dictionary and print out
each key-value pair.

def display_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

display_info(name="Alice", age=30, city="New York")

Output

name: Alice

age: 30

city: New York

Recursion in Python
The term Recursion can be defined as the process of defining something in
terms of itself. In simple words, it is a process in which a function calls itself directly or
indirectly.

Advantages of using recursion


 A complicated function can be split down into smaller sub-problems utilizing
recursion.
61
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.
Disadvantages of using recursion

 A lot of memory and time is taken through recursive calls which makes it
expensive for use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.

Syntax:

def func(): <--

| (recursive call)

func() ----

Example 1: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8…

# Program to print the fibonacci series upto n_terms

# Recursive function

def recursive_fibonacci(n):

if n <= 1:

return n

else:

return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))

n_terms = 10

# check if the number of terms is valid

if n_terms <= 0:

print("Invalid input ! Please input a positive value")

62
else:

print("Fibonacci series:")

for i in range(n_terms):

print(recursive_fibonacci(i))

Output

Fibonacci series:
0
1
1
2
3
5
8
13
21
34

Python String
A String is a data structure in Python Programming that represents a sequence
of characters. It is an immutable data type, meaning that once you have created a
string, you cannot change it.
Python String are used widely in many different applications, such as storing
and manipulating text data, representing names, addresses, and other types of data
that can be represented as text.
Syntax of String Data Type in Python

string_variable = 'Hello, world!'

Example of string data type in Python

string_0 = "A Computer Science portal for geeks"

print(string_0)

print(type(string_0))

Output:
63
A Computer Science portal for geeks

<class 'str'>

Python String Methods


Python string methods is a collection of in-built Python functions that
operates on lists.
Note: Every string method in Python does not change the original string instead
returns a new string with the changed attributes.
Python string is a sequence of Unicode characters that is enclosed in quotation
marks.

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
 string.digits
The string '0123456789'.
 string.hexdigits
The string '0123456789abcdefABCDEF'.
 string.octdigits
The string '01234567'.
 string.punctuation
String of ASCII characters which are considered punctuation characters in
the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
 string.printable
String of ASCII characters which are considered printable. This is a
combination of digits, ascii_letters, punctuation, and whitespace.
 string.whitespace
A string containing all ASCII characters that are considered whitespace. This
includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

Example: Changing the case of Python String Methods


# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case

64
print("\nConverted String:")
print(text.upper())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# 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

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)
65
Python Strings Immutable
Strings in Python are “immutable” which means they can not be changed after
they are created. Some other immutable data types are integers, float, boolean, etc.

The immutability of Python string is very useful as it helps in hashing,


performance optimization, safety, ease of use, etc.

The article will explore the differences between mutable and immutable objects,
highlighting the advantages of using immutable objects. It will also compare
immutability with mutability, discussing various methods to handle immutability and
achieve desired outcomes.

Input: name_1 = "Aarun"

name_1[0] = 'T'

Output: TypeError: 'str' object does not support item assignment

Explanation: We cannot update the string after declaring it means once an immutable
the objects instantiated, its value cannot be changed

Python Strings Immutability


Immutability is the property of an object according to which we can not change
the object after we declared or after the creation of it and this Immutability in the case of
the string is known as string immutability in Python.

Benefits of Immutable Objects

1. Hashability and Dictionary Keys: Immutable objects can be used as keys in


dictionaries because their hash value remains constant, ensuring that the key-value
mapping is consistent.
2. Memory Efficiency: Since immutable objects cannot change their value, Python
can optimize memory usage. Reusing the same immutable object across the
program whenever possible reduces memory overhead.
3. Thread Safety: Immutability provides inherent thread safety. When multiple
threads access the same immutable object, there’s no risk of data corruption due to
concurrent modifications.
4. Predictability and Debugging: With immutability, you can be confident that a
given object’s value will not change unexpectedly, leading to more predictable and
easier-to-debug code.
5. Performance Optimization: Immutable objects facilitate certain performance
optimizations, such as caching hash values for quick dictionary lookups.

Python Built in Functions


66
1. abs()

 It returns the absolute value of the number.


 It takes only one argument.
 The argument may be: an integer or floating point.
 If the argument is complex: it will return the magnitude.

Example -1:

print("absolute value of -20 is:", abs(-9))

print("absolute value of 0 is:", abs(0))

print("absolute value of 9.38 is:", abs(9.38))

2. chr()

 It returns the string representation of a character whose Unicode is an integer.


 i.e., it takes Unicode as an input and returns the corresponding character as an
output.

Example

# use chr() function to find the characters corresponding to the given Unicode

num = [65, 97, 36, 57]

for i in num:

print(chr(i))

3. dict()

 It is used to create the dictionary


 Dictionaries are unordered collections of the object, that stores the data in key:
value pair.

Example

D1 = {}
D2 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 }
D3 = dict(name='Jim', age=20, height = 6.1)
print("D1 is empty dictionary", D1)
print("creating 'dict' using curly braces and colons:", D2)

print("creating 'dict' using dict built-in function:", D3)

67
4. enumerate()

 Enumerate in a built-in function of Python that helps you count each object of a
list, tuple, set, or any data structure that can be iterated.
 It takes input as a collection of tuples and returns it as an enumerate object.
 An enumerated object (returned as an output) can be used directly for loops
 It can be converted as a list of tuples using the list method.

Example

car_list = [‘Honda’, ‘Tata’, ‘Mahindra’, ‘Ford’, ‘Toyota’]

e_car_list = enumerate(car_list)

print(list(e_car_list))

5. float()

 The float () function in Python returns a floating-point number of a number or a


string representation of a numeric value.
 a floating-point number.
 If no value assigns, it will return 0.0.
 If a string is passed without a number, it will return an error.

Example

print(float(2))
print(float('3.5'))
print(float())
print(float('inf'))
print(float('NaN'))

print(float('InfoEdge'))

6. len()

The len() function is one of the built-in functions in python that counts the
number of items in an object (string, list, tuple, set, or sequence). It returns the number
of objects in an integer format.

#find the length of the tuple


#define tuple
bike = ('yamaha', 'honda', 'tvs', 'RE')
len(bike)
68
7. list()

The Python list object is the most general mutable sequence type provided by the
language. Python lists are mutable that is the contents of the list be modified in place.
Items in the list can be accessed, changed, new elements can be added, existing element
can be removed or deleted.

Example

# Changing List Items

List1 = ['Python', 2.0, 'Infoedge', 'Python Courses']

print("Original List:", List1)

List1[1] = 3.0

List1[-1] = 'Python Certifications'

print("Updated List:", List1)

8. ord()

 ord() function in Python converts a single Unicode character into its integer
representation.
 i.e., it takes a single character as an input and returns the corresponding Unicode.
 It is the opposite of chr() function.

Example

# use ord() function to find the Unicode of

UpperCase_Char =ord( 'A')

lowercase_char = ord('a')

Special_Char = ord('$')

num = ord('9')

print('The Unicodes are:', UpperCase_Char, lowercase_char, Special_Char, num)

9. range()

 The range function in Python returns a sequence of numbers starting from the
given input value (by default: 0), increments the number at the defined step size
(by default: 1), and stops before the specified value.
 range () functions are most commonly used for loops to iterate sequences on a
sequence of numbers.

69
 range () function only takes integer values.

Example

#list the number of integers between 0 to 20 at the step size of 2

for i in range (0, 20, 2):

print(i, end =" ")

print()

10. set()

Python sets are unordered collections of unique elements and immutable objects.
You can think of them as a dictionary with just the keys and its values thrown away.
Therefore, each item of a set should be unique. Similar, to the dictionary, you can access,
add, remove the element from the set.

Example

#create a set

set1 = set([2, 3, 4, 4, 5, 5, 6])

print("The set1 has:", set1)

set2 = {2, 2, 3, 4, 5, 5, 6, 6, 6, 7}

print("The set2 has:", set2)

String Comparison in Python


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

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

print("Geek" == "Geek")

print("Geek" < "geek")

print("Geek" > "geek")

print("Geek" != "Geek")

Output

True

True

False

False

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.

str1 = "Geek"
str2 = "Geek"

str3 = str1

71
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

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

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.

# based on the number of digits


def compare_strings(str1, str2):

72
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
return count1 == count2
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))

Output

False

False

True

Import module in Python


Import in Python is similar to #include header_file in C/C++. Python modules
can get access to code from another module by importing the file/function using
import. The import statement is the most common way of invoking the import
machinery, but it is not the only way.

Import Modules in Python

When we import a module with the help of the Python import module it
searches for the module initially in the local scope by calling __import__() function.
The value returned by the function is then reflected in the output of the initial code.
import math

pie = math.pi

print("The value of pi is : ", pie)

Output

The value of pi is : 3.141592653589793


73
Importing Module using “from”
In the above code module, math is imported, and its variables can be accessed by
considering it to be a class and pi as its object. The value of pi is returned
by __import__(). pi as a whole can be imported into our initial code, rather than
importing the whole module. We can also import a file in Python using from.
from math import pi

print(pi)

Output

3.141592653589793

Import Python Built-In Modules


In this example, the built-in ‘random’ module is imported in Python using the
import statement. The randint function from the ‘random’ module is then utilized to
generate a random integer between 1 and 10, and the result is printed. We can also
import a file in Python by using import statement.

import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)

print("Random Number:", random_number)

Output

Random Number: 5

Importing `*` in Python

In the above code module, math is not imported, rather just pi has been imported as a
variable.

All the functions and constants can be imported using *.

from math import *


print(pi)

print(factorial(6))

Output

3.141592653589793

720

74
dir() function in Python
In Python, the dir() function is a built-in function used to list the attributes
(methods, properties, and other members) of an object. In this article we will see about
dir() function in Python.

Python dir() Function Syntax

Syntax: dir({object})
Parameters :
object [optional] : Takes object name
Returns :
dir() tries to return a valid list of attributes of the object it is called upon. Also, dir()
function behaves rather differently with different type of objects, as it aims to
produce the most relevant one, rather than the complete information.
 For Class Objects, it returns a list of names of all the valid attributes and base
attributes as well.
 For Modules/Library objects, it tries to return a list of names of all the attributes,
contained in that module.
 If no parameters are passed it returns a list of names in the current local scope.

What is dir() in Python?

dir() is a powerful inbuilt function in Python3, which returns a list of the attributes
and methods of any object (say functions, modules, strings, lists, dictionaries, etc.)

Python dir() function Examples

When No Parameters are Passed


In this example, we are using the dir() function to list object attributes and
methods in Python. It provides a demonstration for exploring the available functions
and objects in our Python environment and modules when we are working with them.

# when no parameters are passed


# Note that we have not imported any modules
print(dir())
# Now let's import two modules
import random
import math
print(dir())
75
Output

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',


'__name__', '__package__', '__spec__']

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '...

Namespaces and Scope in Python

A namespace is a system that has a unique name for each and every object in
Python. An object might be a variable or a method. Python itself maintains a
namespace in the form of a Python dictionary.

Let’s go through an example, a directory-file system structure in computers.


Needless to say, that one can have multiple directories having a file with the same
name inside every directory. But one can get directed to the file, one wishes, just by
specifying the absolute path to the file.

Real-time example, the role of a namespace is like a surname. One might not
find a single “Alice” in the class there might be multiple “Alice” but when you
particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one
(time being don’t think of both first name and surname are same for multiple
students).

Types of namespaces :
When Python interpreter runs solely without any user-defined modules,
methods, classes, etc. Some functions like print(), id() are always present, these are
built-in namespaces.
When a user creates a module, a global namespace gets created, later the
creation of local functions creates the local namespace. The built-in
namespace encompasses the global namespace and the global namespace
encompasses the local namespace.

76
The lifetime of a namespace :
A lifetime of a namespace depends upon the scope of objects, if the scope of an
object ends, the lifetime of that namespace comes to an end. Hence, it is not possible
to access the inner namespace’s objects from an outer namespace.

Example:

# var1 is in the global namespace


var1 = 5
def some_func():

# var2 is in the local namespace


var2 = 6
def some_inner_func():

# var3 is in the nested local


# namespace
var3 = 7
As shown in the following figure, the same object name can be present in multiple
namespaces as isolation between the same name is maintained by their namespace.

77
But in some cases, one might be interested in updating or processing global
variables only, as shown in the following example, one should mark it explicitly as
global and the update or process. Note that the line “count = count +1” references the
global variable and therefore uses the global variable, but compare this to the same
line written “count = 1”. Then the line “global count” is absolutely needed according to
scope rules.

Creating your own modules

Writing your own Python modules is easy. Any file containing valid Python code
can be imported as a module. Let's assume we have a file named words.py with the
following contents:

def first_word(my_string: str):


parts = my_string.split(" ")
return parts[0]
def last_word(my_string: str):
parts = my_string.split(" ")
return parts[-1]
def number_of_words(my_string: str):
parts = my_string.split(" ")
return len(parts)
The functions defined in the file can be accessed by importing the file:

import words
my_string = "Sheila sells seashells by the seashore"
print(words.first_word(my_string))
print(words.last_word(my_string))
print(words.number_of_words(my_string))
Output:
Sheila
Seashore
6

78
We can use our own modules just as we have learnt to use the modules from the
Python standard library:

from words import first_word, last_word


sentence = input("Please type in a sentence: ")
print("The first word was: " + first_word(sentence))
print("The last word was: " + last_word(sentence))
Output:
The first word was: Python

The last word was: language

Main function code in a module

If a module contains any code which is not contained within a function


definition (that is, if the module contains code in the main function of the module),
this code is executed automatically whenever the module is imported.

Let's assume our words.py file also contained some test cases:

def first_word(my_string: str):


parts = my_string.split(" ")
return parts[0]

def last_word(my_string: str):


parts = my_string.split(" ")
return parts[-1]

def number_of_words(my_string: str):


parts = my_string.split(" ")
return len(parts)

print(first_word("This is a test"))
print(last_word("Here we are still testing"))
print(number_of_words("One two three four five"))

79
Now, if we import the module with an import statement, all the code in the module
which is outside the defined functions is automatically executed:

import words
my_string = "Sheila sells seashells by the seashore"
print(words.first_word(my_string))
print(words.last_word(my_string))
print(words.number_of_words(my_string))
Output:
This
testing
5
Sheila
seashore
6

80
UNIT IV

Python Lists
Python Lists are just like dynamically sized arrays, declared in other languages
(vector in C++ and ArrayList in Java). In simple language, a list is a collection of
things, enclosed in [ ] and separated by commas.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
Example of the list in Python

Var = ["Geeks", "for", "Geeks"]

print(Var)

Output:

["Geeks", "for", "Geeks"]

Lists are the simplest containers that are an integral part of the Python language.
Lists need not be homogeneous always which makes it the most powerful tool in Python.
A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are
mutable, and hence, they can be altered even after their creation.

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square
brackets[]. Unlike Sets, a list doesn’t need a built-in function for its creation of a list.

Note: Unlike Sets, the list may contain mutable elements.

Example 1: Creating a list in Python


# Python program to demonstrate

List = []

print("Blank List: ")

print(List)

List = [10, 20, 14]

print("\nList of numbers: ")

print(List)

List = ["Geeks", "For", "Geeks"]

print("\nList Items: ")


81
print(List[0])

print(List[2])

Output

Blank List:

[]

List of numbers:

[10, 20, 14]

List Items:

Geeks

Geeks

Complexities for Creating Lists

Time Complexity: O(1)

Space Complexity: O(n)

Accessing elements from the List


In order to access the list items refer to the index number. Use the index operator
[ ] to access an item in a list. The index must be an integer. Nested lists are accessed
using nested indexing.

Example 1: Accessing elements from list

# Python program to demonstrate

List = ["Geeks", "For", "Geeks"]

print("Accessing a element from the list")

print(List[0])

print(List[2])

Output

Accessing a element from the list

Geeks

Geeks
82
Updating List Values

Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append() and insert()
methods can also add values to a list.

Consider the following example to update the values inside the List.

Code

# updating list values

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

print(list)

# It will assign value to the value to the second index

list[2] = 10

print(list)

# Adding multiple-element

list[1:3] = [89, 78]

print(list)

# It will add value at the end of the list

list[-1] = 25

print(list)

Output:

[1, 2, 3, 4, 5, 6]

[1, 2, 10, 4, 5, 6]

[1, 89, 78, 4, 5, 6]

[1, 89, 78, 4, 5, 25]

Nested List
List Comprehension are one of the most amazing features of Python. It is a smart
and concise way of creating lists by iterating over an iterable object. Nested List
Comprehensions are nothing but a list comprehension within another list
comprehension which is quite similar to nested for loops.

83
Nested List Comprehension in Python Syntax

Below is the syntax of nested list comprehension:

Syntax: new_list = [[expression for item in list] for item in list]

Parameters:

Expression: Expression that is used to modify each item in the statement

Item: The element in the iterable

List: An iterable object

Example:

matrix = []

for i in range(5):

# Append an empty sublist inside the list

matrix.append([])

for j in range(5):

matrix[i].append(j)

print(matrix)

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are

1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

1. Repetition

The redundancy administrator empowers the rundown components to be rehashed on


different occasions.

84
# repetition of list

# declaring the list

list1 = [12, 14, 16, 18, 20]

# repetition operator *

l = list1 * 2

print(l)

Output:

[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation

It concatenates the list mentioned on either side of the operator.

# concatenation of two lists

# declaring the lists

list1 = [12, 14, 16, 18, 20]

list2 = [9, 10, 32, 54, 86]

# concatenation operator +

l = list1 + list2

print(l)

Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length

It is used to get the length of the list

# size of the list

list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]

# finding length of the list

len(list1)

85
Output:

4. Iteration

The for loop is used to iterate over the list elements.

# iteration of the list

# declaring the list

list1 = [12, 14, 16, 39, 40]

# iterating

for i in list1:

print(i)

Output:

12

14

16

39

40

5. Membership

It returns true if a particular item exists in a particular list otherwise false.

# declaring the list

list1 = [100, 200, 300, 400, 500]

# true will be printed if value exists

# and false if not

print(600 in list1)

print(700 in list1)

print(1040 in list1)

print(300 in list1)

86
print(100 in list1)

print(500 in list1)

Output:

False

False

False

True

True

True

Python List methods


Python List Methods are the built-in methods in lists used to perform operations
on Python lists/arrays.
List Methods in Python
Let’s look at some different list methods in Python for Python lists:
S.no Method Description

Used for adding elements to the end of the


1 append()
List.

2 copy() It returns a shallow copy of a list

This method is used for removing all items


3 clear()
from the list.

4 count() These methods count the elements.

Adds each element of an iterable to the end


5 extend()
of the List

6 index() Returns the lowest index where the

87
S.no Method Description

element appears.

Inserts a given element at a given index in


7 insert()
a list.

Removes and returns the last value from


8 pop()
the List or the given index value.

9 remove() Removes a given object from the List.

10 reverse() Reverses objects of the List in place.

Sort a List in ascending, descending, or


11 sort()
user-defined order

Calculates the minimum of all the


12 min()
elements of the List

Calculates the maximum of all the


13 max()
elements of the List

Tuples in Python

Python Tuple is a collection of objects separated by commas. In some ways, a


tuple is similar to a Python list in terms of indexing, nested objects, and repetition but
the main difference between both is Python tuple is immutable, unlike the Python list
which is mutable.

A comma-separated group of items is called a Python triple. The ordering, settled items,
and reiterations of a tuple are to some degree like those of a rundown, but in contrast to
a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the components of a tuple
once they have been assigned. On the other hand, we can edit the contents of a list.

88
Creating Python Tuples

There are various ways by which you can create a tuple in Python. They are as follows:
 Using round brackets
 With one item
 Tuple Constructor

Create Tuples using Round Brackets ()


To create a tuple we will use () operators.
var = ("Geeks", "for", "Geeks")

print(var)

Output:

('Geeks', 'for', 'Geeks')

Features of Python Tuple

 Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
 Each element in a tuple has a specific order that will never change because tuples
are ordered sequences.

Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.

# Python program to show how to create a tuple

# Creating an empty tuple

empty_tuple = ()

print("Empty tuple: ", empty_tuple)

# Creating tuple having integers

int_tuple = (4, 6, 8, 10, 12, 14)

print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types

mixed_tuple = (4, "Python", 9.3)

89
print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple

nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))

print("A nested tuple: ", nested_tuple)

Output:

Empty tuple: ()

Tuple with integers: (4, 6, 8, 10, 12, 14)

Tuple with different data types: (4, 'Python', 9.3)

A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Accessing Tuple Elements


A tuple's objects can be accessed in a variety of ways.

Indexing

Indexing We can use the index operator [] to access an object in a tuple, where the index
starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error will be
raised assuming we attempt to get to a list from the Tuple that is outside the scope of the
tuple record. An index above four will be out of range in this scenario.

Because the index in Python must be an integer, we cannot provide an index of a


floating data type or any other type. If we provide a floating index, the result will be
TypeError.

The method by which elements can be accessed through nested tuples can be seen in the
example below

# Python program to show how to access tuple elements

# Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Collection")

print(tuple_[0])

print(tuple_[1])

90
# trying to access element index more than the length of a tuple

try:

print(tuple_[5])

except Exception as e:

print(e)

# trying to access elements through the index of floating data type

try:

print(tuple_[1.0])

except Exception as e:

print(e)

# Creating a nested tuple

nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))

# Accessing the index of a nested tuple

print(nested_tuple[0][3])

print(nested_tuple[1][1])

Output:

Python

Tuple

tuple index out of range

tuple indices must be integers or slices, not float

Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or
remove tuple components as a result.

However, the keyword del can completely delete a tuple.

# Python program to show how to delete elements of a Python tuple


91
# Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")

# Deleting a particular element of the tuple

try:

del tuple_[3]

print(tuple_)

except Exception as e:

print(e)

# Deleting the variable from the global space of the program

del tuple_

# Trying accessing the tuple after deleting it

try:

print(tuple_)

except Exception as e:

print(e)

Output:

'tuple' object does not support item deletion

name 'tuple_' is not defined

Nested Tuples in Python


A nested tuple is a Python tuple that has been placed inside of another tuple. Let's
have a look at the following 8-element tuple.

tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))

This last element, which consists of three items enclosed in parenthesis, is known as a
nested tuple since it is contained inside another tuple. The name of the main tuple with
the index value, tuple[index], can be used to obtain the nested tuple, and we can access
each item of the nested tuple by using tuple[index-1][index-2].

Example of a Nested Tuple

# Creating a nested tuple of one element only

92
employee = ((10, "Itika", 13000),)

print(employee)

# Creating a multiple-value nested tuple

employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 20001), (40, "Peter",
16395))

print(employee)

Output:

((10, 'Itika', 13000),)

((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter', 16395))

Difference Between List and Tuple in Python


Lists and Tuples in Python are two classes of Python Data Structures. The list structure
is dynamic, and readily changed whereas the tuple structure is static and cannot be
changed.
This means that the tuple is generally faster than the list. Lists are denoted by square
brackets and tuples are denoted with parenthesis.
Differences between List and Tuple in Python
Sno LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


2
consuming comparatively Faster

The list is better for performing A Tuple data type is appropriate


3
operations, such as insertion and deletion. for accessing the elements

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-


5 Lists have several built-in methods
in methods.

Unexpected changes and errors are more Because tuples don’t change they
6
likely to occur are far less error-prone.

93
Python Dictionary

Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.

The data is stored as key-value pairs using a Python dictionary

o This data structure is mutable


o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.

A dictionary is, in other words, a group of key-value pairs, where the values can be any
Python object. The keys, in contrast, are immutable Python objects, such as strings,
tuples, or numbers.

Creating the Dictionary

Curly brackets are the simplest way to generate a Python dictionary, although there are
other approaches as well. With many key-value pairs surrounded in curly brackets and a
colon separating each key from its value, the dictionary can be built. (:). The following
provides the syntax for defining the dictionary.

Syntax:

Dict = {"Name": "Gayle", "Age": 25}

In the above dictionary Dict, The keys Name and Age are the strings which comes
under the category of an immutable object.

How to Create a Dictionary


In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’.
The dictionary holds pairs of values, one being the Key and the other corresponding
pair element being its Key:value.
Values in a dictionary can be of any data type and can be duplicated, whereas keys
can’t be repeated and must be immutable.

94
Note – Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print("\nDictionary with the use of Integer Keys: ")

print(Dict)

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys: ")

print(Dict)

Output

Dictionary with the use of Integer Keys:

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:

{'Name': 'Geeks', 1: [1, 2, 3, 4]}

Complexities for Creating a Dictionary:

Time complexity: O(len(dict))

Space complexity: O(n)

Accessing the dictionary values


To access data contained in lists and tuples, indexing has been studied. The keys of the
dictionary can be used to obtain the values because they are unique from one another.
The following method can be used to access dictionary values.

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}

print(type(Employee))

print("printing Employee data .... ")

print("Name : %s" %Employee["Name"])

print("Age : %d" %Employee["Age"])

print("Salary : %d" %Employee["salary"])

print("Company : %s" %Employee["Company"])

95
Output

<class 'dict'>

printing Employee data ....

Name : Dev

Age : 20

Salary : 45000

Company : WIPRO

Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.

Complexities for Accessing elements in a Dictionary:

Time complexity: O(1)

Space complexity: O(1)

Deleting Elements using ‘del’ Keyword


The items of the dictionary can be deleted by using the del keyword as given below.

Example: The code defines a dictionary, prints its original content, and then uses the
‘del’ statement to delete the element associated with key 1. After deletion, it prints the
updated dictionary, showing that the specified element has been removed.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Dictionary =")

print(Dict)

del(Dict[1])

print("Data after deletion Dictionary=")

print(Dict)

Output

Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}

Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}

96
Dictionary Methods
Here is a list of in-built dictionary functions with their description. You can use these
functions to operate on a dictionary.

Method Description

Remove all the elements from the


dict.clear()
dictionary

dict.copy() Returns a copy of the dictionary

dict.get(key, default = “None”) Returns the value of specified key

Returns a list containing a tuple for


dict.items()
each key value pair

Returns a list containing dictionary’s


dict.keys()
keys

Updates dictionary with specified key-


dict.update(dict2)
value pairs

Returns a list of all the values of


dict.values()
dictionary

pop() Remove the element with specified key

popItem() Removes the last inserted key-value pair

set the key to the default value if the key


dict.setdefault(key,default= “None”)
is not specified in the dictionary

returns true if the dictionary contains


dict.has_key(key)
the specified key.

97
Difference Between List and Dictionary in Python
Here are the differences present between List and Dictionary in Python:

Parameters List Dictionary

Basics A list refers to a collection of A dictionary refers to a hashed structure of


various index value pairs like various pairs of keys and values.
that in the case of an array in
C++.

Creation We can create a list by placing We can create a dictionary by placing all the
all the available elements into a available elements into a { } in the form of a
[ ] and separating them using key:vale. Here, we have to separate each pair of
“,” commas. available key-values using the “,” commas.

Data Type The indices in the case of a list The keys present in a dictionary can easily be
are basically integers that start of any given data type.
from the value 0.

Mode of We can access the elements in We can access the elements present in a
Accessing a key using indices. dictionary using the key-values.

Order of The entered order of elements We don’t have any guarantee of maintaining
Elements is always maintained. the order of the available elements.

98
UNIT V
File Handling in Python
File handling in Python is a powerful and versatile tool that can be used to
perform a wide range of operations. However, it is important to carefully consider the
advantages and disadvantages of file handling when writing Python programs, to
ensure that the code is secure, reliable, and performs well.

The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related information.
We can access the stored information (non-volatile) after the program termination.

In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character like a
comma (,) or a newline character. Python executes the code line by line. So, it works in
one line and then asks the interpreter to start the new line again. This is a continuous
process in Python.

Python supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. The
concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, like other concepts of Python, this
concept here is also easy and short.
Python treats files differently as text or binary and this is important. Each line
of code includes a sequence of characters, and they form a text file. Each line of a file is
terminated with a special character, called the EOL or End of Line characters
like comma {,} or newline character.
It ends the current line and tells the interpreter a new one has begun. Let’s start
with the reading and writing files.

Advantages of File Handling in Python


 Versatility: File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform
different operations on files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling,
making it easy to create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.

99
Disadvantages of File Handling in Python
 Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the file
system (e.g. file permissions, file locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially if
the program accepts user input that can be used to access or modify sensitive files
on the system.
 Complexity: File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be paid to
the code to ensure that files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.

Types of files in Python:


In Python, files come in two distinct flavors: text and binary.

Text Files: Easily readable by humans, text files find their purpose in storing textual
data, such as documents, configuration files, and Python source code. Python offers
seamless handling of these files, facilitating straightforward text-based operations.

Binary Files: Contrary to text files, binary files store non-textual data, including
images, audio, video, or any data that defies textual representation. Manipulating binary
files necessitates specialized functions.

Access modes govern the type of operations possible in the opened file. It refers to how
the file will be used once its opened. These modes also define the location of the File
Handle in the file. The file handle is like a cursor, which defines from where the data
has to be read or written in the file and we can get Python output in text file.

There are 6 access modes in Python:


 Read Only (‘r’)
 Read and Write (‘r+’)
 Write Only (‘w’)
 Write and Read (‘w+’)
 Append Only (‘a’)
 Append and Read (‘a+’)

Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning
of the file. If the file does not exist, raises the I/O error. This is also the default mode
in which a file is opened.
100
Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not exist.
Write Only (‘w’) : Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the beginning of the file.
Creates the file if the file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file,
data is truncated and over-written. The handle is positioned at the beginning of the
file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted
at the end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if
it does not exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.

Opening a file in Python


There are two types of files that can be handled in Python, normal text files and
binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the
file ready either for reading or for writing.
This can be done using the open() function. This function returns a file object
and takes two arguments, one that accepts the file name and another that accepts the
mode(Access Mode).

Note: The file should exist in the same directory as the Python script, otherwise, the
full address of the file should be written.

Syntax: File_object = open(“File_Name”, “Access_Mode”)


Parameters:
 File_Name: It is the name of the file that needs to be opened.
 Access_Mode: Access modes govern the type of operations possible in the
opened file. The below table gives the list of all access mode available in python
Example 1: Open and read a file using Python

In this example, we will be opening a file to read-only. The initial file looks like the be

# open the file using open() function

file = open("sample.txt")

# Reading from file

print(file.read())

Here we have opened the file and printed its content.

101
Output:

Hello Geek!

This is a sample text file for the example.

Closing a file in Python


As you notice, we have not closed any of the files that we operated on in the above
examples. Though Python automatically closes a file if the reference object of the file is
allocated to another file, it is a standard practice to close an opened file as a closed file
reduces the risk of being unwarrantedly modified or read.

Python has a close() method to close a file. The close() method can be called more
than once and if any operation is performed on a closed file it raises a ValueError. The
below code shows a simple use of close() method to close an opened file.

Example: Read and close the file using Python

#open the file using open() function

file = open("sample.txt")

# Reading from file

print(file.read())

# closing the file

file.close()

# Attempt to write in the file

file.write(" Attempt to write on a closed file !")

Output:

ValueError: I/O operation on closed file.

Reading and Writing to text files in Python

Python provides built-in functions for creating, writing, and reading files. Two
types of files can be handled in Python, normal text files and binary files (written in
binary language, 0s, and 1s).
 Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in Python
by default.
102
 Binary files: In this type of file, there is no terminator for a line, and the data is
stored after converting it into machine-understandable binary language.

Writing to a file in Python

There are two ways to write in a file:


 Using write()
 Using writelines()
Writing to a Python Text File Using write()

write() : Inserts the string str1 in a single line in the text file.

File_object.write(str1)

Writing to a Text File Using writelines()

writelines() : For a list of string elements, each string is inserted in the text file.Used
to insert multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]

Reading from a file in Python

There are three ways to read data from a text file:


 Using read()
 Using readline()
 Using readlines()

Reading From a File Using read()


read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file.

File_object.read([n])

Reading a Text File Using readline()

readline() : Reads a line of the file and returns in form of a string.For specified n,
reads at most n bytes. However, does not reads more than one line, even if n exceeds the
length of the line.

File_object.readline([n])
103
Reading a File Using readlines()

readlines() : Reads all the lines and return them as each line a string element in a list.

File_object.readlines()

Note: ‘\n’ is treated as a special character of two bytes.

In this example, a file named “myfile.txt” is created and opened in write mode
("w"). Data is written to the file using write and writelines methods. The file is then
reopened in read and append mode ("r+"). Various read operations,
including read, readline, readlines, and the use of seek, demonstrate different ways to
retrieve data from the file. Finally, the file is closed.
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes
file1 = open("myfile.txt", "r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# byte from the beginning.
file1.seek(0)
print("Output of Readline function is ")
print(file1.readline())
print()

file1.seek(0)
104
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()

file1.close()

Output:

Output of Read function is

Hello

This is Delhi

This is Paris

This is London

Output of Readline function is

Hello

Output of Read(9) function is

Hello

Th

Output of Readline(9) function is

Hello

Output of Readlines function is

105
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Appending To a File in Python


In this example, a file named “myfile.txt” is initially opened in write mode ("w")
to write lines of text. The file is then reopened in append mode ("a"), and “Today” is
added to the existing content. The output after appending is displayed using readlines.
Subsequently, the file is reopened in write mode, overwriting the content with
“Tomorrow”. The final output after writing is displayed using readlines.

# Python program to illustrate


# Append vs write mode
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()

Output:

Output of Readlines after appending

['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing

['Tomorrow \n']

106
Python File Methods
❮ PreviousNext ❯

Python has a set of methods available for the file object.

Method Description

close() Closes the file

detach() Returns the separated raw stream from the buffer

fileno() Returns a number that represents the stream, from the operating system's
perspective

flush() Flushes the internal buffer

isatty() Returns whether the file stream is interactive or not

read() Returns the file content

readable() Returns whether the file stream can be read or not

readline() Returns one line from the file

readlines() Returns a list of lines from the file

seek() Change the file position

107
seekable() Returns whether the file allows us to change the file position

tell() Returns the current file position

truncate() Resizes the file to a specified size

writable() Returns whether the file can be written to or not

write() Writes the specified string to the file

writelines() Writes a list of strings to the file

File Positions

There are two more methods of file objects used to determine or get files positions.

tell()

seek()

tell():
This method is used to tell us the current position within the file which means the next
read or write operation will be performed that many bytes away from the start of the file.
Syntax :
obj.tell()

Example :
#create file object and show the use tell()
object=open("itvoyagers.txt",'w')
object.write("first statement n")
object.write("second statement n")
object=open("itvoyagers.txt",'r')

108
s=11
c=object.read(s)
print(object.tell()) #tells the position based on parameter passed in read operation
g=object.read()
print(object.tell()) #tells position after performing read() on entire file

seek():
This method is used to change the current position of file.This method has two main
parameters offset and from.

Syntax :
obj.seek(offset,from)

Here, offset argument means the number of bytes to be moved.


from argument is used to specify the reference position from where the bytes needs to
be moved.
Points to Remember for “from” argument
if from is set to 0 ,it means use the beginning of the file as reference position

if from is set to 1 ,it means use the current position of the file as reference
position

if from is set to 2 ,it means use the end of the file as reference position

Example :
#create file object and show the use seek()
with open("itvoyagers.txt","r") as f:
s=10
c=f.read(s) #reads till 10 char
print(c,end=' ') #adds space after first read()
f.seek(0,0) #goes to start position in file
c=f.read(s)
print(c)
f.seek(0,1) #goes to current position in file
c=f.read(s)
print(c)
f.seek(0,2) #goes to end position in file
c=f.read(s)
print(c)

109
Python - Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.

To use this module, you need to import it first and then you can call any related
functions.

rename() Method

The rename() method takes two arguments, the current filename and the new filename.

Syntax

os.rename(current_file_name, new_file_name)

Example

Following is an example to rename an existing file "test1.txt" to "test2.txt" −

#!/usr/bin/python3

import os

# Rename a file from test1.txt to test2.txt

os.rename( "test1.txt", "test2.txt" )

remove() Method

You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.

Syntax

os.remove(file_name)

Example

Following is an example to delete an existing file "test2.txt" −

#!/usr/bin/python3

import os

# Delete file test2.txt

os.remove("text2.txt")

Print Page

110

You might also like