0% found this document useful (0 votes)
12 views178 pages

I Python Notes

The document outlines the study material and question paper pattern for the I BCA Python Programming course at Shri Sakthikailassh Women's College. It includes details on the syllabus covering Python basics, control statements, functions, data structures, and file handling, along with a historical overview of Python's development. The paper pattern consists of multiple-choice questions, short answer questions, and detailed answer questions across various units.

Uploaded by

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

I Python Notes

The document outlines the study material and question paper pattern for the I BCA Python Programming course at Shri Sakthikailassh Women's College. It includes details on the syllabus covering Python basics, control statements, functions, data structures, and file handling, along with a historical overview of Python's development. The paper pattern consists of multiple-choice questions, short answer questions, and detailed answer questions across various units.

Uploaded by

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

SHRI SAKTHIKAILASSH WOMEN’S COLLEGE

Military Road, Ammapet, Salem-636003

DEPARTMENT OF COMPUTER APPLICATIONS

I BCA PYTHON PROGRAMMING

STUDY MATERIAL
QUESTION PAPER PATTERN

TIME: 3 Hours
Max.Ma
rks:75

PART – A (15*1=15 MARKS)

Answer all the questions

Three questions from each unit (Multiple Choice Questions)

PART – B (2*5=10 MARKS)

Answer any two questions

One question from each unit

PART – C (5*10=50 MARKS)

Answer all the questions

One question from each unit (Either or Type)


24UCA01-PYTHONPROGRAMMING

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 Life time 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
Element 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.
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.

HISTORY of PYTHON:

➢ 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

Why the Name Python?


 There is a fact behind choosing the name Python. Guido van Rossum was reading the script of
a popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
 Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
 The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
 Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.

Usage of Python

Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.
➢ Desktop Applications
➢ Web Applications
➢ Data Science
➢ Artificial Intelligence
➢ Machine Learning
➢ Scientific Computing
➢ Robotics
➢ Internet of Things (IoT)
➢ Gaming
➢ Mobile Apps
➢ Data Analysis and Preprocessing
➢ Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release.
➢ Latest version of Python 3.11.4 released on 24 October 2022.

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.
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 www.python.org. 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.
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. Suppose we are
assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
PYTHON LITERAL:

TYPES OF PYTHON LITERAL:

I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as
double quotes to create a string.
Example:
"Aman" , '12345'
TYPES OF STRINGS:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as Single line
Strings.
Example: text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
II. Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical
types.
Int(signed Long(long float(floating Complex(complex)
integers) integers) point)

Numbers can be Integers of Real numbers with In the form of a+bj where a
both positive and unlimited size both integer and forms the real part and b forms
negative) with no followed by fractional part eg: - the imaginary part of the
fractional part.eg: lowercase or 26.2 complex number. eg: 3.14j
100 uppercase L eg:
87032845L

Example - Numeric Literals


x = 0b10100 #Binary Literals
y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal
III. Boolean literals:
A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
IV. Special literals:
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for the end of lists in Python.
Example - Special Literals
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
V. Literal Collections:
Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals,
and Set literals.
❖ List:
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square brackets([]).
We can store different types of data in a List.

Example - List literals


list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
❖ Dictionary:
o Python dictionary stores the data in the key-value pair.
o It is enclosed by curly-braces {} and each pair is separated by the commas(,).

Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}

❖ Tuple:
o Python tuple is a collection of different data-type. It is immutable which means it cannot be
modified after creation.
o It is enclosed by the parentheses () and each element is separated by the comma(,).

Example
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
❖ Set:
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the comma(,).

Example: - Set Literals

set = {'apple','grapes','guava','papaya'}
print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}
CONSTANT:
✓ a constant term is used in Mathematics, a value or quantity that never changes.
✓ In programming, a constant refers to the name associated with a value that never changes during
the programming execution.
✓ Programming constant is different from other constants, and it consists of two things - a name
and an associated value.
✓ A real-life example is - The speed of light, the number of minutes in an hour, and the name of a
project's root folder.
Advantages of constant:

o Improved Readability - It helps to improve the readability of the code. For example, it is
easier to read and understand a constant named MAX_SPEED than the substantial speed
value itself.
o Clear communication of intent - Most developers consider the 3.14 as the pi constant.
However, the Pi, pi, or PI name will communicate intent more clearly. This practice will
allow another developer to understand our code.
o Better Maintainability - Constants allow us to use the same value throughout your code.
Suppose we want to update the constant's value; we don't need to change every instance.
o Low risk of errors - A constant representing a given value throughout a program is less
error-prone. If we want to change the precision in the calculations, replacing the value can be
risky. Instead of replacing it, we can create different constants for different precision levels
and change the code where we needed.
o Thread-safe data storage - A constants are thread-safe objects, meaning several threads can
simultaneously use a constant without risking losing data.

Built-in Constants:
In the official documentation, the True and False are listed as the first constant. These are Python Boolean values
and are the instance of the int. A True has a value of 1, and False has a value 0.
Example -
>>> True
True
>>> False
False
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> int(True)
1
>>> int(False)
0
>>> True = 42
...
SyntaxError: cannot assign to True
>>> True is True
True
>>> False is False
True
PYTHON VARIABLES:
Variables
Variables are containers for storing data values.
Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x=5
y = "John"
print(x)
print(y)
Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and smart
enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
Identifier Naming:
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
o The first character of the variable must be an alphabet or underscore ( _ ).
o All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are
used to denote objects by that name.
Let's understand the following example

a = 50

In the above image, the variable a refers to an integer object.


Suppose we assign the integer value 50 to a new variable b.
a = 50
b=a

The variable b refers to the same object that a points to because Python does not create another
object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100

Python manages memory efficiently if we assign the same variable to two different values.

Object Identity
In Python, every created object identifies uniquely in Python. Python provides the guaranteed that no
two objects will have the same identifier. The built-in id() function, is used to identify the object
identifier.
Consider the following example.
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944

The multi-word keywords can be created by the following method.


⚫ Camel Case - In the camel case, each word or abbreviation in the middle of begins with a
capital letter. There is no intervention of whitespace. For example - nameOfStudent,
valueOfVaraible, etc.
⚫ Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For
example - NameOfStudent, etc.
⚫ Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
PYTHON VARIABLE TYPES:
There are two types of variables in Python - Local variable and Global variable. Let's understand the
following variables.

➢ LOCAL VARIABLE:

Local variables are the variables that declared inside the function and have scope within the function.
Let's understand the following example.

Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
Explanation:
In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside the
function. If we try to use them outside the function, we get a following error.
add()
# Accessing local variable outside the function
print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw the NameError.

➢ GLOBAL VARIABLES:

✓ Global variables can be used throughout the program, and its scope is in the entire program. We
can use global variables inside or outside the function.
✓ A variable declared outside the function is the global variable by default.
✓ Python provides the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable.
Let's understand the following example.
Example -
Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint

Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we defined a function
and accessed the declared variable using the global keyword inside the function. Now we can modify
its value. Then, we assigned a new string value to the variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.

Delete a variable:
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x, and
print it, we get the error "variable x is not defined". The variable x will no longer use in future.
Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
6

BASIC FUNDAMENTALS:
i)Tokens and their types.
ii) Comments
a)Tokens:
➢ The tokens can be defined as a punctuator mark, reserved words, and each word in a
statement.
➢ The token is the smallest unit inside the given program.
There are following tokens in Python:

o Keywords.
o Identifiers.
o Literals.
o Operators.

KEYWORDS:

✓ Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions.
✓ You'll never need to import any keyword into your program because they're permanently present.
✓ Python's built-in methods and classes are not the same as the keywords.
✓ Built-in methods and classes are constantly present; however, they are not as limited in their
application as keywords.
✓ False ✓ await ✓ else ✓ import ✓ pass

✓ None ✓ break ✓ except ✓ in ✓ raise


✓ True ✓ class ✓ finally ✓ is ✓ return
✓ and ✓ continue ✓ for ✓ lambda ✓ try
✓ as ✓ def ✓ from ✓ nonlocal ✓ while
✓ assert ✓ del ✓ global ✓ not ✓ with
✓ async ✓ elif ✓ if ✓ or ✓ yield

✓ # Python program to demonstrate the application of iskeyword()


# importing keyword library which has lists
import keyword

# displaying the complete list using "kwlist()."


print("The set of keywords in this version is: ")
print( keyword.kwlist )

Output:

The set of keywords in this version is :


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']

By calling help(), you can retrieve a list of currently offered keywords:

Code
help("keywords")

Python Keywords and Their Usage:


The are so many categorize in Python keywords under the headings based on their frequency of use.
The first category, for instance, includes all keywords utilized as values, whereas the next group
includes keywords employed as operators. These classifications will aid in understanding how
keywords are employed and will assist you in arranging the huge collection of Python keywords.
o The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness
reveals if the value of the variable is true or false.

Value Keywords: True, False, None


Three Python keywords are employed as values in this example. These are singular values, which we
can reuse indefinitely and every time correspond to the same entity. These values will most probably
be seen and used frequently.
The Keywords True and False
These keywords are typed in lowercase in conventional computer languages (true and false);
however, they are typed in uppercase in Python every time. In Python script, the True Python
keyword represents the Boolean true state. False is a keyword equivalent to True, except it has the
negative Boolean state of false.
True and False are those keywords that can be allocated to variables or parameters and are compared
directly.
Code
print( 4 == 4 )
print( 6 > 9 )
print( True or False )
print( 9 <= 28 )
print( 6 > 9 )
print( True and False )
Output:
True
False
True
True
False
False
Because the first, third, and fourth statements are true, the interpreter gives True for those and
False for other statements. True and False are the equivalent in Python as 1 & 0. We can use
the accompanying illustration to support this claim:
Code
print( True == 3 )
print( False == 0 )
print( True + True + True)
Output:
False
True
3
The None Keyword
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in different
computer languages.
If a function does not have a return clause, it will give None as the default output:
Code

print( None == 0 )
print( None == " " )
print( None == False )
A = None
B = None
print( A == B )
Output:
False
False
False
True
If a no_return_function returns nothing, it will simply return a None value. None is delivered by
functions that do not meet a return expression in the program flow. Consider the following scenario:
Code
def no_return_function():
num1 = 10
num2 = 20
addition = num1 + num2
number = no_return_function()
print( number )
Output:
None
This program has a function with_return that performs multiple operations and contains a return
expression. As a result, if we display a number, we get None, which is given by default when there is
no return statement. Here's an example showing this:
Code
def with_return( num ):
if num % 4 == 0:
return False
number = with_return( 67 )
print( number )
Output:

None
Operator Keywords: and, or, not, in, is
Several Python keywords are employed as operators to perform mathematical operations. In many
other computer languages, these operators are represented by characters such as &, |, and!. All of
these are keyword operations in Python:
Mathematical Operations Operations in Other Languages Python Keyword

AND, ∧ && and

OR, ∨ || or

NOT, ¬ ! not

CONTAINS, ∈ in

IDENTITY === is
Writers created Python programming with clarity in mind. As a result, many operators in other
computer languages that employ characters in Python are English words called keywords.
The and Keyword
The Python keyword and determines whether both the left-hand side and right-hand side operands
and are true or false. The outcome will be True if both components are true. If one is false, the
outcome will also be False:

Truth table for and

X Y X and Y

True True True


False True False
True False False
False False False

component1> and <component2>


It's worth noting that the outcomes of an and statement aren't always True or False. Due to
and's peculiar behavior, this is the case. Instead of processing the inputs to corresponding
Boolean values, it just gives <component1> if it is false or <component2> if it is true. The
outputs of a and expression could be utilized with a conditional if clause or provided to bool()
to acquire an obvious True or False answer.
The or Keyword
The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the
first argument is true, the or operation yields it; otherwise, the second argument is returned:
<component1> or <component2>
Similarly to the and keyword, the or keyword does not change its inputs to corresponding
Boolean values. Instead, the outcomes are determined based on whether they are true or false.

Truth table for or


X Y X or Y

True True True


True False True

False True True


False False False
The not Keyword
The not keyword in Python is utilized to acquire a variable's contrary Boolean value:
The not keyword is employed to switch the Boolean interpretation or outcome in conditional
sentences or other Boolean equations. Not, unlike and, and or, determines the specific Boolean state,
True or False, afterward returns the inverse.

Truth Table for not

X not X

True False

False True
Code

False and True


False or True
not True
Output:
False
True
False
The in Keyword
The in keyword of Python is a robust confinement checker, also known as a membership operator. If
you provide it an element to seek and a container or series to seek into, it will give True or False,
depending on if that given element was located in the given container:
<an_element> in <a_container>
Testing for a certain character in a string is a nice illustration of how to use the in keyword:
Code
container = "Javatpoint"
print( "p" in container )
print( "P" in container )
Output:
True
False
Lists, dictionaries, tuples, strings, or any data type with the method __contains__(), or we can iterate
over it will work with the in keyword.
The is Keyword
In Python, it's used to check the identification of objects. The == operation is used to determine
whether two arguments are identical. It also determines whether two arguments relate to the unique
object.
When the objects are the same, it gives True; otherwise, it gives False.
Code
print( True is True )
print( False is True )
print( None is not None )
print( (9 + 5) is (7 * 2) )
Output:
True
False
False
True
True, False, and None are all the same in Python since there is just one version.
Code
print( [] == [] )
print( [] is [] )
print( {} == {} )
print( {} is {} )
Output:
True
False
True
False
A blank dictionary or list is the same as another blank one. However, they aren't identical entities
because they are stored independently in memory. This is because both the list and the dictionary are
changeable.
Code
print( '' == '' )
print( '' is '' )
Output:
True
True
Strings and tuples, unlike lists and dictionaries, are unchangeable. As a result, two equal strings or
tuples are also identical. They're both referring to the unique memory region.
The nonlocal Keyword
Nonlocal keyword usage is fairly analogous to global keyword usage. The keyword nonlocal is
designed to indicate that a variable within a function that is inside a function, i.e., a nested function is
just not local to it, implying that it is located in the outer function. We must define a non-local
parameter with nonlocal if we ever need to change its value under a nested function. Otherwise, the
nested function creates a local variable using that title. The example below will assist us in clarifying
this.
Code
def the_outer_function():
var = 10
def the_inner_function():
nonlocal var
1. var = 14
2. print("The value inside the inner function: ", var)
3. the_inner_function()
4. print("The value inside the outer function: ", var)
5.
6. the_outer_function()
Output:
The value inside the inner function: 14
The value inside the outer function: 14
the_inner_function() is placed inside the_outer_function in this case.
The the_outer_function has a variable named var. Var is not a global variable, as you may have
noticed. As a result, if we wish to change it inside the the_inner_function(), we should declare it
using nonlocal.
As a result, the variable was effectively updated within the nested the_inner_function, as evidenced
by the results. The following is what happens if you don't use the nonlocal keyword:
Code

def the_outer_function():
var = 10
def the_inner_function():
var = 14
print("Value inside the inner function: ", var)
the_inner_function()
print("Value inside the outer function: ", var)

the_outer_function()
Output:
Value inside the inner function: 14
Value inside the outer function: 10
Iteration Keywords: for, while, break, continue
The iterative process and looping are essential programming fundamentals. To generate and operate
with loops, Python has multiple keywords. These would be utilized and observed in almost every
Python program. Knowing how to use them correctly can assist you in becoming a better Python
developer.
The for Keyword
The for loop is by far the most popular loop in Python. It's built by blending two Python keywords.
They are for and in, as previously explained.
The while Keyword
Python's while loop employs the term while and functions similarly to other computer languages'
while loops. The block after the while phrase will be repeated repeatedly until the condition
following the while keyword is false.
The break Keyword
If you want to quickly break out of a loop, employ the break keyword. We can use this keyword in
both for and while loops.
The continue Keyword
You can use the continue Python keyword if you wish to jump to the subsequent loop iteration. The
continue keyword, as in many other computer languages, enables you to quit performing the present
loop iteration and go on to the subsequent one.
Code

# Program to show the use of keywords for, while, break, continue


for i in range(15):

print( i + 4, end = " ")

# breaking the loop when i = 9


if i == 9:
break
print()

# looping from 1 to 15
i = 0 # initial condition
while i < 15:

# When i has value 9, loop will jump to next iteration using continue. It will not print
if i == 9:
i += 3
continue
else:
# when i is not equal to 9, adding 2 and printing the value
print( i + 2, end = " ")

i += 1
Output:
4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 14 15 16
Exception Handling Keywords - try, except, raise, finally, and assert
try: This keyword is designed to handle exceptions and is used in conjunction with the keyword
except to handle problems in the program. When there is some kind of error, the program inside
the "try" block is verified, but the code in that block is not executed.
except: As previously stated, this operates in conjunction with "try" to handle exceptions.
finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.
raise: The raise keyword could be used to specifically raise an exception.
assert: This method is used to help in troubleshooting. Often used to ensure that code is correct.
Nothing occurs if an expression is interpreted as true; however, if it is false, "AssertionError" is
raised. An output with the error, followed by a comma, can also be printed.
Code
# initializing the numbers
var1 = 4
var2 = 0

# Exception raised in the try section


try:
d = var1 // var2 # this will raise a "divide by zero" exception.
print( d )
# this section will handle exception raised in try block
except ZeroDivisionError:
print("We cannot divide by zero")
finally:
# If exception is raised or not, this block will be executed every time
print("This is inside finally block")
# by using assert keyword we will check if var2 is 0
print ("The value of var1 / var2 is : ")
assert var2 != 0, "Divide by 0 error"
print (var1 / var2)
Output:
We cannot divide by zero
This is inside finally block
The value of var1 / var2 is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [44], in ()
15 # by using assert keyword we will check if var2 is 0
16 print ("The value of var1 / var2 is : ")
---> 17 assert var2 != 0, "Divide by 0 error"
18 print (var1 / var2)

AssertionError: Divide by 0 error


The pass Keyword
In Python, a null sentence is called a pass. It serves as a stand-in for something else. When it is run,
nothing occurs.
Let's say we possess a function that has not been coded yet however we wish to do so in the long
term. If we write just this in the middle of code,
Code
def function_pass( arguments ):
Output:
def function_pass( arguments ):
^
IndentationError: expected an indented block after function definition on line 1
as shown, IndentationError will be thrown. Rather, we use the pass command to create a blank
container.
Code

def function_pass( arguments ):


pass
We can use the pass keyword to create an empty class too.
Code
class passed_class:
pass
The return Keyword
The return expression is used to leave a function and generate a result.
The None keyword is returned by default if we don't specifically return a value. The accompanying
example demonstrates this.
Code
def func_with_return():
var = 13
return var

def func_with_no_return():
var = 10

print( func_with_return() )
print( func_with_no_return() )
Output:
13
None
The del Keyword
The del keyword is used to remove any reference to an object. In Python, every entity is an object.
We can use the del command to remove a variable reference.
Code
var1 = var2 = 5
del var1
print( var2 )
print( var1 )
Output:
5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [42], in ()
2 del var1
3 print( var2 )
----> 4 print( var1 )
NameError: name 'var1' is not defined
We can notice that the variable var1's reference has been removed. As a result, it's no longer
recognized. However, var2 still exists.
Deleting entries from a collection like a list or a dictionary is also possible with del:
Code
list_ = ['A','B','C']
del list_[2]
print(list_)
Output:
['A', 'B']
BUILT IN DATA TYPES:

Python Data Types are used to define the type of a variable. It defines what type of data we are going
to store in a variable. The data stored in memory can be of many types. For example, a person's age
is stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various built-in data types which we will discuss with in this tutorial:

• Numeric - int, float, complex


• String - str
• Sequence - list, tuple, range
• Binary - bytes, bytearray, memoryview
• Mapping - dict
• Boolean - bool
• Set - set, frozenset
• None - NoneType

Python Numeric Data Type


Python numeric data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
var3 = 10.023
Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)

Examples
Here are some examples of numbers −

Int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

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

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

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

Python allows you to use a lowercase l with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted by x +
yj, where x and y are the real numbers and j is the imaginary unit.
Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.

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

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

# complex variable.

c=10+3jprint("The type of variable having value", c, " is ", type(c))

Python String Data Type


Python Strings are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the
slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in
Python. For example −
str = 'Hello World!'
print (str)
# Prints complete stringprint (str[0])
# Prints first character of the stringprint (str[2:5])
# Prints characters starting from 3rd to 5thprint (str[2:])
# Prints string starting from 3rd characterprint (str * 2)
# Prints string two timesprint (str + "TEST")
# Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python List Data Type
Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays
in C. One difference between them is that all the items belonging to a Python list can be of different
data type where as C array can store elements related to a particular data type.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator. For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete listprint (list[0]) # Prints first element of the listprint
(list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting
from 3rd elementprint (tinylist * 2) # Prints list two timesprint (list + tinylist) # Prints concatenated
lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists. For example −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple)
# Prints the complete tupleprint (tuple[0])
# Prints first element of the tupleprint (tuple[1:3])
# Prints elements of the tuple starting from 2nd till 3rd print (tuple[2:])
# Prints elements of the tuple starting from 3rd elementprint (tinytuple * 2)
# Prints the contents of the tuple twiceprint (tuple + tinytuple) # Prints concatenated tuples
This produce the following result −
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tuple[2] = 1000 #
Invalid syntax with tuplelist[2] = 1000 # Valid syntax with list
Python Ranges
Python range() is an in-built function in Python which returns a sequence of numbers starting from 0
and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers. Following is the
syntax of the function:
range(start, stop, step)
Here is the description of the parameters used:

• start: Integer number to specify starting position, (Its optional, Default: 0)


• stop: Integer number to specify starting position (It's mandatory)
• step: Integer number to specify increment, (Its optional, Default: 1)

Examples
Following is a program which uses for loop to print number from 0 to 4 −
for i in range(5):
print(i)
This produce the following result −
0
1
2
3
4
Now let's modify above program to print the number starting from 1 instead of 0:
for i in range(1, 5):
print(i)
This produce the following result −
1
2
3
4
Again, let's modify the program to print the number starting from 1 but with an increment of 2
instead of 1:
for i in range(1, 5, 2):
print(i)
This produce the following result −
1
3
Python Dictionary
Python dictionaries are kind of hash table type. They work like associative arrays or hashes found in
Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually
numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −
dict = {}dict['one'] = "This is one"dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' keyprint (dict[2]) # Prints value for 2 keyprint
(tinydict) # Prints complete dictionaryprint (tinydict.keys()) # Prints all the keysprint
(tinydict.values()) # Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Python dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order"; they are simply unordered.
Python Boolean Data Types
Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression.
OUTPUT STATEMENTS:
The basic way to do output is the print statement.

print('Hello, world')

To print multiple things on the same line separated by spaces, use commas between them:

print('Hello,', 'World')

This will print out the following:

Hello, World

Syntax of print()

In the above code, the print() function is taking a single parameter.

However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,

object - value(s) to be printed

sep (optional) - allows us to separate multiple objects inside print().

end (optional) - allows us to add add specific values like new line "\n", tab "\t"

file (optional) - where the values are printed. It's default value is sys.stdout (screen)

flush (optional) - boolean specifying if the output is flushed or buffered. Default: False
INPUT:
Python input() Function
Python input() function is used to get input from the user. It prompts for the user input and reads a
line. After reading data, it converts it into a string and returns that. It throws an error EOF Error if
EOF is read.
Signature
input ([prompt])
Parameters
prompt: It is a string message which prompts for the user input.
Return
It returns user input after converting into a string.
Let's see some examples of input() function to understand it's functionality.
Python input() Function Example 1
we are using this function get user input and display to the user as well.
# Python input() function example
# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
Output:
Enter a value: 45
You entered: 45

Python Comments:
learn about single-line comments, multi-line comments, documentation strings, and other Python
comments.
Introduction to Python Comments
We may wish to describe the code we develop. We might wish to take notes of why a section of
script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and
sophisticated business logic are typically explained with comments. The Python interpreter overlooks
the remarks and solely interprets the script when running a program. Single-line comments, multi-
line comments, and documentation strings are the 3 types of comments in Python.
Advantages of Using Comments
Our code is more comprehensible when we use comments in it. It assists us in recalling why specific
sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other code
sections. This simple technique stops some lines from running or creates a fast pseudo-code for the
program.

Below are some of the most common uses for comments:


o Readability of the Code
o Restrict code execution
o Provide an overview of the program or project metadata
o To add resources to the code

Types of Comments in Python


In Python, there are 3 types of comments. They are described below:
Single-Line Comments
Single-line remarks in Python have shown to be effective for providing quick descriptions for
parameters, function definitions, and expressions. A single-line comment of Python is the one that
has a hashtag # at the beginning of it and continues until the finish of the line. If the comment
continues to the next line, add a hashtag to the subsequent line and resume the conversation.
Consider the accompanying code snippet, which shows how to use a single line comment:
Code
# This code is to show an example of a single-line comment
print( 'This statement does not have a hashtag before it' )
Output:
This statement does not have a hashtag before it
The following is the comment:
# This code is to show an example of a single-line comment
The Python compiler ignores this line.
Everything following the # is omitted. As a result, we may put the program mentioned above
in one line as follows:
Code
print( 'This is not a comment' ) # this code is to show an example of a single-line comment
Output:
This is not a comment
This program's output will be identical to the example above. The computer overlooks all content
following #.
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways
to create multi-line comments.
With Multiple Hashtags (#)
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every
line with a (#) before it will be regarded as a single-line comment.
Code
# it is a
# comment
# extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Using String Literals
Because Python overlooks string expressions that aren't allocated to a variable, we can utilize them
as comments.
Code
'it is a comment extending to multiple lines'
We can observe that on running this code, there will be no output; thus, we utilize the strings inside
triple quotes(""") as multi-line comments.

Python Docstring

The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain what
they perform. The docstring is then readily accessible in Python using the __doc__ attribute.
Code
# Code to show how we use docstrings in Python
def add(x, y):
"""This function adds the values of x and y"""
return x + y
# Displaying the docstring of the add function
print( add.__doc__ )
Output:
This function adds the values of x and y

INDENTATION

✓ Indentation is the leading whitespace (spaces or/and tabs) before any statement. The importance
of indentation in Python stems from the fact that it serves a purpose other than code readability.
✓ Python treats statements with the same indentation level (statements preceded by the same
number of whitespaces) as a single code block.
✓ So, whereas in languages such as C, C++, and others, a block of code is represented by curly
braces, a block in Python is a group of statements with the same Indentation level, i.e. the same
number of leading whitespaces.
Advantages of Indentation in Python
o Indentation is used in python to represent a certain block of code, but in other programming
languages, they refer to various brackets. Due to indentation, the code looks more efficient
and beautifully structured.
o Indentation rules used in a python programming language are very simple; even a
programmer wants their code to be readable.
o Also, indentation increases the efficiency and readability of the code by structuring it
beautifully.

Disadvantages of Indentation in Python


o Due to the uses of whitespaces in indentation, sometimes it is a very tough task to fix the
indentation error when there are many lines of code.
o The various popular programming languages like C, C++, Java use braces for indentation, so
anybody coming from the other side of the developed world finds it hard to adjust to the idea
of using whitespaces for the indentation.

EXPRESSIONS:

A combination of operands and operators is called an expression. The expression in Python


produces some value or result after being interpreted by the Python interpreter. An expression in
Python is a combination of operators and operands. An example of expression can be : x = x + 1
0 x = x + 10 x=x+10.

Example :
x = 25 # a statementx = x + 10 # an expressionprint(x)
Output :
35
An expression in Python is very different from statements in Python. A statement is not evaluated for
some results. A statement is used for creating variables or for displaying values.
Example :
a = 25 # a statementprint(a) # a statement
Output :
25
An expression in Python can contain identifiers, operators, and operands. Let us briefly discuss
them.
An identifier is a name that is used to define and identify a class, variable, or function in Python.
An operand is an object that is operated on. On the other hand, an operator is a special symbol that
performs the arithmetic or logical computations on the operands. There are many types of operators
in Python, some of them are :

• + : add (plus).
• - : subtract (minus).
• x : multiply.
• / : divide.
• ** : power.
• % : modulo.
• << : left shift.
• >> : right shift.
• & : bit-wise AND.
• | : bit-wise OR.
• ^ : bit-wise XOR.
• ~ : bit-wise invert.
• < : less than.
• > : greater than.
• <= : less than or equal to.
• >= : greater than or equal to.
• == : equal to.
• != : not equal to.
• and : boolean AND.
• or : boolean OR.
• not : boolean NOT.

The expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on their
precedence. We have various types of expression in Python, refer to the next section for a more
detailed explanation of the types of expression in Python.
Types of Expression in Python:
We have various types of expression in Python, let us discuss them along with their respective
examples.
1. Constant Expressions:
A constant expression in Python that contains only constant values is known as a constant expression.
In a constant expression in Python, the operator(s) is a constant. A constant is a value that cannot be
changed after its initialization.
Example :
x = 10 + 15# Here both 10 and 15 are constants but x is a variable.print("The value of x is: ", x)
Output :
The value of x is: 25

2. Arithmetic Expressions:
An expression in Python that contains a combination of operators, operands, and sometimes
parenthesis is known as an arithmetic expression. The result of an arithmetic expression is also a
numeric value just like the constant expression discussed above. Before getting into the example of
an arithmetic expression in Python, let us first know about the various operators used in the
arithmetic expressions.
Operator Syntax Working
+ x+y Addition or summation of x and y.
- x-y Subtraction of y from x.
X xxy Multiplication or product of x and y.
/ x/y Division of x and y.
// x // y Quotient when x is divided by y.
% x%y Remainder when x is divided by y.
** x ** y Exponent (x to the power of y).
Example :
x = 10y = 5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
print("The sum of x and y is: ", addition)print("The difference between x and y is: ",
subtraction)print("The product of x and y is: ", product)print("The division of x and y is: ",
division)print("x to the power y is: ", power)
Output :
The sum of x and y is: 15The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000

3. Integral Expressions:
An integral expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). An integral expression always produces an integer value as a resultant.
Example :
x = 10 # an integer numbery = 5.0 # a floating point number# we need to convert the floating-point number into
an integer or vice versa for summation.result = x + int(y)print("The sum of x and y is: ", result)
Output :
The sum of x and y is: 15

4. Floating Expressions:
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer numbery = 5.0 # a floating point number# we need to convert the integer
number into a floating-point number or vice versa for summation.result = float(x) + yprint("The sum
of x and y is: ", result)
Output :
The sum of x and y is: 15.0

5. Relational Expressions:
A relational expression in Python can be considered as a combination of two or more arithmetic
expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in
Python (>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10+15>2010+15>20
In this example, first, the arithmetic expressions (i.e. 10+1510+15 and 2020) are evaluated, and then
the results are used for further comparison.
Example :
a = 25b = 14c = 48d = 45# The expression checks if the sum of (a and b) is the same as the
difference of (c and d).result = (a + b) == (c - d)print("Type:", type(result))print("The result of the
expression is: ", result)
Output :
Type: <class 'bool'>The result of the expression is: False

6. Logical Expressions:
As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical expressions
in Python, let us discuss them briefly.
Operator Syntax Working
and x and y The expression return True if both x and y are true, else it returns False.
or x or y The expression return True if at least one of x or y is True.
not Not x The expression returns True if the condition of x is False.
Note :
In the table specified above, x and y can be values or another expression as well.
Example :
from operator import and_
x = (10 == 9) y = (7 > 5)
and_result = x and yor_result = x or ynot_x = not xprint("The result of x and y is: ",
and_result)print("The result of x or y is: ", or_result)print("The not of x is: ", not_x)
Output :
The result of x and y is: FalseThe result of x or y is: True
The not of x is: True

7. Bitwise Expressions:
The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.
Example :
x = 25left_shift = x << 1right_shift = x >> 1print("One right shift of x results: ",
right_shift)print("One left shift of x results: ", left_shift)
Output :
One right shift of x results: 12One left shift of x results: 50

8. Combinational Expressions:
As the name suggests, a combination expression can contain a single or multiple expressions which
result in an integer or boolean value depending upon the expressions involved.
Example :
x = 25y = 35result = x + (y << 1)print("Result obtained : ", result)
Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are resolved based on their
precedence or priority. Let us learn about the precedence of various operators in the following
section.
Multiple Operators in Expression (Operator Precedence) ?
The operator precedence is used to define the operator's priority i.e. which operator will be executed
first. The operator precedence is similar to the BODMAS rule that we learned in mathematics. Refer
to the list specified below for operator precedence.
Precedence Operator Name
1. ()[]{} Parenthesis
2. ** Exponentiation
3. -value , +value , ~value Unary plus or minus, complement
4. / * // % Multiply, Divide, Modulo
5. +– Addition & Subtraction
6. >> << Shift Operators
7. & Bitwise AND
8. ^ Bitwise XOR
9. pipe symbol Bitwise OR
10. >= <= > < Comparison Operators
11. == != Equality Operators
12. = += -= /= *= Assignment Operators
13. is, is not, in, not in Identity and membership operators
14. and, or, not Logical Operators
Let us take an example to understand the precedence better :
x = 12y = 14z = 16
result_1 = x + y * zprint("Result of 'x + y + z' is: ", result_1)
result_2 = (x + y) * zprint("Result of '(x + y) * z' is: ", result_2)
result_3 = x + (y * z)print("Result of 'x + (y * z)' is: ", result_3)
Output :
Result of 'x + y + z' is: 236Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236

Difference between Statements and Expressions in Python


We have earlier discussed statement expression in Python, let us learn the differences between them.
Statement in Python Expression in Python
A statement in Python is used for creating The expression in Python produces some value or result
variables or for displaying values. after being interpreted by the Python interpreter.
A statement in Python is not evaluated for
An expression in Python is evaluated for some results.
some results.
The execution of a statement changes the The expression evaluation does not result in any state
state of the variable. change.
A statement can be an expression. An expression is not a statement.
Example : �=3x=3. Example: �=3+6x=3+6.
Output : 33 Output : 99

TYPE CONVERSION IN PYTHON:


Type conversion is the transformation of a Py type of data into another type of data. Implicit type
translation and explicit type converter are the two basic categories of type conversion procedures in
Python.
Python has type conversion routines that allow for the direct translation of one data type to another.
This is helpful for both routine programming and competitive programming. This page aims to
enlighten readers about specific conversion functions.
In Python,

there are two kinds of type conversion:


 Explicit Type Conversion-The programmer must perform this task manually.
 Implicit Type Conversion-By the Python program automatically.

Implicit Type Conversion:


Implicit character data conversion is the term used in Python when a data type conversion occurs
whether during compilation or even during runtime.
We do not need to manually change the file format into some other type of data because Python
performs the implicit character data conversion.
Without user input, the Programming language automatically changes one data type to another in
implicit shift of data types.
x = 20
print("x type:",type(x)
y = 0.6
print("y type:",type(y))
a=x+y
print(a)
print("z type:",type(z))
Output:
x type: <class 'int'>
y type: <class 'float' >20.6
a type: <class 'float'>

✓ while one variable, x, is only of integer type and the other, y, is of float type, the data type of "z"
was automatically transformed to the "float" type.
✓ Due to type promotion, which enables operations by transforming raw data it in to a wider-sized
type of data without any information loss, the float value is instead not turned into an integer.
This is a straightforward instance of Python's Implicit type conversion.
✓ The result variable was changed into to the float dataset rather than the int data type since doing
so would have required the compiler to eliminate the fractional element, which would have
resulting in data loss. To prevent data loss, Python always translates smaller data types into
larger data types.
✓ We may lose the decimal portion of the report if the variable percentage's data type is integer.
Python automatically converts percentage data to float type, which can store decimal values, to
prevent this data loss.

Explicit Type Conversion:


✓ Let us say we want to change a number from a higher data type to a lower data type.
✓ Implicit type conversion is ineffective in this situation, as we observed in the previous section.
Explicit type conversion, commonly referred to as type casting, now steps in to save the day.
Using built-in Language functions like str() to convert to string form and int() to convert to
integer type, a programmer can explicitly change the data form of an object by changing it
manually.
✓ The user can explicitly alter the data type in Python's Explicit Type Conversion according to
their needs. Since we are compelled to change an expression into a certain data type when doing
express type conversion, there is chance of data loss. Here are several examples of explicit type
conversion.
o The function int(a, base) transforms any data type to an integer. If the type of data is a string,
"Base" defines the base wherein string is.
o float(): You can turn any data type into a floating-point number with this function.

# Python code to show type conversion


# Initializing string with int() and float()
a = "10010"
# # outputting string to int base 2 conversion.
b = int(a,2)
print ("following the conversion to integer base 2: ", end="")
print (r)
# printing a float after converting a string
d = float(a)
print ("After converting to float : ", end="")
print (d)
Output:
following the conversion to integer base 2: 18
After converting to float : 1010.0
3. The ord() method turns a character into an integer.
4. The hex() method turns an integer into a hexadecimal string.
5. The oct() method turns an integer into an octal string.

# Python code to show type conversion


# initialising integer
# using ord(), hex(), and oct()
a = '4'
# printing and converting a character to an integer
b = ord(a)
print ("After converting character into integer : ",end="")
print (b)
# printing integer converting to hexadecimal string
b = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (b)
# printing the integer converting into octal string
b = oct(56)
print ("After converting 56 into octal string : ",end="")
print (b)
Output:

After converting the character into integer : 52


After converting the 56 to hexadecimal string : 0x38
After converting the 56 into octal string : 0o70
6. The tuple() method is used to transform data into a tuple.
7. The set() function, which converts a type to a set, returns the set.
8. The list() function transforms any data type into a list type.

# Python code to show type conversion


# Initializing string with tuple(), set(), and list()
a = 'java'
# printing string into converting to tuple
b = tuple(a)
print ("After converting the string to tuple : ",end="")
print (b)
# printing string the converting to set
b = set(a)
print ("After converting the string to set : ",end="")
print (b)
# printing the string converting to list
b = list(a)
print ("After converting the string to list : ",end="")
print (b)
Output:

After converting the string to tuple : ('j', 'a', 'v', 'a')


After converting the string to set : {'j', 'a', 'v', 'a'}
After converting the string the to list : ['j', 'a', 'v', 'a']

PYTHON ARRAYS
The Array is a process of memory allocation. It is performed as a dynamic memory allocation. We
can declare an array like x[100], storing 100 data in x. It is a container that can hold a fixed number
of items, and these items should be the same type.
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.

The Array can be created in Python by importing the array module to the python program.
from array import *
arrayName = array(typecode, [initializers])
Accessing array elements
We can access the array elements using the respective indices of those elements.
Program code:
Here we give an example of how we access the elements of an array using its index value in Python.
The code is given below -
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])
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:
Now we compile the above code in python, and after successful compilation, we run it. Then the
output is given below -
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
Explanation:
In the above example, we have imported an array, defined a variable named "a" that holds the
elements of an array, and printed the elements by accessing elements through the indices of an array.
Here we can easily find out the array element by using the array index like a[0], a[1], a[-1], and so on.

◆ Access the Elements of an Array


You refer to an array element by referring to the index number.
Example
Get the value of the first array item:
x = cars[0]
◆ The Length of an Array
Use the len() method to return the length of an array (the number of elements in an array).
Example
Return the number of elements in the cars array:
x = len(cars)
◆ Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)

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

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

PART - A

1. Is Python case sensitive when dealing with identifiers?


a) yes
b) no
c) machine dependent
d) none of the mentioned
Explanation: Case is always significant while dealing with identifiers in python.

2. What is the maximum possible length of an identifier?


a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
Explanation: Identifiers can be of any length.

3. Which of the following is invalid?


a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned
Explanation: All the statements will execute successfully but at the cost of reduced readability.

4. Which of the following is an invalid variable?


a) my_string_1
b) 1st_string
c) foo
d) _
Explanation: Variable names should not start with a number.

5. Why are local variable names beginning with an underscore discouraged?


a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
Explanation: As Python has no concept of private variables, leading underscores are used to
indicate variables that must not be accessed from outside the class.

6. Which of the following commands will create a list?


a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned
Explanation: Execute in the shell to verify

7. What is the output when we execute list(“hello”)?


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
Explanation: Execute in the shell to verify.

8. To shuffle the list(say list1) what function do we use?


a) list1.shuffle()
b) shuffle(list1)
c) random.shuffle(list1)
d) random.shuffleList(list1)
Explanation: Execute in the shell to verify.

9. Which of the following functions is a built-in function in python?


a) seed()
b) sqrt()
c) factorial()
d) print()
Explanation: The function seed is a function which is present in the random module. The functions
sqrt and factorial are a part of the math module. The print function is a built-in function which
prints a value directly to the system output.

10. What will be the output of the following Python expression?


a) 4.5
b) 5
c) 4
d) 4.6

Explanation: This is a built-in function which rounds a number to give precision in decimal digits.
In the above case, since the number of decimal places has not been specified, the decimal number
is rounded off to a whole number. Hence the output will be 5.
11. Which of these in not a core data type?
a) Lists
b) Dictionary
c) Tuples
d) Class
Explanation: Class is a user defined data type.

12. Given a function that does not return any value, What value is thrown by default when
executed in shell.
a) int
b) bool
c) void
d) None
Explanation: Python shell throws a NoneType object back.

13. Which is the correct operator for power(xy)?


a) X^y
b) X**y
c) X^^y
d) None of the mentioned
Explanation: In python, power operator is x**y i.e. 2**3=8.

14. Which one of these is floor division?


a) /
b) //
c) %
d) None of the mentioned
Explanation: When both of the operands are integer then python chops out the fraction part and
gives you the round off value, to get the accurate answer use floor division. This is floor division.
For ex, 5/2 = 2.5 but both of the operands are integer so answer of this expression in python is 2.
To get the 2.5 answer, use floor division.

15. What is the answer to this expression, 22 % 3 is?


a) 7
b) 1
c) 0
d) 5
Explanation: Modulus operator gives the remainder. So, 22%3 gives the remainder, that is, 1.

16. Mathematical operations can be performed on a string.


a) True
b) False
Explanation: You can’t perform mathematical operation on string even if the string is in the form:
‘1234…’.

17. Operators with the same precedence are evaluated in which manner?
a) Left to Right
b) Right to Left
c) Can’t say
d) None of the mentioned
Explanation: None.

18. What is the output of this expression, 3*1**3?


a) 27
b) 9
c) 3
d) 1
Explanation: First this expression will solve 1**3 because exponential has higher precedence than
multiplication, so 1**3 = 1 and 3*1 = 3. Final answer is 3.
19. Which one of the following has the same precedence level?
a) Addition and Subtraction
b) Multiplication, Division and Addition
c) Multiplication, Division, Addition and Subtraction
d) Addition and Multiplication
Explanation: “Addition and Subtraction” are at the same precedence level. Similarly,
“Multiplication and Division” are at the same precedence level. However, Multiplication and
Division operators are at a higher precedence level than Addition and Subtraction operators.

20. What will be the output of the following Python code?

>>>example = "snow world"


>>>print("%s" % example[4:7])

a) wo
b) world
c) sn
d) rl
Explanation: Execute in the shell and verify.

21. Which of these about a set is not true?


a) Mutable data type
b) Does not allow duplicate values
c) Data type with unordered values
d) Immutable data type
Explanation: A set is a mutable data type with non-duplicate, unordered values, providing the usual
mathematical set operations.

22. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
Explanation: The argument given for the set must be an iterable

23. Which of the following statements is used to create an empty set?


a) { }
b) set()
c) [ ]
d) ( )
Explanation: { } creates a dictionary not a set. Only set() creates an empty set.

24. What will be the output of the following Python code?

>>> a={5,4}>>> b={1,2,4,5}>>> a<b


a) {1,2}
b) True
c) False
d) Invalid operation
Explanation: a<b returns True if a is a proper subset of b.

25. If a={5,6,7,8}, which of the following statements is false?


a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
Explanation: The members of a set can be accessed by their index values since the elements of the
set are unordered.

PART - B (5 MARK)

1. Define variable and explain its types?


2. Differentiate between Statement and Expressions.
3. What are all the Keywords available in python.
4. What is comments and explain it.
5. Define python data types.
6. Explain Array and its Method.
7. Explain about Collection topic.
PART - C (10 MARK)

1. Briefly explain Python literal and types of literal.


2. What are all the Expressions we used in python. Explain it.
3. i. Types of conversion
ii. Explain about Indentation operators.

….……………………………………..UNIT 1 COMPLETED………….…………………………..
UNIT II
Control Statements:

Selection/Conditional Branching statements:


if, ifelse, 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.

Control Statements
• Control statements in python are used to control the order of execution of the program based on
the values and logic.
• Loops are employed in Python to iterate over a section of code continually.
• Control statements are designed to serve the purpose of modifying a loop's execution from its
default behaviors.
• Based on a condition, control statements are applied to alter how the loop executes.

Conditional Statements
A conditional statement as the name suggests itself, is used to handle conditions in program. These
statements guide the program while making decisions based on the conditions encountered by the
program.
Like every other programming language, Python also has some predefined conditional statements.
These statements guide the program while making decisions based on the conditions encountered
by the program.
Python has 4 key Conditional Statements that you should know:
1. if statement
2. if-else statement
3. Nested if
4. if-elif-else ladder

if Statement
• if – It help us to run a particular code, but only when a certain condition is met or satisfied.
A if only has one condition to check.
• Meaning if the program finds the condition defined in the if statement to be true, it will go ahead
and execute the code block inside the if statement.
Syntax:
if condition:
# execute code block

Example:
# list of numbers
list_of_numbers = [2,4,6,9,5]
# for loop to iterate through the list and check each elements of the list
for i in list_of_numbers:
# check if no. is odd
if i % 2 != 0:
# if condition is True print "odd"
print (i, "is an odd number")
# check if no. is even
if i % 2 == 0:
# if condition is false print "even"
print (i, "is an even number")

Output:

Home Task : Program to print the largest of the three numbers.


if-else Statement
The if statement executes the code block when the condition is true. Similarly, the else statement works
in conjuncture with the if statement to execute a code block when the defined if condition is false.

SYNTAX:

Python Example: Python program to check if a number is odd or even.


# list of numbers
list_of_numbers = [2,4,6,9,5]

# for loop to iterate through the list and check each element of the list
for i in list_of_numbers:

# check if no. is odd


if i%2 != 0:

# if condition is True print "odd"


print(i, "is an odd number")

# if the no. is not odd then the no. is even therfore print "even"
else:

# if condition is True print "even"


print(i, "is an even number")
Output:

if-elif-else ladder
• The elif statement is used to check for multiple conditions and execute the code block
within if any of the conditions evaluate to be true.
• The elif statement is similar to the else statement in the context that it is optional but unlike
the else statement, there can be multiple elif statements in a code block following
an if statement.

Syntax:

Python Example: Python program to check if a string matches the condition.


# take a sample string
string ="ShikshaOnline"
# check if value in the string variable
# matches "Shik"
if string == "Shik":
print ("The first condition is true")

# check if value in the string variable


# matches "Shiksha"
elif string == "Shiksha":
print("The second condition is true")

# check if value in the string variable


# matches "Online"
elif string == "Online":
print("The third condition is true")

# check if value in the string variable


# matches "ShikshaOnline"
elif string=="ShikshaOnline":
print("The fourth condition is true")

# if none of the above


# conditions evaluate to true
# execute the code inside the else block
else:
print ("All the above conditions are false")

Output:

The fourth condition is true

Nested if Statements:

A nested if statement is considered as if within another if statement(s). These are generally


used to check for multiple conditions.

if condition1:
if condition2:
# execute code if both condition1and
condition2 are True

Example: Python program to check if a number is odd and divisible by 3.

# list of numbers
list_of_numbers = [4,5,9,17,21]

# for loop to iterate through the list and check each element of the list
for i in list_of_numbers:
# condition1: check if no. is odd
# if yes execute the code block inside the first if statement
if i%2!=0:

# condition2: check if no. is also divisible by 3.


if i%3==0:

# if condition2 is true
# execute the below code block
print (i,"is an odd number & divisible by 3")

# if codition2 if False
# execute the below code block

else:
print (i, "is an odd number but not divisible by 3")

# if condition1 is False
# execute the below code block
else:
print(i,"is an even number")

Output:

Loops in Python
Python programming language provides the following types of loops to handle looping
requirements. 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.
There are 2 types of Loops in Python.
1. While loop
2. For loop
While Loop in Python
In python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately after the
loop in the program is executed.
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:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
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:

Example:
# Python program to illustrate
# combining else with while
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
Infinite While Loop in Python
If we want a block of code to execute infinite number of time, we can use the while loop in
Python to do so.
# Python program to illustrate
# Single statement while block
count = 0
while (count == 0):
print("Hello Geek")
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 for each loop in other languages. Let us
learn how to use for in loop for sequential traversals. It can be used to iterate over a range
and iterators.

# Python program to illustrate


# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
Output
0
1
2
3
Example with List, Tuple, string, and dictionary iteration using For Loops in Python
We can use for loop to iterate lists, tuples, strings and dictionaries in Python.
# Python program to illustrate
# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s:
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("%s %d" % (i, d[i]))

# Iterating over a set


print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Output
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345

Set Iteration
1
2
3
4
5
6
Iterating by the index of sequences
We can also use the index of elements in the sequence to iterate. The key idea is to first
calculate the length of the list and in iterate over the sequence within the range of this
length. See the below example:
# Python program to illustrate
# Iterating by index

list = ["geeks", "for", "geeks"]


for index in range(len(list)):
print(list[index])
Output
geeks
for
geeks
Using else statement with for loop in Python
We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block will be
executed immediately after for block finishes execution.
# Python program to illustrate
# combining else with for

list = ["geeks", "for", "geeks"]


for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
Output
geeks
for
geeks
Inside Else Block
Nested Loops
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.

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

A final note on loop nesting is that we can put any type of loop inside of any other type of
loop. For example, a for loop can be inside a while loop or vice versa.
# Python program to illustrate
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
2 2
3 3 3
4 4 4 4
JUMP STATMENTS
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
• Break Statement
• Pass Statement
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'
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.
for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'


# or 's'
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.
# An empty loop
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output
Last Letter : s
PART A

1. Which of the following is not used as loop in Python?

A. for loop
B. while loop
C. do-while loop
D. None of the above
View Answer
Ans : C

Explanation: do-while loop is not used as loop in Python.


2. Which of the following is False regarding loops in Python?

A. Loops are used to perform certain tasks repeatedly.


B. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes False
C. While loop is used when multiple statements are to executed repeatedly until the given
condition becomes True.
D. for loop can be used to iterate through the elements of lists.
View Answer
Ans : B

Explanation: While loop is used when multiple statements are to executed repeatedly until the
given condition becomes False statement is False regarding loops in Python.

3. Which of the following is True regarding loops in Python?

A. Loops should be ended with keyword "end".


B. No loop can be used to iterate through the elements of strings.
C. Keyword "break" can be used to bring control out of the current loop.
D. Keyword "continue" is used to continue with the remaining statements inside the loop.
View Answer
Ans : C

Explanation: Keyword break can be used to bring control out of the current loop statement is
True regarding loops in Python.
4. What will be the output of given Python code?

n=7

c=0

while(n):

if(n>5):

c=c+n-1

n=n-1

else:

break
print(n)

print(c)

A. 5 11
B. 5 9
C. 7 11
D. 5 2
View Answer
Ans : A

Explanation: 5 11 will be the output of the given code

5. What will be the output of given Python code?

str1="hello"

c=0

for x in str1:

if(x!="l"):

c=c+1

else:

pass

print(c)

A. 2
B. 0
C. 4
D. 3
View Answer
Ans : D

Explanation: 3 will be the output of given Python code.


6. Which of the following Python code will give different output from the others?

A. for i in range(0,5):
print(i)
B. for j in [0,1,2,3,4]:
print(j)
C. for k in [0,1,2,3,4,5]:
print(k)
D. for l in range(0,5,1):
print(l)
View Answer
Ans : C

Explanation: Option C python code will give different output from the others.

7. How many times will the loop run?

i=2

while(i>0):

i=i-1

A. 2
B. 3
C. 1
D. 0
View Answer
Ans : A

Explanation: The loop will run 2 times.

8. What will be the output of the following Python code?

list1 = [3 , 2 , 5 , 6 , 0 , 7, 9]

sum = 0

sum1 = 0

for elem in list1:

if (elem % 2 == 0):

sum = sum + elem

continue

if (elem % 3 == 0):

sum1 = sum1 + elem

print(sum , end=" ")


print(sum1)

A. 8 9
B. 8 3
C. 2 3
D. 8 12
View Answer
Ans : D

Explanation: The output of the following python code is 8 12.

9. What will be the output of the following Python code?

str1="learn python"

str2=""

str3=""

for x in str1:

if(x=="r" or x=="n" or x=="p"):

str2+=x

pass

if(x=="r" or x=="e" or x=="a"):

str3+=x

print(str2,end=" ")

print(str3)

A. rnpn ea
B. rnpn ear
C. rnp ea
D. rnp ear
View Answer
Ans : B

Explanation: The output of the following python code is rnpn ear.

10. What will be the output of the following Python code?

for i in range(0,2,-1):
print("Hello")

A. Hello
B. Hello Hello
C. No Output
D. Error
View Answer
Ans : C

Explanation: There will be no output of the following python code.

11. Which one of the following is a valid Python if statement :

A. if a>=2 :
B. if (a >= 2)
C. if (a => 22)
D. if a >= 22
View Answer

12. What keyword would you use to add an alternative condition to an if statement?

A. else if
B. elseif
C. elif
D. None of the above
View Answer
Ans : C

Explanation: elif is used to add an alternative condition to an if statement. So, option C is


correct.

13. Can we write if/else into one line in python?

A. Yes
B. No
C. if/else not used in python
D. None of the above
View Answer
Ans : A

Explanation: Yes, we can write if/else in one line. For eg i = 5 if a > 7 else 0. So, option A is
correct.
14. In a Python program, a control structure:

A. Defines program-specific data structures


B. Directs the order of execution of the statements in the program
C. Dictates what happens before the program starts and after it terminates
D. None of the above
View Answer
Ans : B

Explanation: Control structures determine which statements in the program will be executed
and in what order, allowing for statements to be skipped over or executed repeatedly. So,
option B is correct.
15. What will be output of this expression:
'p' + 'q' if '12'.isdigit() else 'r' + 's'
A. pq
B. rs
C. pqrs
D. pq12
View Answer
Ans : A

Explanation: If condition is true so pq will be the output. So, option A is correct.

16. Which statement will check if a is equal to b?

A. if a = b:
B. if a == b:
C. if a === c:
D. if a == b
View Answer
Ans : B

Explanation: if a == b: statement will check if a is equal to b. So, option B is correct.

17. Does python have switch case statement?

A. True
B. False
C. Python has switch statement but we can not use it.
D. None of the above
View Answer
Ans : B

Explanation: Python does not have switch case statement. So, option B is correct.

18. Which of the following is a valid for loop in Python?

A. for(i=0; i < n; i++)


B. for i in range(0,5):
C. for i in range(0,5)
D. for i in range(5)
View Answer
Ans : B

Explanation: For statment always ended with colon (:). So, option B is correct.

19. Which of the following sequences would be generated bt the given line of code?

range (5, 0, -2)

A. 5 4 3 2 1 0 -1
B. 5 4 3 2 1 0
C. 5 3 1
D. None of the above
View Answer
Ans : C

Explanation: The initial value is 5 which is decreased by 2 till 0 so we get 5, then 2 is decreased
so we get 3 then the same thing repeated we get 1 and now when 2 is decreased we get -1
which is less than 0 so we stop and hence we get 5 3 1. So, option C is correct.

20. A while loop in Python is used for what type of iteration?

A. indefinite
B. discriminant
C. definite
D. indeterminate
View Answer
Ans : A

Explanation: A while loop implements indefinite iteration, where the number of times the loop
will be executed is not specified explicitly in advance. So, option A is correct.

21. When does the else statement written after loop executes?

A. When break statement is executed in the loop


B. When loop condition becomes false
C. Else statement is always executed
D. None of the above
View Answer
Ans : B

Explanation: Else statement after loop will be executed only when the loop condition becomes
false. So, option B is correct.
22. What will be the output of the following code?

x = "abcdef"
i = "i"

while i in x:

print(i, end=" ")


A. a b c d e f
B. abcdef
C. i i i i i.....
D. No Output
View Answer
Ans : D

Explanation: There will be no output since there is no i in the string x. So, option D is correct.

23. What will be the output of the following code?

x = "abcd"

for i in range(len(x)):

print(i)
A. abcd
B. 0 1 2 3
C. 1 2 3 4
D. a b c d
View Answer
Ans : B

Explanation: len(x) will give 4 and the loop will run for 4 times starting from 0. Hence output
will be 0 1 2 3. So, option B is correct.

24. What will be the output of the following code?

x = 12

for i in x:

print(i)

A. 12
B. 1 2
C. Error
D. None of the above
View Answer
Ans : C

Explanation: Objects of type int are not iterable. So, option C is correct.
25. A loop becomes infinite loop if a condition never becomes ________.

A. TRUE
B. FALSE
C. Null
D. Both A and C
View Answer
Ans : B

Explanation: A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to
a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

26. If the else statement is used with a while loop, the else statement is executed when the
condition becomes _______.

A. TRUE
B. FALSE
C. Infinite
D. Null
View Answer
Ans : B

Explanation: If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.

27. Python programming language allows to use one loop inside another loop known as?

A. switch
B. foreach
C. nested
D. forall
View Answer
Ans : C

Explanation: Python nested loops : Python programming language allows to use one loop
inside another loop.

28. The ________ statement is a null operation.

A. break
B. exit
C. return
D. pass
View Answer
Ans : D

Explanation: The pass statement is a null operation; nothing happens when it executes.
29. The continue statement can be used in?

A. while loop
B. for loop
C. do-while
D. Both A and B
View Answer
Ans : D

Explanation: The continue statement can be used in both while and for loops.
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.

PYTHON FUCTIONS

Fundamentals of Python functions, including what they are, their syntax, their primary parts,
return keywords, and significant types. We'll also look at some examples of Python function
definitions.

What are Python Functions?

A collection of related assertions that carry out a mathematical, analytical, or evaluative


operation is known as a function. An assortment of proclamations called Python Capabilities
returns the specific errand. Python functions are necessary for intermediate-level
programming and are easy to define. Function names meet the same standards as variable
names do. The objective is to define a function and group-specific frequently performed
actions. Instead of repeatedly creating the same code block for various input variables, we
can call the function and reuse the code it contains with different variables.

Client-characterized and worked-in capabilities are the two primary classes of capabilities in
Python. It aids in maintaining the program's uniqueness, conciseness, and structure.

Advantages of Python Functions

Pause We can stop a program from repeatedly using the same code block by including
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.

However, calling functions has always been overhead in a Python program.

Syntax

1. # An example Python Function


2. def function_name( parameters ):
3. # code block

The accompanying components make up to characterize a capability, as seen previously.


o The start of a capability header is shown by a catchphrase called def.
o function_name is the function's name, which we can use to distinguish it from other
functions. We will utilize this name to call the capability later in the program. Name
functions in Python must adhere to the same guidelines as naming variables.
o Using parameters, we provide the defined function with arguments. Notwithstanding,
they are discretionary.
o A colon (:) marks the function header's end.
o We can utilize a documentation string called docstring in the short structure to make
sense of the reason for the capability.
o Several valid Python statements make up the function's body. The entire code block's
indentation depth-typically four spaces-must be the same.
o A return expression can get a value from a defined function.

Illustration of a User-Defined Function

We will define a function that returns the argument number's square when called.

1. # Example Python Code for User-Defined function


2. def square( num ):
3. """
4. This function computes the square of the number.
5. """
6. return num**2
7. object_ = square(6)
8. print( "The square of the given number is: ", object_ )

Output:

The square of the given number is: 36


Calling a Function

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.

1. # Example Python Code for calling a function


2. # Defining a function
3. def a_function( string ):
4. "This prints the value of length of string"
5. return len(string)
6.
7. # Calling the function we defined
8. print( "Length of the string Functions is: ", a_function( "Functions" ) )
9. print( "Length of the string Python is: ", a_function( "Python" ) )
Output:

Length of the string Functions is: 9


Length of the string Python is: 6

Function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result. function is a block of code
which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Features of Functions

Following are the features of Python Functions:

1. It is used to avoid repetitions of code.


2. Using the function, we can divide a group of code into smaller modules.
3. It helps to hide the code and create clarity to understand the modules.
4. It allows code to be reusable, thus saving memory.
5. Statements written inside a function can only be executed with a function name.
6. Python function starts with def and then a colon (:) followed by the function name.

Rules for defining a function


1. The def keyword is used in the Python function to declare and define a function.
2. The function name must begin with the following identifiers such as: A-Z, a- z, and
underscore (_).
3. Every function must follow colon (:) and then indention to write the program.
4. In a Python function, the reserved word cannot be used as a function name or
identifier.
5. In Python, the function parameter can be empty or multiples.

Create a function in Python

To create a function, we need to use a def keyword to declare or write a function in Python.
Here is the syntax for creating a function:

Syntax

def function_name(): # use def keyword to define the function


Statement to be executed
return statement # return a single value.

Let's create a function program in Python.

Myfun.py
1. def myFun(): # define function name
2. print(" Welcome to JavaTpoint")
3. myFun() # call to print the statement

Output:

Welcome to JavaTpoint
Creating a Function

In Python a function is defined using the def keyword:

ExampleGet your own Python Server


def my_function():
print("Hello from a function")
Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()
Function Calling in Python

Once a function is created in Python, we can call it by writing function_name() itself or


another function/ nested function. Following is the syntax for calling a function.

Syntax:

1. def function_name():
2. Statement1
3. function_name() # directly call the function
4.
5. # calling function using built-in function
6. def function_name():
7. str = function_name('john') # assign the function to call the function
8. print(str) # print the statement

Consider the following example to print the Welcome Message using a function in Python.

CallFun.py

1. def MyFun():
2. print("Hello World")
3. print(" Welcome to the JavaTpoint")
4.
5. MyFun() # Call Function to print the message.

Output:

Hello World
Welcome to the JavaTpoint

In the above example, we call the MyFun() function that prints the statements

VARIABLE SCOPE AND ITS LIFETIME

The scope of variable is a region of the program where a variable is visible or


accessible. Lifetime of a variable is the duration for which a variable exists in the memory.
The existence and accessibility depend on the declaration of a variable in the program.

The scope of variable is a region of the program where a variable is visible or accessible.
Lifetime of a variable is the duration for which a variable exists in the memory. The existence
and accessibility depend on the declaration of a variable in the program.

For example, the lifetime of a variable declared inside a function is as long as the function is
alive. When the execution of function body is finished, then the variable defined inside a
function will destroy.

Types of Scope of Variables in Python

There are two basic types of scope of variables in Python. They are:
• Global scope
• Local scope
Let’s understand each type of variable scope with the help of examples.

Global Scope in Python

When we define a variable inside the main program but outside the function body, then it has
a global scope. The variable declared in the main body of the program or file is a global
variable.
In the global scope, the global variable will be visible throughout the program or file, and
also inside any file which imports that file. We can easily access a variable defined in global
scope from all kinds of functions and blocks.
Let’s take some important example programs based on the global scope in Python.
Example 2:
Let’s write a program in Python in which we will define a global variable and access it from
both inside the function and main program body.
# Declaring a global variable in the global scope.
x = 50

# Declare a simple function that prints the value of x.

def showMe():

print('Value of x from local scope = ',x) # calling variable x inside the function.

# Main program.

showMe() # calling function.

print('Value of x from global scope = ',x)

Output:

Value of x from local scope = 50

Value of x from global scope = 50

In this example, variable x is a global variable. We have accessed it from both inside the
function and outside the function because it has a global scope.

Local Scope

A variable defined or created inside a function body or a block has a local scope. We can
access it only within the declared function or block and not from outside that function or
block.
As the execution of function body or block is finished, Python destroys the local variable
from the memory. In other words, local variable exists in the memory as long as the function
is executing.
Consider the following example code below in which we will define a local variable within in
a function and we will access it inside a function and from outside the function.
Example 3:
def my_funct():

msg = 'Good morning!' # local variable with local scope.

print(msg) # accessing local variable from inside the function.

my_funct()
print(msg) # accessing local variable from outside the function.

Output:

Good morning!
print(msg) # accessing local variable from outside the function.
NameError: name 'msg' is not defined

RETURN STATEMENT
The return Statement
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as
follows −
#!/usr/bin/python

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30

The return statement in python is an extremely useful statement used to return the flow of
program from the function to the function caller. The keyword return is used to write the
return statement.
Since everything in python is an object the return value can be any object such as – numeric
(int, float, double) or collections (list, tuple, dictionary) or user defined functions and classes
or packages.
The return statement has the following features -
• Return statement cannot be used outside the function.
• Any code written after return statement is called dead code as it will never be
executed.
• Return statement can pass any value implicitly or explicitly, if no value is given then
None is returned.
Syntax
Following is the syntax of return statement in python -
def some_function(parameters):
return <expression>
print(some_function)
Example
Following is the simple example of return statement -
def welcome(str):
return str + " from TutorialsPoint"
print(welcome("Good morning"))
Output
Following is an output of the above code
The return statement is useful in multiple ways and the below sections discuss the different
use case of return statement along with examples.
Use of return statement in Python
Functions are core of any programming language as they allow for code modularity thereby
reducing program complexity. Functions can display the result within itself, but it makes the
program complex, hence it is best to pass the result from all the functions to a common
place.
It is in this scenario that the return statement is useful as it terminates the currently executing
function and passes control of the program to the statement that invoked the function.
Example
In the below code the sum_fibonacci function is used to calculate the sum of the first 15
terms in the fibonacci series. After calculating the sum, it prints and returns the sum to the
sum_result variable. This is to show that printing inside the function and returning the value
give the same output.
# Defining function to calculate sum of Fibonacci series
def sum_fibonacci(terms):
first_term = 0
second_term = 1
sum_series = 0
# Finding the sum of first 15 terms of Fibonacci series
for i in range(0, terms):
sum_series = sum_series + first_term
next_term = first_term + second_term
first_term = second_term
second_term = next_term
# Printing the sum inside the function
print("Sum of Fibonacci series inside the function is = {}".format(sum_series))

# Returning the sum using return statement


return sum_series

# Invoking the sum_fibonacci function


sum_result = sum_fibonacci(15)
print("Sum of Fibonacci series outside the function is = {}".format(sum_result))
Output
The output shows that the sum from inside the function using print statement and the sum
from outside the function using return statement is equal.
Sum of Fibonacci series inside the function is = 986
Sum of Fibonacci series outside the function is = 986

Function Arguments
You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
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 −
Live Demo

#!/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()
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)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
Live Demo

#!/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( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not
matter.
Live Demo

#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed −
Live Demo

#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
Live Demo

#!/usr/bin/python

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
The Anonymous Functions
These functions are called anonymous because they are not declared in the standard manner
by using the def keyword. You can use the lambda keyword to create small anonymous
functions.
• Lambda forms can take any number of arguments but return just one value in the form
of an expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an
expression
• Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function
stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo

#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
Recursion
Recursion allows a function to call itself. Fixed steps of code get executed again and again
for new values. We also have to set criteria for deciding when the recursive call ends. In the
below example we see a recursive approach to the binary search. We take a sorted list and
give its index range as input to the recursive function.
Binary Search using Recursion
We implement the algorithm of binary search using python as shown below. We use an
ordered list of items and design a recursive function to take in the list along with starting and
ending index as input. Then, the binary search function calls itself till find the searched item
or concludes about its absence in the list.
Example
def bsearch(list, idx0, idxn, val):
if (idxn < idx0):
return None
else:
midval = idx0 + ((idxn - idx0) // 2)
# Compare the search item with middle most value
if list[midval] > val:
return bsearch(list, idx0, midval-1,val)
else if list[midval] < val:
return bsearch(list, midval+1, idxn, val)
else:
return midval
list = [8,11,24,56,88,131]
print(bsearch(list, 0, 5, 24))
print(bsearch(list, 0, 5, 51))
Output
When the above code is executed, it produces the following result −
2
None

Python string

Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string. Consider the following example in Python to create a string.
Syntax:
1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script

1. print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)
13. Output:
14. Hello Python
15. Hello Python
16. Triple quotes are generally used for
17. represent the multiline or
18. docstring
Strings indexing and splitting

Like other languages, the indexing of the Python strings starts from 0. For example,
The string "HELLO" is indexed as given in the below figure.

The string "HELLO" is indexed as given in the below figure.


Consider the following example:
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range
String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given


either side of the operator.

* It is known as repetition operator. It concatenates the multiple copies


of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a


particular string.
[:] It is known as range slice operator. It is used to access the characters
from the specified range.

in It is known as membership operator. It returns if a particular sub-


string is present in the specified string.

not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified
string.

r/R It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such
as "C://python". To define any string as a raw string, the character r or
R is followed by the string.

% It is used to perform string formatting. It makes use of the format


specifiers used in C programming like %d or %f to map their values
in python. We will discuss how formatting is done in python.

Example

Consider the following example to understand the real use of Python operators.

1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
IMMUTABLE

the string data types are immutable. Which means a string value cannot be updated. We can
verify this by trying to update a part of the string which will led us to an error.
# Can not reassign
t= "Tutorialspoint"
print type(t)
t[0] = "M"
When we run the above program, we get the following output −

t[0] = "M"
TypeError: 'str' object does not support item assignment
We can further verify this by checking the memory location address of the position of the
letters of the string.
.
x = 'banana'

for idx in range (0,5):


print x[idx], "=", id(x[idx])
When we run the above program we get the following output. As you can see above a and a
point to same location. Also N and N also point to the same location.
b = 91909376
a = 91836864
n = 91259888
a = 91836864
n = 91259888
What are Immutable Data Types?

Immutable refers to a state in which no change can occur over time. A Python object is
referred to as immutable if we cannot change its value over time. The value of these Python
objects is fixed once they are made.

List of Mutable and Immutable objects

Python mutable data types:

Example of Immutable Python Objects


int

Since int in Python is an immutable data type, we cannot change or update it.

As we previously learned, immutable objects shift their memory address whenever they are
updated.

Here is an illustration of that:


Code

1. # Python program to show that int is an immutable data type


2.
3. int_ = 25
4. print('The memory address of int before updating: ', id(int_))
5.
6. # Modifying an int object by giving a new value to it
7. int_ = 35
8. print('The memory address of int after updating: ', id(int_))

Output:

The memory address of int before updating: 11531680


The memory address of int after updating: 11532000
float

Since the float object in Python is an immutable data type, we cannot alter or update it. As we
previously learned, immutable objects shift their memory address whenever they are updated.

Here is an illustration of that:

Code

1. # Python program to show that float is an immutable data type


2.
3. float_ = float(34.5)
4. print('The memory address of float before updating: ', id(float_))
5.
6. # Modifying the float object by giving a new value to it
7. float_ = float(32.5)
8. print('The memory address of float after updating: ', id(float_))

Output:

The memory address of float before updating: 139992739659504


The memory address of float after updating: 139992740128048
String

Since strings in Python are immutable data structures, we cannot add or edit any data. We
encountered warnings stating that strings are not changeable when modifying any section of
the string.

Here is an illustration of that:

Code

1. # Python program to show that a string is an immutable data type


2.
3. # Creating a string object
4. string = 'hello peeps'
5.
6. # Trying to modify the string object
7. string[0] = 'X'
8. print(string)

Output:

TypeError Traceback (most recent call last)


<ipython-input-3-4e0fff91061f> in <module>
3 string = 'hello peeps'
4
----> 5 string[0] = 'X'
6
7 print(string)

TypeError: 'str' object does not support item assignment


Tuple

Because tuples in Python are immutable by nature, we are unable to add or modify any of
their contents. Here is an illustration of that:

Code

1. # Python program to show that a tuple is an immutable data type


2.
3. # Creating a tuple object
4. tuple_ = (2, 3, 4, 5)
5.
6. # Trying to modify the tuple object
7. tuple_[0] = 'X'
8. print(tulple_)

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-e011ebc4971e> in <module>
5
6 # Trying to modify the tuple object
----> 7 tuple_[0] = 'X'
8 print(tulple_)
9

TypeError: 'tuple' object does not support item assignment


Built-in String Methods in Python

Python includes the following built-in methods to manipulate strings −

Sr.No Function & Description

1 capitalize()Capitalizes first letter of string

2 center(width, fillchar)Returns a space-padded string with the original string


centered to a total of width columns.

3 count(str, beg= 0,end=len(string))Counts how many times str occurs in string or in


a substring of string if starting index beg and ending index end are given.

4 decode(encoding='UTF-8',errors='strict')Decodes the string using the codec


registered for encoding. encoding defaults to the default string encoding.

5 encode(encoding='UTF-8',errors='strict')Returns encoded string version of string;


on error, default is to raise a ValueError unless errors is given with 'ignore' or
'replace'.

6 endswith(suffix, beg=0, end=len(string))Determines if string or a substring of


string (if starting index beg and ending index end are given) ends with suffix;
returns true if so and false otherwise.

7 expandtabs(tabsize=8)Expands tabs in string to multiple spaces; defaults to 8


spaces per tab if tabsize not provided.

8 find(str, beg=0 end=len(string))Determine if str occurs in string or in a substring of


string if starting index beg and ending index end are given returns index if found
and -1 otherwise.

9 index(str, beg=0, end=len(string))Same as find(), but raises an exception if str not


found.

10 isalnum()Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

11 isalpha()Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Sr.No Function & Description

12 isdigit()Returns true if string contains only digits and false otherwise.

13 islower()Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.

14 isnumeric()Returns true if a unicode string contains only numeric characters and


false otherwise.

15 isspace()Returns true if string contains only whitespace characters and false


otherwise.

16 istitle()

compare strings in Python using the equality (==) and comparison (<, >, !=, <=, >=)
operators. There are no special methods to compare two strings. In this article, you’ll learn
how each of the operators work when comparing strings.

Python string comparison compares the characters in both strings one by one. When different
characters are found, then their Unicode code point values are compared. The character with
the lower Unicode value is considered to be smaller.

Python Equality and Comparison Operators

Declare the string variable:

fruit1 = 'Apple'
Copy
The following table shows the results of comparing identical strings (Apple to Apple) using
different operators.

Operator Code Output

Equality print(fruit1 == 'Apple') True

Not equal to print(fruit1 != 'Apple') False

Less than print(fruit1 < 'Apple') False


Operator Code Output

Greater than print(fruit1 > 'Apple') False

Less than or equal to print(fruit1 <= 'Apple') True

Greater than or equal to print(fruit1 >= 'Apple') True

Both the strings are exactly the same. In other words, they’re equal. The equality operator and
the other equal to operators return True.

If you compare strings of different values, then you get the exact opposite output.

If you compare strings that contain the same substring, such as Apple and ApplePie, then the
longer string is considered larger.
Comparing User Input to Evaluate Equality Using Operators

This example code takes and compares input from the user. Then the program uses the results
of the comparison to print additional information about the alphabetical order of the input
strings. In this case, the program assumes that the smaller string comes before the larger
string.

fruit1 = input('Enter the name of the first fruit:\n')


fruit2 = input('Enter the name of the second fruit:\n')

if fruit1 < fruit2:


print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
elif fruit1 > fruit2:
print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
else:
print(fruit1 + " and " + fruit2 + " are the same.")
Copy

Here’s an example of the potential output when you enter different values:

Output
Enter the name of first fruit:
Apple
Enter the name of second fruit:
Banana
Apple comes before Banana in the dictionary.

Here’s an example of the potential output when you enter identical strings:

Output
Enter the name of first fruit:
Orange
Enter the name of second fruit:
Orange
Orange and Orange are the same.
Python Modules

In this tutorial, we will explain how to construct and import custom Python modules.
Additionally, we may import or integrate Python's built-in modules via various methods.

What is Modular Programming?

Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.

Modularizing our code in a big application has a lot of benefits.

Simplification: A module often concentrates on one comparatively small area of the overall
problem instead of the full task. We will have a more manageable design problem to think
about if we are only concentrating on one module. Program development is now simpler and
much less vulnerable to mistakes.

Flexibility: Modules are frequently used to establish conceptual separations between various
problem areas. It is less likely that changes to one module would influence other portions of
the program if modules are constructed in a fashion that reduces interconnectedness. (We
might even be capable of editing a module despite being familiar with the program beyond
it.) It increases the likelihood that a group of numerous developers will be able to collaborate
on a big project.

Reusability: Functions created in a particular module may be readily accessed by different


sections of the assignment (through a suitably established api). As a result, duplicate code is
no longer necessary.

Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.

In Python, modularization of the code is encouraged through the use of functions, modules,
and packages.

What are Modules in Python?

A document with definitions of functions and various statements written in Python is called a
Python module.

In Python, we can define a module in one of 3 ways:

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
o A built-in module, such as the itertools module, is inherently included in the
interpreter.

A module is a file containing Python code, definitions of functions, statements, or classes. An


example_module.py file is a module we will create and whose name is example_module.

We employ modules to divide complicated programs into smaller, more understandable


pieces. Modules also allow for the reuse of code.

Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.

Let's construct a module. Save the file as example_module.py after entering the following.

Example:

1. # Here, we are creating a simple Python program to show how to create a module.
2. # defining a function in the module to reuse it
3. def square( number ):
4. # here, the above function will square the number passed as the input
5. result = number ** 2
6. return result # here, we are returning the result of the function

Here, a module called example_module contains the definition of the function square(). The
function returns the square of a given number.

How to Import Modules in Python?

In Python, we may import functions from one module into our program, or as we say into,
another module.

For this, we make use of the import Python keyword. In the Python window, we add the next
to import keyword, the name of the module we need to import. We will import the module
we defined earlier example_module.

Syntax:

1. import example_module

The functions that we defined in the example_module are not immediately imported into the
present program. Only the name of the module, i.e., example_ module, is imported here.

We may use the dot operator to use the functions using the module name. For instance:

Example:

1. # here, we are calling the module square method and passing the value 4
2. result = example_module.square( 4 )
3. print("By using the module square of number is: ", result )
Output:

By using the module square of number is: 16

There are several standard modules for Python. The complete list of Python standard modules
is available. The list can be seen using the help command.

Similar to how we imported our module, a user-defined module, we can use an import
statement to import other standard modules.

Importing a module can be done in a variety of ways. Below is a list of them.

Python import Statement

Using the import Python keyword and the dot operator, we may import a standard module
and can access the defined functions within it. Here's an illustration.

Code

1. # Here, we are creating a simple Python program to show how to import a standard m
odule
2. # Here, we are import the math module which is a standard module
3. import math
4. print( "The value of euler's number is", math.e )
5. # here, we are printing the euler's number from the math module

Output:

The value of euler's number is 2.718281828459045


Importing and also Renaming

While importing a module, we can change its name too. Here is an example to show.

Code

1. # Here, we are creating a simple Python program to show how to import a module and
rename it
2. # Here, we are import the math module and give a different name to it
3. import math as mt # here, we are importing the math module as mt
4. print( "The value of euler's number is", mt.e )
5. # here, we are printing the euler's number from the math module

Output:

The value of euler's number is 2.718281828459045

The math module is now named mt in this program. In some situations, it might help us type
faster in case of modules having long names.
Please take note that now the scope of our program does not include the term math. Thus,
mt.pi is the proper implementation of the module, whereas math.pi is invalid.

Python from...import Statement

We can import specific names from a module without importing the module as a whole. Here
is an example.

Code

1. # Here, we are creating a simple Python program to show how to import specific
2. # objects from a module
3. # Here, we are import euler's number from the math module using the from keyword

4. from math import e


5. # here, the e value represents the euler's number
6. print( "The value of euler's number is", e )

Output:

The value of euler's number is 2.718281828459045

Only the e constant from the math module was imported in this case.

We avoid using the dot (.) operator in these scenarios. As follows, we may import many
attributes at the same time:

Code

1. # Here, we are creating a simple Python program to show how to import multiple
2. # objects from a module
3. from math import e, tau
4. print( "The value of tau constant is: ", tau )
5. print( "The value of the euler's number is: ", e )

Output:

The value of tau constant is: 6.283185307179586


The value of the euler's number is: 2.718281828459045
Python dir() Function

Python dir() function returns the list of names in the current local scope. If the object on
which method is called has a method named __dir__(), this method will be called and must
return the list of attributes. It takes a single object type argument. The signature of the
function is given below.

Signature
1. dir ([object])
Parameters

object: It takes an optional parameter.

Return

It returns a list of valid attributes of the object.

Let's see some examples of dir() function to understand it's functionality.

Python dir() Function Example 1

Let's create a simple example to get a list of valid attributes. It takes a single parameter which
is optional.

1. # Python dir() function example


2. # Calling function
3. att = dir()
4. # Displaying result
5. print(att)

Output:

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


'__name__', '__package__',
'__spec__']
Python dir() Function Example 2

If we pass a parameter to this function, it returns attributes related to that object. See an
example below.

1. # Python dir() function example


2. lang = ("C","C++","Java","Python")
3. # Calling function
4. att = dir(lang)
5. # Displaying result
6. print(att)

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',


'__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__',
'__sizeof__', '__str__',
'__subclasshook__', 'count', 'index']
how to construct and import custom Python modules. Additionally, we may import or
integrate Python's built-in modules via various methods.

Modular Programming

Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.

Modules in Python

A document with definitions of functions and various statements written in Python is called a
Python module.

In Python, we can define a module in one of 3 ways:

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
o A built-in module, such as the itertools module, is inherently included in the
interpreter.

A module is a file containing Python code, definitions of functions, statements, or classes. An


example_module.py file is a module we will create and whose name is example_module.

Example:

# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function

In Python, we may import functions from one module into our program, or as we say into,
another module.

For this, we make use of the import Python keyword.

Syntax:

import example_module

Example:

# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
Output:

By using the module square of number is: 16

Namespace in Python

the structure used to organize the symbolic names assigned to objects in a Python program,
why namespace is important, and how we can use them in our Python program. To put it
another way, it is a collection of the known symbolic names and the details about the thing
that each name refers to. A name can be thought of as a key in a dictionary, and objects are
the values in a namespace.

there are four types of namespaces which are given below.

o Built-in
o Global
o Enclosing
o Local

As these namespace various have lifetimes, Python interpreter creates namespaces as


necessary and deletes them when they are no longer needed.

Let's understand the various types of namespace in Python.

The Built-in Namespace

As its name suggests, it contains pre-defined names of all of Python's built-in objects already
available in Python. Let's list these names with the following command.

Open the Python terminal and type the following command.

Command -

1. dir(__builtins__)

The built-in namespace creates by the Python interpreter when its starts up. These are
terminated when Python interpreter terminates.

The Global Namespace

The global namespace consists of any names in Python at any level of the main program. It is
created when the main body executes and remains in existence until the interpreter
terminates.

The Python interpreter creates a global namespace for any module that our Python loads with
the import statement. To get more information, visit our Python Module.
The Local and Enclosing Namespaces

The local namespaces are used by the function; When the function is run, the Python
interpreter creates a new namespace. The local namespaces continue to exist after the
function has finished running. The capability can likewise comprise of another capability. As
shown below, we can define one function within another.

Example -

1. def f():
2. print('Initiate f()')
3.
4. def g():
5. print('Initiate g()')
6. print('End g()')
7. return
8.
9. g()
10.
11. print('Initiate f()')
12. return
13. f()

In the above model, the capability g() is characterized inside the collection of f(). We called
the g() function within the f() and the main f() function. Let's look at how the above function
works:

o Python creates a new namespace for f() when we call it.


o Likewise, the f() calls g(), g() gets its own different namespace.
o The local namespace g() was created for the enclosing namespace, f().

Each of these namespaces is terminated when the function is terminated.

Developing of a Python Module


A file containing Python commands and definitions is referred to as a module. These files
named .py which contain that contains Python code, such as example.py, and the name of the
module is an example. Modules are used to divide down huge applications into smaller,
more manageable files.
The prerequisites for using modules you should have Python 3 installed and a programming
environment set up. If you don't already have one, you can refer to the installation and setup
recommendations for a local programming environment.
Example 1
Let us look at an example to create a simple python module. Let us make a python file ad.py
def add(x, y):
return (x+y)
After doing so, upon saving the file as ad.py, a module named ad.py is created.
In Python, we can import definitions from one module into another or into the interactive
interpreter. To accomplish this, we employ the import keyword as shown below.
import module
Let us look at an example on how to import a python module. In the Python prompt, type the
following to import our previously defined module ad.
import ad
#importing module ad.py
The below code can be referred to for understanding how to access functions developed in a
custom module in python.
import ad
print(ad.add(9, 2))
Output
The output generated for the above line of code, when the add function from the user-defined
ad module has been called can be seen below.
11
Example 2
Let us another example to develop a python m
1. What is the method string?
2. What is string function and method in Python?
3. What are the built-in types in Python?
4. What are 4 built-in data types in Python?
5. How strings are immutable in Python with example?
6. Explain about string immutable data types in Python?
7. What are examples of immutable in Python?
8. Explain about string Comparison ?
9. What are the modules and namespace in Python?
10. How to defining our own modules?

-------------------------------------------------- UNIT - 3 completed ------------------------------------------

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.

Python Lists:
mylist = ["apple", "banana", "cherry"]

List:
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

List Items:

• List items are ordered, changeable, and allow duplicate values.


• List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered:

When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will
not change.

Changeable:
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.

Allow Duplicates:

Since lists are indexed, lists can have items with the same value:

Example
Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

List Length:
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types:

List items can be of any data type:

Example
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

type():
From Python's perspective, lists are defined as objects with the data type 'list':

<class 'list'>
Example
What is the data type of a list?

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

The list() Constructor:

It is also possible to use the list() constructor when creating a new list.

Example:
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


print(thislist)

Python Collections (Arrays):

There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.

Python - Access List Items:


Access Items:

List items are indexed and you can access them by referring to the index number:

Example

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])
Note: The first item has index 0.

Negative Indexing:

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]

Range of Indexes:

• You can specify a range of indexes by specifying where to start and where to end the
range.
• When specifying a range, the return value will be a new list with the specified items.

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:
Example

This example returns the items from the beginning to, but NOT including, "kiwi":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from "cherry" to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:])
Range of Negative Indexes:

Specify negative indexes if you want to start the search from the end of the list:

Check if Item Exists:

To determine if a specified item is present in a list use the in keyword:

Python Access List Items:


Access Items

You access the list items by referring to the index number:

Negative Indexing

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last item etc.

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:
Example

This example returns the items from the beginning to "orange":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from "cherry" and to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:])
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

Python List Operations

Introduction:
Do you know what a list is? Have you ever performed any operations on a list in Python? If
not, then don't worry; we got your back.

In Python, a list is a type of data structure that enables users to store information in sequence
to constitute a record. Its indexing starts from 0; a list can keep any data (integer, character, boolean,
string). Before we jump to Python list operations, it is recommended you go through the python
data types. Let us discuss the characteristics of a list.

Operations on Lists
A list in Python is built using square brackets. We write the values inside the square brackets
separated by commas.

Code to Create a List


#Creating an empty list
new_list = []

#List with string


new_list=['Coding', 'Ninjas']

Access Python List Elements


If suppose there is a Python list that has more than one element and the user wants to access a
particular element from that list, then that can be done by just declaring that index in square brackets
“[ ]”. As we know, indexing starts at 0, so to access the first element of a list, we need to input 0 into
the square brackets, and so on for subsequent elements.
Example:
coding_list = ["coding", “ninjas”, “data”, “science”] #This is a list declared under name: coding_list
print(coding_list[1]) #Accessing the 2nd element (index 1) of the list
Negative Indexing in Python
Python Lists and Strings allow element accessibility from the end as well, without writing
any long codes. If there is a long list with an enormous number of elements and the user wants to
access an element that is positioned in the last indexes, rather than traversing the whole list from the
start (index 0), the user can simply access the last elements by declaring the index with the “-” sign,
which indicates negation.
Example:
coding_list = ["coding", “ninjas”, “data”, “science”] #This is a list declared under name: coding_list
print(coding_list[-2]) #Accessing the 2nd last element (index 3) of the list

List Operations in Python


Below are some of the commonly used list operations in python:

1. Append()
As we know, a list is mutable. We can add an element at the back of the list using an inbuilt
function of Python list operation append(). Let us see implementations of it.
my_list=[1,2,3]
my_list.append(9)
my_list.append(8)
print("The list after append() operation is: ",my_list)
Here, we created a list called my_list and added elements to the list. The output of the above
code is:
Output:

2. extend()
Extend () method can be used to add more than one element at the end of a list. Let us
understand the function by its implementation.
my_list.extend([20,21])

print("The list after axtend() operator is: ",my_list)


By entering the values in a square bracket inside the function extend, we can see that all the elements
are added to the list.

3. Insert()
Now we can insert an element in between the list using the inbuilt function of Python list
operation insert()
my_list.insert(5,30)
print("The list after insert() operator is: \n",my_list)
In this function, the first input is the position at which the element is to be added, and the second
input is the element's value. Here after using the insert() we have added 30 at 5th position in my_list.
Hence the updated list will be:

4. remove()
The way we added an element between the list, similarly, we can remove from in between a
list using an inbuilt Python list operation function remove().
my_list.remove(10)
print("The list after remove() operator is: \n",my_list)
As we have removed 10 from my_list, the output of the above code will be:
We can see that element 10 is removed from the list.
5. Pop()
There is an inbuilt function to remove the last element from the list known as pop().
my_list.pop()
print("The list after pop() operator is:\n",my_list)
After using pop() operator, the last element would be removed from our my_list list. Here the
last element, 5, is removed from the list. Hence our updated list is

6. Slice()
This method is used to print a section of the list. Which means we can display elements of a
specific index.
print("The elements of list in the range of 3 to 12 are:\n",my_list[3:12])
Using the slicing operator, we have sliced elements from range of 3 to 12 in the my_list.
Hence the above code would print elements whose index lies between the range 3 to 12.

Note that the slice method only prints the elements; it does not change the list.

7. reverse()
To reverse the indexing of elements in a list, the simple built-in function reverse() can be
used. This function allows the user to reverse the order of elements very quickly and without large
code lines. To reverse a list, it needs to be parsed with the function itself.

Example:
coding_list = ["coding", "ninjas”, "data", "science"]
coding_list.reverse() #Reverse Function implemented
print(coding_list)
Output:
['science', 'data', 'ninjas', 'coding']

8. len(), min() & max()


Other Python list operations are len(), min(), and max(). As the name suggests, they are used
to know the length of a list, the minimum element in the list, and the maximum element in the list,
respectively.
print("Length of the list is: ",len(my_list))
print("Maximum element in the list is: ",max(my_list))
print("Minimum element in the list is: ",min(my_list))
The length, maximum and minimum element in my_list are:

9. count()
As we can store duplicates in a list, a Python list operation is used to count the number of
copies, known as count().
my_list.extend([10,20,22])
print("The list is: \n",my_list)
print("Number of times 21 is in the list are: ",my_list.count(20))
After using the extend() and count() operator on my_list, the the number of repetitions of 21
are:

Here 2 shows the number of occurrences of element 23.


10. Concatenate

Concatenate is a very simple process, with the literal meaning of combining or joining two
objects. Similarly, concatenation in Python can be used to combine two lists or strings.
Concatenation in Python can be simply performed by using “+” between variable names that hold a
string or list.

Example:
list_one = [100, 150, 200]
list_two = [900, 950, 800]
new_list = list_one + list_two #new_list variable holds the concatenated list
print(new_list)
Output:
[100, 150, 200, 900, 950, 800]
Similarly, following is an example to perform concatenation on a string:
string_one = ["Coding"]
string_two = ["Ninjas"]
new_string = string_one + string_two
print(new_string)
Output:
['Coding', 'Ninjas']

11. Multiply
Did you know that you can increase the number of elements in a list by
simply multiplying it by a number? For example, by multiplying a list with the
number ‘n’, you get that list element being repeated ‘n’ times. List
multiplication can be performed by just

Basic List Operations in Python


Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior
chapter.

Python Expression Results Description

len([1, 2, 3]) 3 Length

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


Python Expression Results Description

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration


t using the “*” operator. Following is a code example:

Python - List Methods

List Methods

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

Method Description

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

clear() Removes all the elements from the list

copy() Returns a copy of the list

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

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

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position


remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python List Exercises

Test Yourself With Exercises

• Now you have learned a lot about lists, and how to use them in Python.
• Are you ready for a test?
• Try to insert the missing part to make the code work as expected:

Tuple:

• Tuples are used to store multiple items in a single variable.


• Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.

Example
Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Tuple Items:

• Tuple items are ordered, unchangeable, and allow duplicate values.


• Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered:
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example
Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length

To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not
recognize it as a tuple.

Example

One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types

Tuple items can be of any data type:

Example
String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
type()

From Python's perspective, tuples are defined as objects with the data type 'tuple':

The tuple() Constructor


Python Collections (Arrays)
There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate members.


• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.

Python - Access Tuple Items


Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Python - Update Tuples

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is
created.

But there are some workarounds.

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as
it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)
Add Items

Since tuples are immutable, they do not have a built-in append() method, but there are other ways
to add items to a tuple.

1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.

Example

Convert the tuple into a list, add "orange", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or
many), create a new tuple with the item(s), and add it to the existing tuple:

Example
Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y

print(thistuple)

Remove Items
Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:

Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Python Dictionaries

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items

• Dictionary items are ordered, changeable, and does not allow duplicates.
• Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

type()
The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary.

ONE MARK QUESTIONS

1. Which of the following is a Python tuple?


a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable

2. Which of the following is not a declaration of the dictionary?

a) {1: ‘A’, 2: ‘B’}


b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }

3. What will be the output of the following Python code snippet?

a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”

4. What will be the output of the following Python code snippet?

a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method

5. What will be the output of the following Python code snippet?

a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
a) Error, invalid syntax
b) A
c) 5
d) 4

6. What will be the output of the following Python code snippet?

a={1:"A",2:"B",3:"C"}
print(a.setdefault(3))
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) C
c) {1: 3, 2: 3, 3: 3}
d) No method called setdefault() exists for dictionary

7. What will be the output of the following Python code snippet?


a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D")
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}
b) None
c) Error
d) [1,3,6,10]

8. What will be the output of the following Python code?

a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) Method update() doesn’t exist for dictionaries
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
d) {4: ‘D’, 5: ‘E’}

9. What will be the output of the following Python code?

a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn’t exist for dictionaries
b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
d) “None” is printed

10. What will be the output of the following Python code?

a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) { None:None, None:None, None:None}
c) {1:None, 2:None, 3:None}
d) { }

11. Which of the following isn’t true about dictionary keys?


a) More than one key isn’t allowed
b) Keys must be immutable
c) Keys must be integers
d) When duplicate keys encountered, the last assignment wins

12. What will be the output of the following Python code?

a={1:5,2:3,3:4}
a.pop(3)
print(a)
a) {1: 5}
b) {1: 5, 2: 3}
c) Error, syntax error for pop() method
d) {1: 5, 3: 4}

13. What will be the output of the following Python code?

a={1:5,2:3,3:4}
print(a.pop(4,9))
a) 9
b) 3
c) Too many arguments for pop() method
d) 4

14. What will be the output of the following Python code?

a={1:"A",2:"B",3:"C"}
for i in a:
print(i,end=" ")
a) 1 2 3
b) ‘A’ ‘B’ ‘C’
c) 1 ‘A’ 2 ‘B’ 3 ‘C’
d) Error, it should be: for i in a.items():

15. What will be the output of the following Python code?

>>> a={1:"A",2:"B",3:"C"}
>>> a.items()
a) Syntax error
b) dict_items([(‘A’), (‘B’), (‘C’)])
c) dict_items([(1,2,3)])
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])

5 MARKS

1. Check if a list contains an element?


2. How to iterate over 2+ lists at the same time?
3. When would you use a list vs dictionary?
4. what you mean by tuple in python?
5. Explain about creating in tuples?
6. Explain about updating and deleting in tuples?
7.Difference between List and Dictionaries?
8. Explain about dictionary function and methods?
9. Explain about nested tuples?
10. How to access tuples?

10 MARKS
1. What 4 methods can be used with a list?
2. What are the operations performed in the list?
3. What is list and methods of list in Python?
4. How many lists function in Python?
5. What are the types of list?
6.What are dictionaries for Python?
7.What is dictionary in Python with example?
8.What is dictionary and its types in Python?
9.How to get top 10 values in dictionary Python?
10.What are nested list in Python?
11.How do you make a list of 10 elements in Python?
12.What are nested lists?
13.How do you create a nested list in Python?
14.How do you update and delete a list in Python?
15.What is the delete method for list in Python?
16.How do you update a list of lists in Python?
17.How do I remove the first 10 elements from a list in Python?
18.What is the difference between list and tuple in Python?
19.What are the three main differences between tuples and lists in Python?
20.What's the main difference between Python lists and tuples?

--------------------------------------------- UNIT - 4 Completed ----------------------------------------------

UNIT - V
Python File Handling:
Types of files in Python - Opening and Closing filesReading 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.

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.

Python File Handling


Python too 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, but 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

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

Disadvantages of File Handling


• 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.
For this article, we will consider the following “geeks.txt” file as an example.

Working of open() Function in Python


Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time of
opening, we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.

Working in Read mode


There is more than one way to read a file in Python. Let us see how we can read the
content of a file in read mode.
Example 1: The open command will open the file in the read mode and the for loop will
print each line present in the file.
Output:
Hello world

Creating a File using the write() Function


Just like reading a file in Python, there are a number of ways to write in a file in
Python. Let us see how we can write the content of a file using the write() function in
Python.

Working in Write Mode


Let’s see how to create a file and how the write mode works.
Example 1: In this example, we will see how the write mode and the write() function is
used to write in a file. The close() command terminates all the resources in use and frees
the system of this particular program.
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.

Open a File in Python


Python provides inbuilt functions for creating, writing, and reading files. 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).
• 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. In the case of CSV(Comma Separated Files, the EOF is a
comma by default.
• 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, i.e., 0 and
1 format.
Refer to the below articles to get an idea about the basics of file handling.
• Basics of file handling
• Reading and Writing to file

Opening a File in Python

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). Now, the question arises what is the access mode? Access
modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File
Handle in the file. The file handle is like a cursor, which defines where the data has
to be read or written in the file. There are 6 access modes in Python.

Mode Description

‘r’ Open text file for reading. Raises an I/O error if the file does not exist.

‘r+’ Open the file for reading and writing. Raises an I/O error if the file does not exist.

Open the file for writing. Truncates the file if it already exists. Creates a new file if it does
‘w’
not exist.

Open the file for reading and writing. Truncates the file if it already exists. Creates a new
‘w+’
file if it does not exist.

Open the file for writing. The data being written will be inserted at the end of the file.
‘a’
Creates a new file if it does not exist.

Open the file for reading and writing. The data being written will be inserted at the end of
‘a+’
the file. Creates a new file if it does not exist.

‘rb’ Open the file for reading in binary format. Raises an I/O error if the file does not exist.

‘rb+’ Open the file for reading and writing in binary format. Raises an I/O error if the file does
Mode Description

not exist.

Open the file for writing in binary format. Truncates the file if it already exists. Creates a
‘wb’
new file if it does not exist.

Open the file for reading and writing in binary format. Truncates the file if it already
‘wb+’
exists. Creates a new file if it does not exist.

Open the file for appending in binary format. Inserts data at the end of the file. Creates a
‘ab’
new file if it does not exist.

Open the file for reading and appending in binary format. Inserts data at the end of the file.
‘ab+’
Creates a new file if it does not exist.

Syntax:
File_object = open(r"File_Name", "Access_Mode")
Note: The file should exist in the same directory as the Python script, otherwise full address
of the file should be written. If the file is not exist, then an error is generated, that the file
does not exist.
Output:
Welcome to GeeksForGeeks!!
Note: In the above example, we haven’t provided the access mode. By default, the open()
function will open the file in read mode, if no parameter is provided.

Adding data to the existing file in Python

If you want to add more data to an already created file, then the access mode should be
‘a’ which is append mode, if we select ‘w’ mode then the existing text will be overwritten by
the new data.
# Python program to demonstrate
# opening a file

# Open function to open the file "myfile.txt"


# (same directory) in append mode and store
# it's reference in the variable file1
file1 = open("myfile.txt" , "a" )

# Writing to file
file1.write("\nWriting to file:)" )

# Closing file
file1.close()
Sample Run:

Enter the name of the employee: Aditya


Enter the name of the employee: Aditi
Enter the name of the employee: Anil

writelines() function

This function writes the content of a list to a file.


Syntax:
# write all the strings present in the list "list_of_lines"
# referenced by file object.
file_name.writelines(list_of_lines)
As per the syntax, the list of strings that is passed to the writelines() function is written into
the opened file. Similar to the write() function, the writelines() function does not add a
newline character(\n) to the end of the string.
Example:
Python3
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')

file1.writelines(lst)
file1.close()
print("Data is written into the file.")

Output:
Data is written into the file.
Sample Run:
Enter the name of the employee: Rhea
Enter the name of the employee: Rohan
Enter the name of the employee: Rahul
The only difference between the write() and writelines() is that write() is used to write
a string to an already opened file while writelines() method is used to write a list of strings in
an opened file.

Python List append() Method


Lists are fundamental data structure in Python that allows storing and manipulating a
collection of objects in a list in Python. The list is mutable. There are different methods to
add elements to a list in Python. In This Article, we will learn to add elements to a list using
different methods. The Python List append() method is used for appending and adding
elements to the end of the Python List.
Example
Input: list = ['geeks', 'for']
Output: ['geeks', 'for', 'geeks']
Explaination: "geeks" Element added to a List

Python List append() Syntax


The syntax of the Python List append() method is as follows:
Syntax: list.append(item)
Parameters:
• item: an item to be added at the end of the list, The parameter is mandatory and
omitting it can give an error.
Returns: The method doesn’t return any value
How To add Elements to a List in Python
The list is a sequence datatype used to store elements. Lists are mutable i.e., we can
add/remove elements. There are different methods to add elements to a list in Python.
• Using the Append() Method
• Adding List to the List
• Using the Concatenation operator
• Using List Slicing
Adding elements to the end of a list with Python’s append() method increases the list’s size.
It offers a practical method to add one or more elements to a list that already exists. Here is
an example of using the List Append() method.

Adding an Element to the List Using Append()


In this example, we will append a single element at the end of the given list using the List
append() method in Python.
Python3

# my_list
my_list = ['geeks', 'for']

# Add 'geeks' to the list


my_list.append('geeks')

print(my_list)

Output:
['geeks', 'for', 'geeks']
Adding List to the List
In this example, we will append a complete list at the end of the given list.
Python3

# my_list
my_list = ['geeks', 'for', 'geeks']

# another list
another_list = [6, 0, 4, 1]

# append another_list to my_list


my_list.append(another_list)
print(my_list)

Output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]
Note: A list is an object. If you append another list onto a list, the parameter list will be a
single object at the end of the list. If you want to append the elements of a list to another list
you can use Python’s List extend() method.
Time complexity: O(1) or constant time. This is because lists can be accessed randomly
using indexing, so the last element can be accessed easily in O(1) time.
Elements Add to a List in Python Using Concatenation Operator
Another way to add elements to a list is using the concatenation operator( ‘+’ ), in this
we create a new list by combining the existing list with another list that contains the new
element.

Python3

my_list = [9, 5, 7] # Existing list


new_element = 3
my_list = my_list + [new_element]
print(my_list) # Output: [9, 5, 7, 3]

Output:
[9, 5, 7, 3]
Elements Add to a List in Python Using List Slicing
Another way to add elements to a list is using list slicing, this allows you to modify a
portion of a list by assigning new values to it. To add elements to specific positions within a
list, we can use list slicing with the insert() method.
Python3

my_list = [3, 4, 6] # Existing list


my_list.insert(2, 5) # Insert element 5 at index 2
print(my_list)

Output:
[3, 4, 5, 6]

What are readline() & readlines() Methods In Python

Python programming language is a pinnacle in the IT industry. With brilliant library support and
out of the box features, Python programming has made file handling looking like a piece of cake. It
provides easy implementations for File handling related tasks. One such method is the Python
readline method. In this article, we will learn about the Python readline() method with examples. The
following concepts are covered in this article:

• What is Python readline()?


• Syntax And Usage
• Python readline() Examples
• Python readlines() Examples

What is Python readline()?


Python readline() method will return a line from the file when called.

readlines() method will return all the lines in a file in the format of a list where each element is a
line in the file.

Syntax And Usage

After opening the file using the open() method, we can simply use these methods.

Python readline() syntax

Python Certification Training Course

Explore Curriculum

1file = open("filename.txt", "r")


2file.readline()
The readline method takes one parameter i.e size, the default value for the size parameter is -1. It
means that the method will return the whole line. It is an optional parameter, we can specify the
number of bytes from a line to return.

readlines() Syntax

1file = open("filename.txt","r")
2file.readlines()

The readlines method takes one parameter i.e hint, the default value for the hint parameter is -
1. It means that the method will return all the lines. If we specify the hint parameter, the lines
exceeding the number of bytes from the hint parameter will not be returned by the readlines method.

Let us go ahead and take a look at a few examples to understand how these methods work in Python.

Python readline() Examples

Let us suppose we have a text file with the name examples.txt with the following content.

Python is the best programming language in the world in 2020


Edureka is the biggest Ed-tech platform to learn python
Python programming is as easy as writing a program in simple English language

Now, to use the readline, we will have to open the example.txt file.

readlines() Examples

We can use the readlines() method just like we used readline() in the above example.

Output: ['Python is the best programming language in the world in 2020',


'Edureka is the biggest Ed-tech platform to learn python',
'Python programming is as easy as writing a program in simple English language']

This brings us to the end of this article where we have learned how we use the Python
readline() method with examples. I hope you are clear with all that has been shared with you in this
tutorial.

If you found this article on “Python readline()” relevant, check out Edureka’s Python Course a
trusted online learning company with a network of more than 250,000 satisfied learners spread
across the globe.

Python read, readline and readlines | Differences

Python allows you to read the contents of a file using methods such as:

▪ read()
▪ readline()
▪ readline()

Python read()

The read method reads the entire contents of a file and returns it as a string.

with open("file.txt", "r") as file:


content = file.read()
print(content)

Python readline()

The readline method reads a single line from a file and returns it as a string. This means that
if you use readline, you can read the contents of a file line by line, which can be useful
for processing large files that do not fit in memory.

with open("file.txt", "r") as file:


line = file.readline()
while line:
print(line.strip())
line = file.readline()

In the above example, the while loop continues to read lines from the file until
readline returns an empty string, indicating the end of the file. The strip method is used to remove
the line terminator from each line.

Python readlines()

The readline method reads a single line from a file and returns it as a string, while the
readlines method reads the entire contents of a file and returns it as a list of strings, where each
element of the list is a single line of the file.

You can see the difference of readline() and readlines() methods from the following example:

with open("file.txt") as f:
line = f.readline()
print(line)# Prints the first line of the file

lines = f.readlines()
print(lines) # Prints a list of all the lines in the file after the first line

Python readlines reads the whole file into memory, which can be problematic if the file is
very large. In such cases, it's usually better to use readline and process the file one line at a time. If
you want to remove the line terminator characters (\n or \r\n) from each line, you can use the strip
method:

with open("file.txt", "r") as file:


lines = file.readlines()
for line in lines:
print(line.strip())

Pros and Cons | read, readline, and readlines


Python read() method:

Pros:

▪ Simple and straightforward to use.


▪ Good for reading small files.

Cons:

▪ Can consume a lot of memory if the file is large.


▪ The entire contents of the file must be stored in memory, which can lead to performance
issues.

Python readline() method:


Pros:

▪ Good for processing large files that do not fit in memory.


▪ Reads the file line by line, reducing memory usage.

Cons:

▪ More complicated to use than read.


▪ Not as efficient for reading small files.

Python readlines():

Pros:

▪ Good for reading small files.


▪ Returns the contents of the file as a list of strings, which makes it easy to work with the file's
contents.

Cons:

▪ Can consume a lot of memory if the file is large.


▪ The entire contents of the file must be stored in memory, which can lead to performance issue

How to read from a file in Python

Python provides inbuilt functions for creating, writing and reading files. 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).

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.
• 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.
Note: To know more about file handling click here.
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File Handle in
the file. File handle is like a cursor, which defines from where the data has to be read or
written in the file. Different access modes for reading a file are –
1. Read Only (‘r’) : Open text file for reading.
The handle is positioned at the beginning of the file. If the file does not exists, raises I/O
error. This is also the default mode in which file is opened.
2. 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 exists.
3. Append and Read (‘a+’) : Open the file for
reading and writing. The file is created if it does not exist. The handle is position
4. ned at the end of the file. The data being written
will be inserted at the end, after the existing data.
Note: To know more about access mode click here.

Opening a File

It is done using the open() function. No module is required to be imported for this
function.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename. Note: The r is placed before filename to prevent the
characters in filename string to be treated as special character. For example, if there is \temp in the
file address, then \t is treated as the tab character and error is raised of invalid address. The r makes
the string raw, that is, it tells that the string is without any special characters. The r can be ignored if
the file is in same directory and address is not being placed.

• Python3
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile.txt", "r")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "r+")

Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at
the time when the file is no longer needed or if it is to be opened in a different file mode.
Syntax:
File_object.close()

Reading from a file


There are three ways to read data from a text file.
• 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])
• 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])
• 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.

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


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
With statement
with statement in Python is used in exception handling to make the code cleaner and
much more readable. It simplifies the management of common resources like file streams.
Unlike the above implementations, there is no need to call file.close() when using with
statement. The with statement itself ensures proper acquisition and release of resources.
Syntax:
with open filename as file:

• Python3
# Program to show various ways to
# read data from a file.

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

with open("myfile.txt", "r+") as file1:


# Reading from a file
print(file1.read())

Output:
Hello
This is Delhi
This is Paris
This is London

Writing to file in Python

Python provides inbuilt functions for creating, writing and reading files. 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).
•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.
• 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.
Note: To know more about file handling click here.
Table of content
• Access mode
• Opening a file
• Closing a file
• Writing to file
• Appending to a file
• With statement
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File Handle in
the file. File handle is like a cursor, which defines from where the data has to be read or
written in the file. Different access modes for reading a file are –
1. Write Only (‘w’) : Open the file for writing. For an existing file, 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.
2. 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.
3. 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.
Note: To know more about access mode

Opening a File
It is done using the open() function. No module is required to be imported for this
function. Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of
the file should be written on place of filename. Note: The r is placed before filename to
prevent the characters in filename string to be treated as special character. For example, if
there is \temp in the file address, then \t is treated as the tab character and error is raised of
invalid address. The r makes the string raw, that is, it tells that the string is without any
special characters. The r can be ignored if the file is in same directory and address is not
being placed.
• Python3
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile.txt", "w")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "w+")

Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is
used at the time when the file is no longer needed or if it is to be opened in a different file
mode. Syntax:
File_object.close()

• Python3
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt", "w")
file1.close()

Writing to file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
1. 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]
Note: ‘\n’ is treated as a special character of two bytes. Example:
• Python3
# Python program to demonstrate
# writing to file

# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"

# Writing a string to file


file1.write(s)

# Writing multiple strings


# at a time
file1.writelines(L)

# Closing file
file1.close()

# Checking if the data is


# written to file or not
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()

Output:
Hello
This is Delhi
This is Paris
This is London
Appending to a file
When the file is opened in append mode, the handle is positioned at the end of the file.
The data being written will be inserted at the end, after the existing data. Let’s see the below
example to clarify the difference between write mode and append mode.

• Python3
# 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.read())
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.read())
print()
file1.close()

Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today

Output of Readlines after writing


Tomorrow
With statement
with statement in Python is used in exception handling to make the code cleaner and
much more readable. It simplifies the management of common resources like file streams.
Unlike the above implementations, there is no need to call file.close() when using with
statement. The with statement itself ensures proper acquisition and release of resources.
Syntax:
with open filename as file:

• Python3
# Program to show various ways to
# write data to a file using with statement

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Writing to file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)

# Reading from file


with open("myfile.txt", "r+") as file1:
# Reading form a file
print(file1.read())

Output:
Hello
This is Delhi
This is Paris
This is London
Note: To know more about with statement click here.
using for statement:
steps:
To write to a file in Python using a for statement, you can follow these steps:
Open the file using the open() function with the appropriate mode (‘w’ for writing).
Use the for statement to loop over the data you want to write to the file.
Use the file object’s write() method to write the data to the file.
Close the file using the file object’s close() method.
In this example, the file is opened for writing using the with open(‘file.txt’, ‘w’) as f
statement. The data to be written is stored in a list called data. The for statement is used to
loop over each line of data in the list. The f.write(line + ‘\n’) statement writes each line of
data to the file with a newline character (\n) at the end. Finally, the file is automatically
closed when the with block ends.

• Python3
# Open the file for writing
with open('file.txt', 'w') as f:
# Define the data to be written
data = ['This is the first line', 'This is the second line', 'This is the third line']
# Use a for loop to write each line of data to the file
for line in data:
f.write(line + '\n')
# Optionally, print the data as it is written to the file
print(line)
# The file is automatically closed when the 'with' block ends
Output
This is the first line
This is the second line
This is the third line
Keyword Description

and A logical operator

as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

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

False Boolean value, result of comparison operations

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

for To create a for loop


from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value


True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

Approach:
The code opens a file called file.txt in write mode using a with block to ensure the file
is properly closed when the block ends. It defines a list of strings called data that
represents the lines to be written to the file. The code then uses a for loop to iterate
through each string in data, and writes each string to the file using the write() method.
The code appends a newline character to each string to ensure that each string is
written on a new line in the file. The code optionally prints each string as it is written
to the file.
Time Complexity:
Both the original code and the alternative code have a time complexity of O(n), where n is
the number of lines to be written to the file. This is because both codes need to iterate
through each line in the data list to write it to the file.
Space Complexity:
The original code and the alternative code have the same space complexity of O(n), where n
is the number of lines to be written to the file. This is because both codes need to create a list
of strings that represent the lines to be written to the file.

List of Keywords in Python

Python Keywords

Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:

some example of their usage are given below

>>> True and False


False
>>> True or False
True
>>> not False
True

as

as is used to create an alias while importing a module. It means giving a different name (user-
defined) to a module while importing it.
As for example, Python has a standard module called math. Suppose we want to calculate what
cosine pi is using an alias. We can do it as follows using as:

>>> import math as myAlias


>>>myAlias.cos(myAlias.pi)
-1.0

Here we imported the math module by giving it the name myAlias. Now we can refer to
the math module with this name. Using this name we calculated cos(pi) and got -1.0 as the answer.
assert

assert is used for debugging purposes.


While programming, sometimes we wish to know the internal state or check if our assumptions are
true. assert helps us do this and find bugs more conveniently. assert is followed by a condition.
If the condition is true, nothing happens. But if the condition is false, AssertionError is raised. For
example:

>>> a = 4
>>> assert a < 5
>>> assert a > 5
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError

For our better understanding, we can also provide a message to be printed with the AssertionError.

>>> a = 4
>>> assert a > 5, "The value of a is too small"
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError: The value of a is too small

At this point we can note that,


assert condition, message

is equivalent to,

if not condition:
raise AssertionError(message)

async, await

The async and await keywords are provided by the asyncio library in Python. They are used to write
concurrent code in Python. For example,

import asyncio

async def main():


print('Hello')
await asyncio.sleep(1)
print('world')

To run the program, we use

asyncio.run(main())

In the above program, the async keyword specifies that the function will be executed
asynchronously.
Here, first Hello is printed. The await keyword makes the program wait for 1 second. And then
the world is printed.
break, continue

break and continue are used inside for and while loops to alter their normal behavior.
break will end the smallest loop it is in and control flows to the statement immediately below
the loop. continue causes to end the current iteration of the loop, but not the whole loop.
This can be illustrated with the following two examples:

for i in range(1,11):
if i == 5:
break
print(i)

Output

1
2
3
4

Here, the for loop intends to print numbers from 1 to 10. But the if condition is met when i is
equal to 5 and we break from the loop. Thus, only the range 1 to 4 is printed.

for i in range(1,11):
if i == 5:
continue
print(i)

Output

1
2
3
4
6
7
8
9
10

Here we use continue for the same program. So, when the condition is met, that iteration is
skipped. But we do not exit the loop. Hence, all the values except 5 are printed out.
Learn more about Python break and continue statement.
class

class is used to define a new user-defined class in Python.


Class is a collection of related attributes and methods that try to represent a real-world situation. This
idea of putting data and functions together in a class is central to the concept of object-oriented
programming (OOP).

Classes can be defined anywhere in a program. But it is a good practice to define a single
class in a module. Following is a sample usage:

class ExampleClass:
def function1(parameters):

def function2(parameters):

Learn more about Python Objects and Class.


def

def is used to define a user-defined function.


Function is a block of related statements, which together does some specific task. It helps us organize
code into manageable chunks and also to do some repetitive task.

The usage of def is shown below:

def function_name(parameters):

Learn more about Python functions.


del

del is used to delete the reference to an object. Everything is object in Python. We can delete
a variable reference using del

>>> a = b = 5
>>> del a
>>> a
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
5

Here we can see that the reference of the variable a was deleted. So, it is no longer defined.
But b still exists.
del is also used to delete items from a list or a dictionary:

>>> a = ['x','y','z']
>>> del a[1]
>>> a
['x', 'z']

if, else, elif

if, else, elif are used for conditional branching or decision making.
When we want to test some condition and execute a block only if the condition is true, then
we use if and elif. elif is short for else if. else is the block which is executed if the condition is false.
This will be clear with the following example:
def if_example(a):
if a == 1:
print('One')
elif a == 2:
print('Two')
else:
print('Something else')

if_example(2)
if_example(4)
if_example(1)

Output

Two
Something else
One

Here, the function checks the input number and prints the result if it is 1 or 2. Any input other
than this will cause the else part of the code to execute.
Learn more about Python if and if...else Statement.
except, raise, try

except, raise, try are used with exceptions in Python.


Exceptions are basically errors that suggests something went wrong while executing our
program. IOError, ValueError, ZeroDivisionError, ImportError, NameError, TypeError etc. are
few examples of exception in Python. try...except blocks are used to catch exceptions in Python.
We can raise an exception explicitly with the raise keyword. Following is an example:

def reciprocal(num):
try:
r = 1/num
except:
print('Exception caught')
return
return r

print(reciprocal(10))
print(reciprocal(0))

Output

0.1
Exception caught
None
Here, the function reciprocal() returns the reciprocal of the input number.
When we enter 10, we get the normal output of 0.1. But when we input 0, a ZeroDivisionError is
raised automatically.
This is caught by our try…except block and we return None. We could have also raised
the ZeroDivisionError explicitly by checking the input and handled it elsewhere as follows:

if num == 0:
raise ZeroDivisionError('cannot divide')

finally

finally is used with try…except block to close up resources or file streams.


Using finally ensures that the block of code inside it gets executed even if there is an unhandled
exception. For example:

try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
finally:
Finally-block

Here if there is an exception in the Try-block, it is handled in the except or else block. But
no matter in what order the execution flows, we can rest assured that the Finally-block is
executed even if there is an error. This is useful in cleaning up the resources.
Learn more about exception handling in Python programming.
for

for is used for looping. Generally we use for when we know the number of times we want to
loop.
In Python we can use it with any type of sequences like a list or a string. Here is an example in
which for is used to traverse through a list of names:

names = ['John','Monica','Steven','Robin']
for i in names:
print('Hello '+i)

Output
Hello John
Hello Monica
Hello Steven
Hello Robin

Learn more about Python for loop.


from, import

import keyword is used to import modules into the current namespace. from…import is used
to import specific attributes or functions into the current namespace. For example:

import math

will import the math module. Now we can use the cos() function inside it as math.cos(). But
if we wanted to import just the cos() function, this can done using from as

from math import cos

now we can use the function simply as cos(), no need to write math.cos().
Learn more on Python modules and import statement.
global

global is used to declare that a variable inside the function is global (outside the function).
If we need to read the value of a global variable, it is not necessary to define it as global. This is
understood.
If we need to modify the value of a global variable inside a function, then we must declare it
with global. Otherwise, a local variable with that name is created.
Following example will help us clarify this.

globvar = 10
def read1():
print(globvar)
def write1():
global globvar
globvar = 5
def write2():
globvar = 15

read1()
write1()
read1()
write2()
read1()

Output

10
5
5

Here, the read1() function is just reading the value of globvar. So, we do not need to declare
it as global. But the write1() function is modifying the value, so we need to declare the variable
as global.
We can see in our output that the modification did take place (10 is changed to 5). The write2() also
tries to modify this value. But we have not declared it as global.
Hence, a new local variable globvar is created which is not visible outside this function.
Although we modify this local variable to 15, the global variable remains unchanged. This is clearly
visible in our output.
in

in is used to test if a sequence (list, tuple, string etc.) contains a value. It returns True if the value is
present, else it returns False. For example:

>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False

The secondary use of in is to traverse through a sequence in a for loop.

for i in 'hello':
print(i)

Output

h
e
l
l
o

is

is is used in Python for testing object identity. While the == operator is used to test if two
variables are equal or not, is is used to test if the two variables refer to the same object.
It returns True if the objects are identical and False if not.

>>> True is True


True
>>> False is False
True
>>> None is None
True

We know that there is only one instance of True, False and None in Python, so they are
identical.

>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False

An empty list or dictionary is equal to another empty one. But they are not identical objects
as they are located separately in memory. This is because list and dictionary are mutable (value can
be changed).

>>> '' == ''


True
>>> '' is ''
True
>>> () == ()
True
>>> () is ()
True

Unlike list and dictionary, string and tuple are immutable (value cannot be altered once
defined). Hence, two equal string or tuple are identical as well. They refer to the same memory
location.

lambda

lambda is used to create an anonymous function (function with no name). It is an inline


function that does not contain a return statement. It consists of an expression that is evaluated and
returned. For example:

a = lambda x: x*2
for i in range(1,6):
print(a(i))

Output

2
4
6
8
10

Here, we have created an inline function that doubles the value, using the lambda statement.
We used this to double the values in a list containing 1 to 5.
Learn more about Python lamda function.
nonlocal

The use of nonlocal keyword is very much similar to the global keyword. nonlocal is used to
declare that a variable inside afunction (function inside a function) is not local to it, meaning
it lies in the outer inclosing function. If we need to
modify the value of a non-local variable inside a nested function, then we must declare it
with nonlocal. Otherwise a local variable with that name is created inside the nested function.
Following example will help us clarify this.

def outer_function():
a=5
def inner_function():
nonlocal a
a = 10
print("Inner function: ",a)
inner_function()
print("Outer function: ",a)

outer_function()

Output

Inner function: 10
Outer function: 10

Here, the inner_function() is nested within the outer_function.


The variable a is in the outer_function(). So, if we want to modify it in the inner_function(),
we must declare it as nonlocal. Notice that a is not a global variable.
Hence, we see from the output that the variable was successfully modified inside the
nested inner_function(). The result of not using the nonlocal keyword is as follows:

def outer_function():
a=5
def inner_function():
a = 10
print("Inner function: ",a)
inner_function()
print("Outer function: ",a)

outer_function()

Output

Inner function: 10
Outer function: 5

Here, we do not declare that the variable a inside the nested function is nonlocal. Hence, a
new local variable with the same name is created, but the non-local a is not modified as seen in our
output.
pass

pass is a null statement in Python. Nothing happens when it is executed. It is used as a


placeholder.
Suppose we have a function that is not implemented yet, but we want to implement it in the future.
Simply writing,

def function(args):

in the middle of a program will give us IndentationError. Instead of this, we construct a blank body
with the pass statement.

def function(args):
pass

We can do the same thing in an empty class as well.

class example:
pass

return

return statement is used inside a function to exit it and return a value.


If we do not return a value explicitly, None is returned automatically. This is verified with the
following example.

def func_return():
a = 10
return a

def no_return():
a = 10

print(func_return())
print(no_return())

Output

10
None

while

while is used for looping in Python.


The statements inside a while loop continue to execute until the condition for the while loop
evaluates to False or a break statement is encountered. Following program illustrates this.

i=5
while(i):
print(i)
i=i–1

Output

5
4
3
2
1

Note that 0 is equal to False.


Learn more about Python while loop.
with

with statement is used to wrap the execution of a block of code within methods defined by
the context manager.
Context manager is a class that implements __enter__ and __exit__ methods. Use of with statement
ensures that the __exit__ method is called at the end of the nested block. This concept is similar to
the use of try…finally block. Here, is an example.

with open('example.txt', 'w') as my_file:


my_file.write('Hello world!')

This example writes the text Hello world! to the file example.txt. File objects
have __enter__ and __exit__ method defined within them, so they act as their own context manager.
First the __enter__ method is called, then the code within with statement is executed and
finally the __exit__ method is called. __exit__ method is called even if there is an error. It basically
closes the file stream.
yield

yield is used inside a function like a return statement. But yield returns a generator.
Generator is an iterator that generates one item at a time. A large list of values will take up a lot of
memory. Generators are useful in this situation as it generates only one value at a time instead of
storing all the values in memory. For example,

>>> g = (2**x for x in range(100))

will create a generator g which generates powers of 2 up to the number two raised to the
power 99. We can generate the numbers using the next() function as shown below.

>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
>>> next(g)
16

And so on… This type of generator is returned by the yield statement from a function. Here is an
example.

def generator():
for i in range(6):
yield i*i

g = generator()
for i in g:
print(i)

Output

0
1
4
9
16
25

Here, the function generator() returns a generator that generates square of numbers from 0 to
5. This is printed in the for loop.

Split in Python

The split() method in Python returns a list of the words in the string/line , separated by
the delimiter string. This method will return one or more new strings. All substrings are returned in
the list datatype.

Syntax

string.split(separator, max)

Parameter Description
The is a delimiter. The string splits at this specified separator. If is not
separator
provided then any white space is a separator.
It is a number, which tells us to split the string into maximum of provided
maxsplit
number of times. If it is not provided then there is no limit.
return The split() breaks the string at the separator and returns a list of strings.

If no separator is defined when you call upon the function, whitespace will be used by default. In
simpler terms, the separator is a defined character that will be placed between each variable. The
behavior of split on an empty string depends on the value of sep. If sep is not specified, or specified
as None, the result will be an empty list. If sep is specified as any string, the result will be a list
containing one element which is an empty string .

Splitting String by space

The split() method in Python without an argument splits on whitespace.

example

str = "This is a test"


print(str.split())
output
['This', 'is', 'a', 'test']

Splitting on first occurrence

In the following example, it will Split by first 2 whitespace only.

example

str = "This is a test"


print(str.split(" ",2))
output

['This', 'is', 'a test']

Splitting lines from a text file in Python

The following Python program reading a text file and splitting it into single words in python

example

with open("my_file.txt", "r") as my_file:


for line in my_file:
str = line.split()
print(str)

Splitting String by newline(\n)

str = "This \nis \na \ntest"


print(str)
print("\nAfter Split\n")
print(str.split())
output

This
is
a
test
After Split
['This', 'is', 'a', 'test']

Splitting String by tab(\t)

str = "This \tis \ta \ttest"


print(str)
print("\nAfter Split\n")
print(str.split())
output

This is a test
After Split
['This', 'is', 'a', 'test']

Splitting String by comma(,)

str = "This,is,a,test"
print(str.split(","))
output

['This', 'is', 'a', 'test']

Split string with multiple delimiters

In this case Python uses Regular Expression.

example

import re
str = "This,isa;test"
print(re.split(",;",str))
output

['This', 'is', 'a', 'test']

Split a string into a list

The following Python program split a string to a List.

example

str = "This is a test"


lst = str.split()
for st in lst:
print(st)
output

This
is
a
test

maxsplit parameter

Split the string into a list with max 2 items

numbers = "one two three four five six"


result = numbers.split(" ",2)
print (result)
output

['one', 'two', 'three four five six']

In the above program maxsplit is 2, the first two string are split and rest of them are in a same
string.

Split a string into array of characters

characters = "abcdef"
result = list(characters)
print (result)
output

['a', 'b', 'c', 'd', 'e', 'f']

Python split() using substring

Extact a string after a specific substring.

In the above example, you can see the split() function return next part of a string using a specific
substring.
Here, you can see the split() function return the previous part of the string using a specific
substring.

Python File Methods

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

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

Learn more about the file object in our Python File Handling Tutorial.

This chapter covers all the basic I/O functions available in Python. For more functions, please
refer to standard Python documentation.
Printing to the Screen
The simplest way to produce output is using the print statement where you can pass zero or
more expressions separated by commas. This function converts the expressions you pass into a string
and writes the result to standard output as follows −
#!/usr/bin/python

print "Python is really a great language,", "isn't it?"


This produces the following result on your standard screen −
Python is really a great language, isn't it?
Reading Keyboard Input
Python provides two built-in functions to read a line of text from standard input, which by
default comes from the keyboard. These functions are −
• raw_input
• input

The raw_input Function


The raw_input([prompt]) function reads one line from standard input and returns it as a string
(removing the trailing newline).
#!/usr/bin/python

str = raw_input("Enter your input: ")


print "Received input is : ", str
This prompts you to enter any string and it would display same string on the screen. When I
typed "Hello Python!", its output is like this −
Enter your input: Hello Python
Received input is : Hello Python
The input Function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated result to you.
#!/usr/bin/python

str = input("Enter your input: ")


print "Received input is : ", str
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]

Opening and Closing Files


Until now, you have been reading and writing to the standard input and output. Now, we will
see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You
can do most of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to call other support
methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
• file_name − The file_name argument is a string value that contains the name of the
file that you want to access.
• access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given below
in the table. This is optional parameter and the default file access mode is read (r).
• buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the
buffering value as an integer greater than 1, then buffering action is performed with
the indicated buffer size. If negative, the buffer size is the system default(default
behavior).
Here is a list of the different modes of opening a file −

Sr.No. Modes & Description

1
r
Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

2
rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.

3
r+
Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

4
rb+
Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.

5
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

6
wb
Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.

7
w+
Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

8
wb+
Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.

9
a
Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.

10
ab
Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

11
a+
Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.

12
ab+
Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.

The file Object Attributes


Once a file is opened and you have one file object, you can get various information related to
that file.
Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

1
file.closed
Returns true if file is closed, false otherwise.

2
file.mode
Returns access mode with which file was opened.

3
file.name
Returns name of the file.

4
file.softspace
Returns false if space explicitly required with print, true otherwise.

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another
file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close()
Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file


fo.close()
This produces the following result −
Name of the file: foo.txt
Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how
to use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can
have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file


fo.close()
The above method would create foo.txt file and would write given content in that file and finally it
would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings
can have binary data. apart from text data.
Syntax
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as much as
possible, maybe until the end of file.
Example
Let's take a file foo.txt, which we created above.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is

File Positions
The tell() method tells you the current position within the file; in other words, the next read or
write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the
number of bytes to be moved. The from argument specifies the reference position from where the
bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the
current position as the reference position and if it is set to 2 then the end of the file would be taken as
the reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str

# Check current position


position = fo.tell()
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is
Current file position : 10
Again read String is : Python is

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.
The 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 the example to rename an existing file test1.txt −
#!/usr/bin/python
import os

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


os.rename( "test1.txt", "test2.txt" )
The 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 the example to delete an existing file test2.txt −
#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")

The mkdir() Method


You can use the mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method which contains the name of the directory
to be created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os

# Create a directory "test"


os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory.
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")
The getcwd() Method
The getcwd() method displays the current working directory.
Syntax
os.getcwd()
Example
Following is the example to give current directory −
#!/usr/bin/python
import os

# This would give location of the current directory


os.getcwd()
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
Syntax
os.rmdir('dirname')
Example
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name
of the directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os

# This would remove "/tmp/test" directory.


os.rmdir( "/tmp/test" )

File & Directory Related Methods


There are three important sources, which provide a wide range of utility methods to handle
and manipulate files & directories on Windows and Unix operating systems. They are as follows −
• File Object Methods: The file object provides functions to manipulate files.
• OS Object Methods: This provides methods to process files as well as directories.
Table of Contents

•File Positions
o tell():
o seek():
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 :
"""

Author : ITVoyagers (https://itvoyagers.in/)

Date :23rd December 2018

Description : Program to use of tell()

"""

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

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

Author : ITVoyagers (https://itvoyagers.in/)

Date :23rd December 2018

Description : Program to use of seek()

"""

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

Python Delete File


Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example

Remove the file "demofile.txt":

import os
os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Example

Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder
To delete an entire folder, use the os.rmdir() method:

Example

Remove the folder "myfolder":

import os
os.rmdir("myfolder")
Note: You can only remove empty folders.
While working on projects, many times there are so many demo files or directories which you
have to remove because they are not required anymore while cleaning your code base. So, every
programmer needs to know how to delete a file in python. We will explain different ways to delete
files in directories.

In python following modules enable you to perform this type of task:

1. Import os: Os module allows us to use operating system-dependent functionalities.


2. From pathlib import Path: It is similar to the OS module only difference is in this we create a
Path object for a particular file to pass it in function.
3. Import shutil: Shutil is a high-level module for file operations. On individual files and sets of
files, you can carry out operations like copying and removing.

The main difference between the OS module and the Shutil module is that in the OS module, it is
necessary that the directory you want to delete should be empty, but this is not the case in shutil
module, it can delete the whole directory with its contents.

It is a best practice to first check for the existence of a file or folder before deleting it. After that
perform the action to avoid errors. You can check for the file's existence using the following
commands:

• os.path.isfile("/path/to/file")
• Use exception handling (Try - Except block)
• os.path.exists

Note: The file might be deleted or altered between the two lines, that's why exception handling is
advised rather than checking.

How to Delete a File in Python?


Let's now look at 5 different methods to remove a file from a directory using python:

Method 1) os.remove(file_path)
The os.remove(path) function is used to delete a file from the file system whose path is
passed. The path argument is a string that specifies the path of the file that you want to delete. If the
file exists, it will permanently remove it. If it doesn't, it throws a FileNotFoundError exception.

Hence, to avoid the error we always prefer to check for file existence.

Example:

import os
from pathlib import Path
import touch
myfile = "favtutor.txt"
Path(myfile).touch() #creating a new empty file
print("Files in a directory -->",os.listdir())
print("We can see a file created succesfully")
print("-----------------------------------------------------")
# If file exists, delete it.
if os.path.isfile(myfile):
os.remove(myfile)
print("Favtutor file deleted using remove() function")
print("Current files in directory -->",os.listdir())
print("-----------------------------------------------------")
else:
# If it fails, inform the user.
print("Error: %s file not found" % myfile)

Output:

Files in a directory --> ['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
We can see a file created succesfully
-----------------------------------------------------
Favtutor file deleted using remove() function
Current files in directory --> ['demo.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
-----------------------------------------------------

Note that If any files are once deleted using python, They will be deleted permanently. So, be
cautious!

Method 2) os.rmdir(directory_path)
The os.rmdir(directory_path) function is used to remove an empty directory from the file
system. The "rmdir" means to remove the directory. If the directory specified by directory_path
exists and is empty, this function will delete it. If it is not empty, the function will raise an OSError
exception with the message "Directory not empty".

Keep in mind that if the directory is the same as your python program you can pass the
relative path to it otherwise you have to pass the full path of the directory you want to delete inside
the function.

Example:

import pathlib
path="Text_files" # specifiing new folder name

if not os.path.exists(path): # checking for folder existance


# creating a new folder
os.makedirs(path)

# fetching the working directory path


rootdir=os.getcwd()
#loop to iterate working directory files and subdirectory
for root, dirs, files in os.walk(top=rootdir, topdown=False):
for name in dirs:
dir_path=os.path.join(root, name)
print("Subdirectory",dir_path)
print("We can see a folder created succesfully with name Text_files")
print("-----------------------------------------------------")
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
new=os.path.join(dir_path,myfile)
Path(new).touch()
print("Files in a directory -->",os.listdir())

# Try to delete the empty folder


# checking for folder availaibility using try and except block
try:

os.rmdir(dir_path)
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:

print("Error: %s - %s." % (e.filename, e.strerror))


print("-----------------------------------------------------")

Output:

Subdirectory f:\projects\Favtutor\Text_files
We can see a folder created succesfully with name Text_files
-----------------------------------------------------
Files in a directory --> ['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv',
'Text_files']
Error: f:\projects\Favtutor\Text_files - The directory is not empty.
-----------------------------------------------------

As we have created a new file named “Favtutor” inside our newly created subdirectory,
rmdir() function fails to delete the directory, giving us the error stating that the folder is not empty.
Now let's try deleting the folder after first deleting the file so that our directory is empty.

try:
os.remove(new)
print(new,"Favtutor file deleted using remove() function")
os.rmdir()
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:

print("Error: %s - %s." % (e.filename, e.strerror))


print("-----------------------------------------------------")

Output:

f:\projects\Favtutor\Text_files\favtutor.txt Favtutor file deleted using remove() function


No subdiretectory
folder deleted succesfully
-----------------------------------------------------

Now, as the directory was empty, rmdir() method deleted the directory successfully.

Method 3) shutil.rmtree(path[, ignore_errors[, onerror]])


The shutil.rmtree(path) function is used to remove a directory and all of its contents,
including all subdirectories and files. The ignore_errors is an optional Boolean argument to whether
or not to ignore any errors occurred during the deletion process. So, a major drawback is that you
cannot delete a single file using it.

As in the above example we faced the issue of the directory not being empty, we can use
shutil() method in place of rmdir() to delete the directory completely without any error. The code
will have just a few slight changes as below:

Example:

import pathlib
import shutil
path="Text_files" # specifiing new folder name

if not os.path.exists(path): # checking for folder existance


# creating a new folder
os.makedirs(path)

# fetching the working directory path


rootdir=os.getcwd()
#loop to iterate working directory files and subdirectory
for root, dirs, files in os.walk(top=rootdir, topdown=False):
for name in dirs:
dir_path=os.path.join(root, name)
print("Subdirectory",dir_path)
print("We can see a folder created succesfully with name Text_files")
print("-----------------------------------------------------")
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
new=os.path.join(dir_path,myfile)
Path(new).touch()

print("favtutor.txt file created inside Text_files directory")


print("-----------------------------------------------------")

# Try to delete the empty folder


# checking for folder availaibility using try and except block
try:
shutil.rmtree(path)
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("We can see a folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:

print("Error: %s - %s." % (e.filename, e.strerror))


print("-----------------------------------------------------")
Output:

Subdirectory f:\projects\Favtutor\Text_files
We can see a folder created succesfully with name Text_files
-----------------------------------------------------
favtutor.txt file created inside Text_files directory
-----------------------------------------------------
No subdiretectory
We can see a folder deleted succesfully
-----------------------------------------------------
Method 4) pathlib.Path.unlink(missing_ok=False)
The pathlib.Path.unlink() method operates on a Path object that represents the path of the file
that you want to delete. If the file specified by the Path object exists, the unlink() method will delete
it. If missing_ok parameter is false (default value), FileNotFoundError is raised if the path does not
exist. If it is true, FileNotFoundError exceptions will be ignored.

You can check your current working directory with “Path.cwd”.

Example:

import pathlib
import os
path_object = Path(".")
print(type(path_object))
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
Path(myfile).touch()
print("favtutor.txt file created")
print(os.listdir())
print("-----------------------------------------------------")
file = pathlib.Path("favtutor.txt")
file.unlink(missing_ok=False)
print(os.listdir())
print("favtutor.txt file deleted")

Method 5) pathlib.Path.rmdir()
It helps us to remove an empty directory. You need to first select the Path() for the empty
directory, and then call rmdir() method on that path. It will check the folder size. If it's 0 byte i.e.
empty, the will be deleted successfully else throws an error. This is a good way to delete empty
folders without any fear of losing actual data.

It is similar to os.rmdir() method only way of writing the syntax is different, You can just replace the
os.rmdir(dir_path) line with this function.

One Mark Questions

1. To open a file c:\scores.txt for reading, we use _____________


a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\\scores.txt”, “r”)

2. To open a file c:\scores.txt for writing, we use ____________


a) outfile = open(“c:\scores.txt”, “w”)
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

3. To open a file c:\scores.txt for appending data, we use ____________


a) outfile = open(“c:\\scores.txt”, “a”)
b) outfile = open(“c:\\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)

4. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned

5. To read two characters from a file object infile, we use ____________


a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

6. To read the entire remaining contents of the file as a string from a file object infile, we use
____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

7. What will be the output of the following Python code?

1. f = None
2. for i in range (5):
3. with open("data.txt", "w") as f:
4. if i > 2:
5. break
6. print(f.closed)

a) True
b) False
c) None
d) Error

8. To read the next line of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

9. To read the remaining lines of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()

10. The readlines() method returns ____________


a) str
b) a list of lines
c) a list of single characters
d) a list of integers

11. In file handling, what does this terms means “r, a”?
a) read, append
b) append, read
c) write, append
d) none of the mentioned

12. What is the use of “w” in file handling?


a) Read
b) Write
c) Append
d) None of the mentioned

13. What is the use of “a” in file handling?


a) Read
b) Write
c) Append
d) None of the mentioned

14. Which function is used to read all the characters?


a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()

15. Which function is used to read single line from file?


a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()

16. How do you delete a file?


a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)

17. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned

18. What happens if no arguments are passed to the seek function?


a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error

19. How do you delete a file?


a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)

20. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0)
b) fp.seek(offset, 1)
c) fp.seek(offset, 2)
d) none of the mentioned

5-marks

1. How to read, write and append in a file in Python?


2. Types of file modes and attributes of file object in Python
3. File Systems and File Handling in Python
4. .reStructuredText | .rst file to HTML file using Python for Documentations
5. Python - Copy contents of one file to another file
6. Python program to reverse the content of a file and store it in another file
7. Create a GUI to convert CSV file into excel file using Python
8. Python - Get file id of windows file
9. How to save file with file name from user using Python?
10. How to convert PDF file to Excel file using Python?
11. How to convert CSV File to PDF File using Python?
12. How to create a duplicate file of an existing file using Python?
13. How to open and close a file in Python
14. How to open a file using the with statement
15. reStructuredText | .rst file to HTML file using Python for Documentations
16. Python - Copy contents of one file to another file
17. Python program to reverse the content of a file and store it in another file
18. Create a GUI to convert CSV file into excel file using Python
19. Python - Get file id of windows file
20. How to save file with file name from user using Python?

10- Marks

1.Python | Append String to list


2.Python | Append suffix/prefix to strings in list
3.Python - Append Missing elements from other List
5.Python - Append List every Nth index
6.Python - Append given number with every element of the list
7.Append list of dictionary and series to a existing Pandas DataFrame in Python
8.Python | Perform append at beginning of list
9.numpy.append() in Python
10.append() and extend() in Python

….……………………………………..UNIT -5 Completed…………………………………………

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy