Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PYTHON Full Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 241

PYTHON

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

UNIT III - Functions:


Function Definition – Function Call – Variable Scope and its Lifetime-Return
Statement. Function Arguments: Required Arguments, Keyword Arguments, Default
Arguments and Variable Length Arguments Recursion. Python Strings: String
operations- Immutable Strings - Built-in String Methods and Functions - String
Comparison. Modules: import statement- The Python module – dir() function –
Modules and Namespace – Defining our own modules.

UNIT IV - Lists:
Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic list
operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting
Elements in a tuple – Nested tuples– Difference between lists and tuples. Dictionaries:
Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary
Functions and Methods - Difference between Lists and Dictionaries.

UNIT V - Python File Handling:


Types of files in Python - Opening and Closing 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.
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:
 ABC language.
 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.

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.
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 LITERAL:

TYPES OF PYTHON LITERAL:

A literal in Python is a way to represent a fixed value or raw data in the source code. It directly
appears in the program and does not change during the execution of a program.

Literals can be either numbers, text, boolean, or any other form of data.

In Python program, we use literals to create fixed values that are assigned to variables, constants,
used in expressions, or passed to functions.
For example, suppose we want to setting a variable with a specific value in a Python program. We
will write the code for it as:
x = 10
This statement creates an integer object containing a literal value 10. Literal means simply a value.
Some other examples of literal in Python are 100, x, 2.25, “Hello”, ‘World’, True, False, and so on.

TYPES OF LITERALS IN PYTHON LANGUAGE

Literals can be any of the primitive data types in Python language. The way of using literals depends
on its type. The various types of literals used in the Python program are as follows:
 String literals
 Numeric literals
 Boolean literals
 Literal Collections
 Special Literals

Let’s look at the following diagrammatic representation of the classification of Python literals.
String Literals
A string literal in Python is a consecutive sequence of characters used to store and represent
messages, heading, and other text-based information.
It is enclosed within a pair of double quotation marks and single quotation marks. Both are
applicable to define the string literals.
“Hello”, ‘World’, “123”, ‘The area of rectangle is: ‘, etc are some examples of string literals. We use
quotation marks to start and end the string.
Strings in Python are immutable, meaning that when we perform an operation on strings, the Python
interpreter always creates a new string object in the memory, rather than mutating an existing string
object.
String object provides several methods in Python that we will gain knowledge in the further tutorial.
Types of Strings
Python language supports two types of string objects.
1) Single-line String: A string created in a single line is called single-line string. An example of a
single-line string object is as below:
single_line_string = ‘Scientech Easy’ # Here, literal is Scientech Easy.
2) Multi-line String: A piece of statement written in multiple lines is called multiple lines string. In
Python, there are two ways to create multi-line string objects.
a) Adding a black slash (\) at the end of each line. An example of it is:
multi_line_string = 'Welcome \
to \
Scientech Easy'
print(multi_line_string)
Output:
Welcome to Scientech Easy
b) We can also create a multi-line string literal using triple quotation marks. An example of it is as
below:
multi_line_string = '''Welcome \
to \
Scientech Easy, \
Dhanbad'''
print(multi_line_string)
Output:
Welcome to Scientech Easy, Dhanbad
Numeric literals
Numeric literals in Python consists of numbers or digits from 0 to 9. They may be preceded by a
positive (+) or negative (-) sign.
All numeric literals in Python are immutable (unchangeable) objects, meaning that when we perform
an operation on a number object, the Python interpreter always creates a new number object.
Operation performed on numbers are called arithmetic operations.We can classify numeric literals in
Python into three types that are as follows:
 Integer literals
 Floating point literals
 Complex literals
Integer literals in Python
We know an integer is a whole number without any decimal point. It comprises a consecutive
sequence of digits, from (0 to 9). An integer can be positive or negative. An integer literal comes into
a different number system:
 Decimal literal (base 10)
 Octal literal (base 8)
 Hexadecimal literal (base 16)
a) Decimal literal: A decimal literal is a consecutive sequence of digits, from (0 to 9) in which the
first digit is nonzero. It is the most commonly used number system in any programming language.
If a decimal literal consists of two or more digits, the first digit must be some other digit than zero
because the Python interpreter will consider it as an octal number. Some examples of decimal literals
are 10, 30, 33, 676, 20,000, etc.
b) Octal literal: An octal literal consists of 0, followed by the sequence of any of the digits from 0 to
7. The first digit must be 0 in order to identify as an octal literal. For example: 01, 025, 02799, etc.
c) Hexadecimal literal: This literal comprises any of the digits from 0 to 9 and letters from A to F,
representing decimal values from 10 to 15. A hexadecimal integer literal starts with either 0x or 0X.
For example: 0x124, 0X12345, 0x10,000.
Rules for creating integer literals
The following are the rules for creating integer literals:
a) Python does not allow to use commas, or blank spaces in an integer literal. Some examples of
valid integer literals are 20, 40, 140, 1990, etc. Invalid integer literals are 20,5; 30 50, etc.
b) Integer literals may be positive or negative. If no sign precedes an integer literal, Python considers
it as positive. Some example of valid integer literals are +20; -40; 130; -1999. Invalid integer literals
are 20-5; 0x-120.
c) Python does not allow to have a decimal point in integer literals. Some of invalid integer literals
having decimal point are 30.5; 40.50; 0x4.25.
d) Integer literals must contain at least one digit, for example, 0.
e) The value of an integer literal should lie within the range of integers.
 Note that the print() function always outputs integer using decimal representation, even if they
are specified as octal or hexadecimal. The following example code shows the output 50 in three
forms:
x = 50 # Decimal integer
y = 0o62 # Octal integer
z = 0x32 # Hexadecimal integer
print("Decimal literal representation: ", x)
print("Octal literal representation: ", y)
print("Hexadecimal representation: ", z)
Output:
Decimal literal representation: 50
Octal literal representation: 50
Hexadecimal representation: 50
Floating-point literals in Python
A floating-point literal is a real number that contains a decimal point (.) or exponent sign or both,
differentiating them from integer literals. We can express them in either standard or scientific
notation, which is explained in the below:
a) Standard notation: In this notation, the floating point numbers contain an integer part or fractional
part with a decimal point in between two parts.
For example: 15.5, -10.50, 333.999, 9.0, -1234.567, and so on. The following are the general rules
for creating floating point literals in standard notation:
1. A decimal point must be present. Valid examples are 20.30, -150, 0.9999, etc.
2. We cannot use commas, or blanks with real literals.
3. A floating-point literal can be positive or negative. If any sign does not precede a literal, then the
interpreter will consider it as a positive number. For example: +2734.365, 234.55, -1234.55, and so
on.
b) Scientific notation: In scientific notation, a number contains two parts such as mantissa and
exponent. The mantissa part represents the floating point number and the exponent part specifies a
power of 10 by which the number is to be multiplied.
The letter E or e separates the mantissa and exponential portion of a number. For instance, we can
represent a number 24.55 in the exponential form as 2.455e2 (i.e. 2.455*10^2).
Here, the number 2.455 specifies the mantissa part and the part after the letter e specifies the
exponent part which has a base value 10.
In general, we use exponential form to represent the large numbers in order to writing large number
of 0s in a number. For instance, 5,000,000 can be written as 5.0e6.
Rules for creating floating point literals in scientific notation
There are the following rules for creating floating point literals in scientific notation. They are:
1. The mantissa part can be in integer or decimal form. A positive or negative sign can precede it.
The default sign is positive. For example, we can write 25.5 as 2.55e1 or 255e-1, or 0.255e2.
2. The exponent part must contain at least one digit, which should be a positive or negative integer.
The default sign is +ve. Valid examples are 2.32e+1; 234e-1. Invalid examples are 2.0e; -121e;
+1260e.
3. Spaces are not allowed in the mantissa part and in the exponent part. For instance, 5 5.44e-5, 525,
6e-6 are invalid.
4. We can write the letter e in both uppercase or lowercase. For example, 5.2e7, 1.3E7.
5. We can leave out the decimal point if we include the exponent part. For example, we can represent
0.95 as 95e-2.
Note that the print() function always outputs integer floating-point numbers. Even if they are
specified in the exponential form. Look at the following example code of Python floating point
literals.
x = 75e-2
y = 0.75
print(x)
print(y)
Output:
0.75
0.75

Complex literal

A complex number comprises two floating-point values, one each for the real and imaginary. A
complex literal is represented by (a + bj).
Here, a is a real part and the b with j is the imaginary or complex part. The letter j represents the
square root of -1. In mathematics, we use the letter i. An example code of it is below.
# complex literal
a = 5 + 10j
b = 2j
print(a)
print(b)
Output:
(5+10j)
2j
Boolean literals:

A boolean literal is a logical value that can have any of the two values: True or False. True represents
the value 1 whereas False represents the value 0.

We use boolean literal in certain operations in which need a boolean value. We use boolean value to
test whether a condition is true or false. Let’s take an example based on it.
# boolean literals
a = (9 == 9)
b = (5 == False)
c = True + 5
d = False + 5

print("a is ", a)
print("b is ", b)
print("c is ", c)
print("d is ", d)
Output:
a is True
b is False
c is 6
d is 5
You can observe in the above example, we have used boolean literals for numerical comparison.
Based on the conditions, we received the outputs True and False, respectively.
Special literals in Python:
Python language contains only one special literal, i.e., None. It is a special constant in Python that
specifies the null value or the absence of a value. We use None to specify a field that is not
constructed. We also use None at the end of lists in Python. Let’s take an example on it.
# Special literals
a = None
print(a)
Output:
None
You must make a note that None does not imply False, 0, or an empty list, dictionary, string, and so
on.
Collection literals in Python:

A collection literal is a syntactic representation that is used to work with more than one value.
Python language provides the four types of collection literal tokens, such as List, Tuple, Dictionary,
and Set. Let’s understand each one by one.
List literals
A list is a collection of mutable data or values of different types. To create a list in Python, place data
or values in within square brackets ([ ]) and separating them by commas (,).
You can consider the Python lists similar to arrays in C, C++, or Java. To declare a list in Python, the
syntax is as:
<name of list> = [ <value1>, <value2>, <value3>, . . . . ]
Let’s take an example based on it.
# List literals
address = ['Scientech Easy', 'Joraphatak Road', 'Dhanbad']
print(address)
Output:
['Scientech Easy', 'Joraphatak Road', 'Dhanbad']
Let’s take another example in which we will assign the first 10 natural numbers and print the
numbers in a list called num.
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(num)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Dictionary Literals
Python dictionary is a collection of data that stores value in a key-value pairs. They are enclosed in
curly braces ({ }) and separated by the commas (,).
Dictionary literals in Python are mutable (changeable) and can also contain different types of data or
values. Let’s take an example based on it.
# Dictionary literals
fruits_dict = {'a': 'apple',
'o': 'orange',
'b': 'banana'}
print(fruits_dict)
Output:
{'a': 'apple', 'o': 'orange', 'b': 'banana'}
Tuple Literals
Tuple in Python is a collection of different data-type, similar to a list. It is immutable, which means
we cannot change it after creation. It performs the same operation as a list does.
The parentheses ( ( ) ) enclose it and the comma separates each element of tuples. Below is an
example code of tuple literals.
# tuple literals
even_numbers = (2, 4, 6, 8, 10, 12)
vowels = ('a','e','i','o','u')
direction = ('North', 'South', 'East', 'West')
print(even_numbers)
print(vowels)
print(direction)
Output:
(2, 4, 6, 8, 10, 12)
('a', 'e', 'i', 'o', 'u')
('North', 'South', 'East', 'West')
Set Literals
Set literals in Python are a well-defined collection of unordered data that cannot be changed. The
elements of a set are enclosed within curly brackets separated by commas (,). Let’s see an example
code for it.
# Set literals
fruits = {'Apple', 'Mango', 'Banana', 'Orange', 'Grape'}
print(fruits)
Output:
{'Orange', 'Apple', 'Grape', 'Banana', 'Mango'}
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.
Some 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:
 Keywords.
 Identifiers.
 Literals.
 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.

 # Pyt
 False  await  else  import  pass
h on pr
o gram
 None  break  except  in  raise
t o de
m onstr
 True  class  finally  is  return
a te th
e appli
 and  continue  for  lambda  try
c ation
o  as  def  from  nonlocal  while f iske
y word
(  assert  del  global  not  with )
# imp
o  async  elif  if  or  yield rting
k eywo
rd 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 following sections categorize 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.
 A few terms mentioned in the segment following may be unfamiliar to you. They're explained
here, and you must understand what they mean before moving on:
 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.
The not Keyword
Truth table for or

X Y X or Y

True True True


True False True
False True True
False False False
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
var = 14
print("The value inside the inner function: ", var)
the_inner_function()
print("The value inside the outer function: ", var)
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 ):
^
Indentation Error:
expected an indented block after function definition on line 1
as shown, Indentation Error 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: Take Input from User

In Python, Using the input() function, we take input from a user, and using the print() function, we
display output on the screen. Using the input() function, users can give any information to the
application in the strings or numbers format.

Python Input() function

In Python 3, we have the following two built-in functions to handle input from a user and system.

1. input(prompt): To accept input from a user.


2. print(): To display output on the console/screen.

In Python 2,we can use the following two functions:

1. input([prompt])
2. raw_input([prompt])

The input() function reads a line entered on a console or screen by an input device such as a
keyboard, converts it into a string. As a new developer, It is essential to understand what is input in
Python.

What is the input?

The input is a value provided by the system or user. For example, suppose you want to calculate
the addition of two numbers on the calculator, you need to provide two numbers to the calculator. In
that case, those two number is nothing but an input provided by the user to a calculator program.
There are different types of input devices we can use to provide data to application. For example: –

 Stems from the keyboard: User entered some value using a keyboard.
 Using mouse click or movement: The user clicked on the radio button or some drop-down list
and chosen an option from it using mouse.

In Python, there are various ways for reading input from the user from the command line
environment or through the user interface. In both cases, the user is sending information using the
keyboard or mouse.

Python Example to Accept Input From a User

Let see how to accept employee information from a user.

 First, ask employee name, salary, and company name from the user
 Next, we will assign the input provided by the user to the variables
 Finally, we will use the print() function to display those variables on the screen.

# take three values from user


name = input("Enter Employee Name: ")
salary = input("Enter salary: ")
company = input("Enter Company name: ")
# Display all values on screenprint("\n")print("Printing Employee Details")print("Name", "Salary",
"Company")print(name, salary, company)

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.
Operator Syntax Working
** 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 (�.�.>,<,>=,<=)(i.e.>,<,>=,<=).
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
Precedence Operator Name
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 PART -
A
insert() Adds an element at the specified position
1. Is Python
case pop() Removes the element at the specified position sensitive
when
remove( Removes the first item with the specified value dealing
with )

reverse() Reverses the order of the list

sort() Sorts the list


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.

PYTHON SELECTION STATEMENTS

In Python, the selection statements are also known as decision making statements or branching
statements.
The selection statements are used to select a part of the program to be executed based on a condition.
Python provides the following selection statements.

 if statement
 if-else statement
 if-elif statement

if statement in Python

In Python, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then decides
the execution of a block of statements. If it is True, then the block of statements is executed and if it
is False, then the block of statements is ignored. The execution flow of if statement is as follows.

Syntax

if condition:

Statement_1

Statement_2

Statement_3

...
The general syntax of if statement in Python is as follows.

When we define an if statement, the block of statements must be specified using indentation only.
The indentation is a series of white-spaces. Here, the number of white-spaces is variable, but all
statements must use the identical number of white-spaces. Let's look at the following example
Python code.

Python code to illustrate if statement

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

if (num % 5 == 0):

print(f'Given number {num} is divisible by 5')

print('This statement belongs to if statement')

print('This statement does not belongs to if statement')

When we run the above code, it produces the output as follows.


In the above execution, the number 9 is not divisible by 5. So, the condition becomes False and the
condition is evaluated to False. Then the if statement ignores the execution of its block of statements.

IF-ELSE STATEMENT IN PYTHON:

In Python, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the given
condition then decides which block of statements to be executed based on the condition result. If the
condition is True, then the true block of statements is executed and if it is False, then the false block
of statements is executed.

The execution flow of if-else statement is as follows.

Syntax

if condition:

Statement_1

Statement_2

Statement_3

...

else:
Statement_4

Statement_5

...

The general syntax of if-else statement in Python is as follows.

In the above syntax, whenever the condition is True, the statements 1 2 and 3 are gets executed. And
if the condition is False then the statements 4 and 5 are gets executed. Let's look at the following
example of Python code.

Python code to illustrate if-else statement


# Python code for testing whether a given number is Even or Odd

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

if num % 2 == 0:

print(f'The number {num} is a Even number')

else:
print(f'The number {num} is a Odd number')

When we run the above code, it produces the output as Follows.

ELIF STATEMENT IN PYTHON:

In Python, When we want to test multiple conditions we use elif statement.

The general syntax of if-elif-else statement in Python is as follows.

Syntax
if condition_1:

Statement_1

Statement_2

Statement_3

...

elif condition_2:

Statement_4

Statement_5

Statement_6

...

else:

Statement_7

Statement_8

...

In the above syntax, whenever the condition_1 is True, the statements 1 2 and 3 are gets executed. If
the condition_1 is False and condition_2 is True then the statements 4, 5, and 6 are gets executed.
And if condition_1 nad Condition_2 both are False then the statements 7 and 8 are executed. Let's
look at the following example of Python code.
Python code to illustrate if-else statement
# Python code to illustrate elif statement

choice = input(f'Which game do you like, Press\nC - Cricket\nH - Hokey: ')

if choice == 'C':

print('You are a Cricketer!')

elif choice == 'H':

print('You are a Hockey player!')

else:
print('You are not interested in Sports')

When we run the above code, it produces the output as follows:

PYTHON NESTED IF STATEMENTS:


There may be a situation when you want to check for another condition after a condition resolves to
true. In such a situation, you can use the nested if construct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
Syntax
The syntax of the nested if...elif...else construct may be −
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Example
Live Demo
#!/usr/bin/python
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
print "Good bye!"
When the above code is executed, it produces following result −
Expression value is less than 200
Which is 100
Good bye!
PYTHON IF...ELIF...ELSE STATEMENTS:
An else statement can be combined with an if statement. An else statement contains the block of
code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else statement
following if.
Syntax:
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Flow Diagram
Example

#!/usr/bin/python

var1 = 100if var1:


print "1 - Got a true expression value"
print var1else:
print "1 - Got a false expression value"
print var1

var2 = 0if var2:


print "2 - Got a true expression value"
print var2else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
When the above code is executed, it produces the following result −
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
The elif Statement
The elif statement allows you to check multiple expressions for TRUE and execute a block of code
as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at
most one statement, there can be an arbitrary number of elif statements following an if.
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case as follows −

Example

#!/usr/bin/python
var = 100if var == 200:
print "1 - Got a true expression value"
print varelif var == 150:
print "2 - Got a true expression value"
print varelif var == 100:
print "3 - Got a true expression value"
print varelse:
print "4 - Got a false expression value"
print var
print "Good bye!"
When the above code is executed, it produces the following result −
3 - Got a true expression value
100
Good bye!
ITERATIVE STATEMENTS:
In programming, loops are used to repeat a block of code. For example, if we want to show a
message 100 times, then we can use a loop. It's just a simple example, we can achieve much more
with loops.
In the previous tutorial, we learned about Python for loop. Now we will learn about the while loop.
Python while Loop
Python while loop is used to run a block code until a certain condition is met.
The syntax of while loop is:
while condition:
# body of while loop
Here,
A while loop evaluates the condition
If the condition evaluates to True, the code inside the while loop is executed.
condition is evaluated again.
This process continues until the condition is False.
When condition evaluates to False, the loop stops.

Flowchart of Python while Loop


Flowchart of while Loop
Example: Python while Loop
# program to display numbers from 1 to 5
# initialize the variable
i=1
n=5
# while loop from i = 1 to 5while i <= n:
print(i)
i=i+1
HOW TO USE FOR LOOP IN PYTHON:
Python for loop iterate over the sequences. It repeats the piece of code n number of times. Consider
the following flowchart of for loop.
Flowchart

Python for loop can be used in two ways.


o Using Sequence
o Using range() function
Using Sequence
The sequence is referred to as list, set, string, tuple, and dictionary in Python. We can extract the
elements of the sequence using for loop. Below is the syntax for loop.
Syntax:
for iterating_var in sequence:
statement(s)
Let's understand the following example.
Example - 1
list1 = [10, 20, 30, 40, 50, 60]
for i in list1:
print(i)
Output:

10

20

30

40

50

60
Example - 2
str = "JavaTpoint"
for i in str:
print(i)
Output:

o
i

t
Using the range() function
The range function() generates the sequence of the numbers. For example, if we execute
the range(5) and it will generate the 0 to 4. The syntax of the range() function is given below.
Syntax:
 range(start, stop, step-size)
 It accepts the three arguments.
 The start represents the beginning of the iteration.
 The stop indicates the end of for loop. It will iterate till stop-1.
 The step size skips the specific number of iteration. By default, the step size is 1.

Let's understand the following example.


Example - 1
for i in range(20):
print(i, end = ' ')
Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Example - 2 Traverse the List element using range() function
list = ['Peter', 'Joseph', 'Ricky', 'Devansh', 'Kevin']
for i in range(len(list)):
print("Hii",list[i])
Output:

Hii Peter

Hii Joseph

Hii Ricky

Hii Devansh

Hii Kevin
Explanation:
The len() function returns the length of the list. The range() got the number of elements in the list
and printed its elements.
PYTHON ELSE SUITE:
In Python, it is possible to use 'else' statement along with for loop or while loop in the form shown in
Table:
for with else syntax
for( var in sequence)
statementselse:
statements
while with else syntax
while( condition ):
statementselse:
statements
he else suite will be always executed irrespective of the statements in the loop are executed or not.
for i in range(5):
print("Yes") else: print("No")
Output:
Yes
Yes
Yes
Yes
Yes
No
It means, the for loop statement is executed and also the else suite is executed.
A Python program to search for an element in the list of elements.
group1 = [1,2,3,4,5]
search = int(input('Enter element to search:')) for element in group1:
if search == element: print('Element found in group')
break #come out of for loop else: print('Element not found in group1') #this is else suite
Write a python program to check whether given number is Prime number or not?
num = int(input("Enter a number: ")) if num > 1:
for i in range(2,num):
if (num % i) == 0: print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else: print(num,"is a prime number") else: print(num,"is not a prime number")
Write a python program to list of Prime numbers
lower = int(input("Enter starting number : "))
upper = int(input("Enter ending number: ")) for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,end='\t')

Python Nested Loops

Loops Inside Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)

JUMP STATEMENTS:
Break, Pass, and Continue statements are loop controls used in python. The break statement, as the
name suggests, breaks the loop and moves the program control to the block of code after the loop (if
any). The pass statement is used to do nothing.
Python break statement:
The break is a keyword in python which is used to bring the program control out of the loop. The
break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop
first and then proceeds to outer loops. In other words, we can say that break is used to abort the
current execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition. The
syntax of the break statement in Python is given below.
Syntax:
#loop statements
break;
Example 1 : break statement with for loop
Code
# break statement example
my_list = [1, 2, 3, 4]
count = 1
for item in my_list:
if item == 4:
print("Item matched")
count += 1
break
print("Found at location", count)
Output:

Item matched

Found at location 2
In the above example, a list is iterated using a for loop. When the item is matched with value 4, the
break statement is executed, and the loop terminates. Then the count is printed by locating the item.
Example 2 : Breaking out of a loop early
Code
# break statement example
my_str = "python"
for char in my_str:
if char == 'o':
break
print(char)
Output:

p
y

h
When the character is found in the list of characters, break starts executing, and iterating stops
immediately. Then the next line of the print statement is printed.
Example 3: break statement with while loop
Code
# break statement example
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
It is the same as the above programs. The while loop is initialised to True, which is an infinite loop.
When the value is 10 and the condition becomes true, the break statement will be executed and jump
to the later print statement by terminating the while loop.
Example 4 : break statement with nested loops
Code
# break statement example
n=2
while True:
i=1
while i <= 10:
print("%d X %d = %d\n" % (n, i, n * i))
i += 1
choice = int(input("Do you want to continue printing the table? Press 0 for no: "))
if choice == 0:
print("Exiting the program...")
break
n += 1
print("Program finished successfully.")
Output:
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.
There are two nested loops in the above program. Inner loop and outer loop The inner loop is
responsible for printing the multiplication table, whereas the outer loop is responsible for
incrementing the n value. When the inner loop completes execution, the user will have to continue
printing. When 0 is entered, the break statement finally executes, and the nested loop is terminated.

PYTHON CONTINUE STATEMENT


we'll look at how to use Python continue keyword to skip the remaining statements of the current
loop and go to the next iteration. Also, the difference between continue and pass keywords.
Application of the Continue Statement
In Python, loops repeat processes on their own in an efficient way. However, there might be
occasions when we wish to leave the current loop entirely, skip iteration, or dismiss the condition
controlling the loop. We use Loop control statements in such cases. The continue keyword is a loop
control statement that allows us to change the loop's control.
The continue Keyword:
In Python, the continue keyword return control of the iteration to the beginning of the Python for
loop or Python while loop. All remaining lines in the prevailing iteration of the loop are skipped by
the continue keyword, which returns execution to the beginning of the next iteration of the loop.
Both Python while and Python for loops can leverage the continue statements.
Example of Python Continue Statements in For Loop
Assume the following scenario: we want to develop a program that returns numbers from 10 to 20
but not 15. It is mentioned that we must perform this with a 'for' loop. Here's when the continue
keyword comes into play. We will execute a loop from 10 to 20 and test the condition that the
iterator is equal to 15. If it equals 15, we'll employ the continue statement to skip to the following
iteration displaying any output; otherwise, the loop will print the result.
The following code is an example of the above scenario:
Code
# Python code to show example of continue statement
# looping from 10 to 20
for iterator in range(10, 21):
# If iterator is equals to 15, loop will continue to the next iteration
if iterator == 15:
continue
# otherwise printing the value of iterator
print( iterator )
Output:
10
11
12
13
14
16
17
18
19
20
Now will repeat the above code, but this time with a string. We will take a string "Javatpoint" and
print each letter of the string except "a". This time we will use Python while loop to do so. Until the
value of the iterator is less than the string's length, the while loop will keep executing.
Code
# Creating a string
string = "JavaTpoint"
# initializing an iterator
iterator = 0
# starting a while loop
while iterator < len(string):
# if loop is at letter a it will skip the remaining code and go to next iteration
if string[iterator] == 'a':
continue
# otherwise it will print the letter
print(string[ iterator ])
iterator += 1
Output:
J
v
T
p
o
i
n
t
Python Continue vs. Pass
Usually, there is some confusion in the pass and continue keywords. So here are the differences
between these two.

Headings continue pass

Definition The continue statement is utilized to skip the The pass keyword is used when a
current loop's remaining statements, go to phrase is necessary syntactically to
the following iteration, and return control to be placed but not to be executed.
the beginning.

Action It takes the control back to the start of the Nothing happens if the Python
loop. interpreter encounters the pass
statement.

Applicatio It works with both the Python while and It performs nothing; hence it is a
n Python for loops. null operation.

Syntax It has the following syntax: -: continue Its syntax is as follows:- pass

Interpretati It's mostly utilized within a loop's condition. During the byte-compile stage, the
on pass keyword is removed.

Python Pass Statement:


In this tutorial, we will learn more about past statements. It is interpreted as a placeholder for future
functions, classes, loops, and other operations.
What is Python's Pass Statement?
The pass statement is also known as the null statement. The Python mediator doesn't overlook a
Remark, though a pass proclamation isn't. As a result, these two Python keywords are distinct.
We can use the pass statement as a placeholder when unsure of the code to provide. Therefore, the
pass only needs to be placed on that line. The pass might be utilized when we wish no code to be
executed. We can simply insert a pass in cases where empty code is prohibited, such as in loops,
functions, class definitions, and if-else statements.
Syntax

Keyword:
pass
Ordinarily, we use it as a perspective for what's to come.
Let's say we have an if-else statement or loop that we want to fill in the future but cannot. An empty
body for the pass keyword would be grammatically incorrect. A mistake would be shown by the
Python translator proposing to occupy the space. As a result, we use the pass statement to create a
code block that does nothing.
An Illustration of the Pass Statement
Code
# Python program to show how to use a pass statement in a for loop
'''''pass acts as a placeholder. We can fill this place later on'''
sequence = {"Python", "Pass", "Statement", "Placeholder"}
for value in sequence:
if value == "Pass":
pass # leaving an empty if block using the pass keyword
else:
print("Not reached pass keyword: ", value)
Output:
Not reached pass keyword: Python
Not reached pass keyword: Placeholder
Not reached pass keyword: Statement
The same thing is also possible to create an empty function or a class.
Code
# Python program to show how to create an empty function and an empty class
# Empty function:
def empty():
pass
# Empty class
class Empty:
pass

PART - A(1 MARKS)

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

x = ['ab', 'cd']for i in x:
i.upper()print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned
Explanation: The function upper() does not modify a string in place, it returns a new string which
isn’t being stored anywhere.
8. What will be the output of the following Python code?
i = 1while True:
if i%3 == 0:
break
print(i)
i+=1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned
Explanation: SyntaxError, there shouldn’t be a space between + and = in +=.

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

i = 1while True:
if i%0O7 == 0:
break
print(i)
i += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned
Explanation: Control exits the loop when i becomes 7.

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

i = 5while True:
if i%0O11 == 0:
break
print(i)
i += 1
a) 5 6 7 8 9 10
b) 5 6 7 8
c) 5 6
d) error
Explanation: 0O11 is an octal number.
11. What will be the output of the following Python code?
i = 5while True:
if i%0O9 == 0:
break
print(i)
i += 1
a) 5 6 7 8
b) 5 6 7 8 9
c) 5 6 7 8 9 10 11 12 13 14 15 ….
d) error
Explanation: 9 isn’t allowed in an octal number.
12. What will be the output of the following Python code?
i = 1while True:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
Explanation: The loop does not terminate since i is never an even number.
13. What will be the output of the following Python code?
i = 2while True:
if i%3 == 0:
break
print(i)
i += 2
a) 2 4 6 8 10 …
b) 2 4
c) 2 3
d) error
Explanation: The numbers 2 and 4 are printed. The next value of i is 6 which is divisible by 3 and
hence control exits the loop.
14. What will be the output of the following Python code?
i = 1while False:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 3 5 7 …
c) 1 2 3 4 …
d) none of the mentioned
Explanation: Control does not enter the loop because of False.
15. What will be the output of the following Python code?
True = Falsewhile True:
print(True)
break
a) True
b) False
c) None
d) none of the mentioned
Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.
16. 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
Explanation: We can write if/else in one line. For eg i = 2 if a > 5 else 0.
17. else if Statement in Python
a) if a>=2 :
b) if (a >= 2)
c) if (a => 22)
d) if a >= 22
Explanation:- If statement always end with colon (:)
18. 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
19. What is the output of the given below program?
if 1 + 3 == 7:
print("Hello")else:
print("Know Program")
a) Hello
b) Know Program
c) Compiled Successfully, No Output.
d) Error
The 1+3 = 4 which is not equal to 7 therefore else block will be executed.
20. What is the output of the given below program?
if 3 + 4 == 7:
print("Hi")else:
print("Know Program")print("Hello")
a) Hi
b) Know Program
c)
Hi
Hello
d)
Know Program
Hello
The 3+4 = 7 is equal to 7 therefore if block will be executed. The remaining statement after if-else
block also will be executed.

21) Find the output of the given Python program?


a = 25if a < 15:
print("Hi")if a <= 30:
print("Hello")else:
print("Know Program")
a) Hi
b) Hello
c) Know Program
d) Compiled Successfully, No Output.
Here 25 < 15 => false; therefore the if-block will not be executed. Next, 25 <= 30, condition
becomes true therefore if-block will be executed.
22) What is the output of the given below program?
a = 25if a > 15:
print("Hi")if a <= 30:
print("Hello")else:
print("Know Program")
a) Hi
b) Hello
c)
Hi
Hello
d) Hi
Know Program
e) Hello
Know Program
Here 25 > 15, condition is true therefore first if-statment will be executed. Next, 25 <= 30, condition
is true therefore second if-statement also will be executed.
23) Find the output of the given Python program?
a, b, c = 1, 3, 5if a > 0:
if b < 2:
print("Hi")
elif c > 3:
print("Hello")else:
print("Know Program")
a) Hi
b) Hello
c) Know Program
d) Compiled Successfully, No Output.
24) Find the output of the given Python program?
a, b, c = 1, 3, 5if a + b + c:
print("Hello")else:
print("Know Program")
a) Hello
b) Know Program
c) Compiled Successfully, No Output.
d) Error
25) What is the output of the given below program?
if a < b:
print("Hello")else:
print("Know Program")
a) Hello
b) Know Program
c) Compiled Successfully, No Output.
d) Error
The variables are not assigned with any value.
26) What is the output of the given below program?
a = b = trueif (a and b):
print("Hello")else:
print("Know Program")
a) Hello
b) Know Program
c) Compiled Successfully, No Output.
d) Error

PART - B(5 MARK)

1. What is branching statements. And explain nested if and if-elif-else.


2. Explain while loop and for loop in iterative concept
3. Differentiate between break and continue. Explain it.
4. Explain else suite in iterative model.
5. Differentiate between continue and pass
6. Draw the flow chart for elseif, nested if, if else.

PART - C(10 MARK)

1. Explain briefly about Jump statements.


2. Define and elaborate the function of iterative concepts.
3. What is branching statements and explain about all functions.
4. Write a program for break, continue and if else.

….…………………………UNIT - 2 COMPLETED………………………
UNIT - III
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.

FUNCTIONS
Python Functions
This tutorial will go over the 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
# An example Python Function
def function_name( parameters ):
# 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.

# Example Python Code for User-Defined function


def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(6)
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.

# Example Python Code for calling a function


# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)

# Calling the function we defined


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

Length of the string Python is: 6

Pass by Reference vs. Pass by Value


In the Python programming language, all parameters are passed by reference. It shows that if we
modify the worth of contention within a capability, the calling capability will similarly mirror the
change. For instance,
Code

# Example Python Code for Pass by Reference vs. Value


# defining the function
def square( item_list ):
'''''''This function will find the square of items in the list'''
squares = [ ]
for l in item_list:
squares.append( l**2 )
return squares
# calling the defined function
my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )
Output:
Squares of the list are: [289, 2704, 64]

Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no worth
is provided for the contention when the capability is called. The following example demonstrates
default arguments.
Code
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument

number 1 is: 30

number 2 is: 20

Passing two arguments


number 1 is: 50

number 2 is: 30

2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a capability
with watchword contentions, the client might tell whose boundary esteem it is by looking at the
boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the Python
translator will interface the furnished watchwords to connect the qualities with its boundaries. One
more method for utilizing watchwords to summon the capability() strategy is as per the following:
Code
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )
function( 50, 30)
# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:
Without using keyword

number 1 is: 50

number 2 is: 30

With using keyword

number 1 is: 30

number 2 is: 50

3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined positional
sequence. The number of arguments required in the method call must be the same as those provided
in the function's definition.
We should send two contentions to the capability() all put together; it will return a language structure
blunder, as seen beneath.
Code

# Python code to demonstrate the use of default arguments


# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 3
0
print( "Passing out of order arguments" )
function( 30, 20 )

# Calling function and passing only one argument


print( "Passing only one argument" )
try:
function( 30 )
except:
print( "Function needs two positional arguments" )
Output:
Passing out of order arguments

number 1 is: 30

number 2 is: 20

Passing only one argument

Function needs two positional arguments

4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However, we
need a capability. This can be accomplished with one of two types of characters:
"args" and "kwargs" refer to arguments not based on keywords.
To help you understand arguments of variable length, here's an example.
Code
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']

[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]

RETURN STATEMENT:
When a defined function is called, a return statement is written to exit the function and return the
calculated value.

Syntax:

return < expression to be returned as output >


The return statement can be an argument, a statement, or a value, and it is provided as output when a
particular job or function is finished. A declared function will return an empty string if no return
statement is written.
A return statement in Python functions is depicted in the following example.
Code
# Python code to demonstrate the use of return statements
# Defining a function with return statement
def square( num ):
return num**2
# Calling function and passing arguments.
print( "With return statement" )
print( square( 52 ) )
# Defining a function without return statement
def square( num ):
num**2
# Calling function and passing arguments.
print( "Without return statement" )
print( square( 52 ) )
Output:
With return statement

2704

Without return statement

None

The Anonymous Functions


Since we do not use the def keyword to declare these kinds of Python functions, they are unknown.
The lambda keyword can define anonymous, short, single-output functions.
Arguments can be accepted in any number by lambda expressions; However, the function only
produces a single value from them. They cannot contain multiple instructions or expressions. Since
lambda needs articulation, a mysterious capability can't be straightforwardly called to print.
Lambda functions can only refer to variables in their argument list and the global domain name
because they contain their distinct local domain.
In contrast to inline expressions in C and C++, which pass function stack allocations at execution for
efficiency reasons, lambda expressions appear to be one-line representations of functions.
Syntax
Lambda functions have exactly one line in their syntax:
lambda [argument1 [,argument2... .argumentn]] : expression
Below is an illustration of how to use the lambda function:
Code
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;
# Calling the function and passing values
print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:
Value of the function is : 50

Value of the function is : 90

Scope and Lifetime of Variables


A variable's scope refers to the program's domain wherever it is declared. A capability's contentions
and factors are not external to the characterized capability. They only have a local domain as a result.
The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same
as the lifespan of its internal variables. When we exit the function, they are taken away from us. As a
result, the value of a variable in a function does not persist from previous executions.
An easy illustration of a function's scope for a variable can be found here.

Code

# Python code to demonstrate scope and lifetime of variables

#defining a function to print a number.


def number( ):
num = 50
print( "Value of num inside the function: ", num)
num = 10
number()
print( "Value of num outside the function:", num)
Output:
Value of num inside the function: 50

Value of num outside the function: 10

Here, we can see that the initial value of num is 10. Even though the function number() changed the
value of num to 50, the value of num outside of the function remained unchanged.
This is because the capability's interior variable num is not quite the same as the outer variable
(nearby to the capability). Despite having a similar variable name, they are separate factors with
discrete extensions.
Factors past the capability are available inside the capability. The impact of these variables is global.
We can retrieve their values within the function, but we cannot alter or change them. The value of a
variable can be changed outside of the function if it is declared global with the keyword global.
Python Capability inside Another Capability
Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same
everywhere they are used in a programming language. They can be stored in built-in data structures,
used as arguments, and in conditional expressions. If a programming language treats functions like
first-class objects, it is considered to implement first-class functions. Python lends its support to the
concept of First-Class functions.
A function defined within another is called an "inner" or "nested" function. The parameters of the
outer scope are accessible to inner functions. Internal capabilities are developed to cover them from
the progressions outside the capability. Numerous designers see this interaction as an embodiment.

Code

# Python code to show how to access variables of a nested functions


# defining a nested function
def word():
string = 'Python functions tutorial'
x=5
def number():
print( string )
print( x )
number()
word()
Output:
Python functions tutorial

A return statement

A return statement ends the execution of a function, and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return
statement can return a value to the calling function.

Python return statement


Introduction
The Python return statement is used to return a value from a function. The user can only use the
return statement in a function. It cannot be used outside of the Python function. A return statement
includes the return keyword and the value that will be returned after that.
Syntax of return statement:
def funtion_name():
statements
return [expression]
Program 1
def adding(x, y):
i=x+y
return i
result = adding(16, 25)
print(f'Output of adding(16, 25) function is {result}')
Output

Function Arguments
Arguments and Parameters in Python
Be it any programming language, Arguments and Parameters are the two words that cause a lot of
confusion to programmers. Sometimes, these two words are used interchangeably, but actually, they
have two different yet similar meanings. This tutorial explains the differences between these two
words and dives deep into the concepts with examples.
Both arguments and parameters are variables/ constants passed into a function. The difference is that:
1. Arguments are the variables passed to the function in the function call.
2. Parameters are the variables used in the function definition.
3. The number of arguments and parameters should always be equal except for the variable
length argument list.

Example:

def add_func(a,b):
sum = a + b
return sum
num1 = int(input("Enter the value of the first number: "))
num2 = int(input("Enter the value of the second number: "))
print("Sum of two numbers: ",add_func(num1, num2))
Output:
Enter the value of the first number: 5
Enter the value of the second number: 2
Sum of two numbers: 7
Points to grasp from the Example:
1. (num1, num2) are in the function call, and (a, b) are in the function definition.
2. (num1, num2) are arguments and (a, b) are parameters.

Mechanism:
Observe that in the above example, num1 and num2 are the values in the function call with which we
called the function. When the function is invoked, a and b are replaced with num1 and num2, the
operation is performed on the arguments, and the result is returned.
Functions are written to avoid writing frequently used logic again and again. To write a general
logic, we use some variables, which are parameters. They belong to the function definition. When
we need the function while writing our program, we need to apply the function logic on the variables
we used in our program, called the arguments. We then call the function with the arguments.
Types of Arguments:
Based on how we pass arguments to parameters, arguments are of two types:
1. Positional arguments
2. Keyword arguments
o Given some parameters, if the respective arguments are passed in order one after the other,
those arguments are called the "Positional arguments."
o If the arguments are passed by assigning them to their respective parameters in the function
call with no significance to the passing order, they are called "Keyword arguments".

Example:
def details(name, age, grade):
print("Details of student:", name)
print("age: ", age)
print("grade: ", grade)
details("Raghav", 12, 6)
details("Santhosh", grade = 6, age = 12)
Output:
Details of student: Raghav
age: 12
grade: 6
Details of student: Santhosh
age: 12
grade: 6
Points to grasp from the Example:
First Function Call:
o The function has three parameters-name, age and grade. So, it accepts three arguments.
o In the first function call:

details("Raghav", 12, 6)
The arguments are passed position-wise to the parameters, which mean according to the passed
order:
o name is replaced with "Raghav."
o age is replaced with 12 and
o grade is replaced with 6
o In the first function call, the order of passing the arguments matter. The parameters accept the
arguments in the given order only.
o In the Second Function Call:

details("Santhosh", grade = 6, age = 12)


Here, the first argument, "Santhosh", is passed based on its position to name, and the next two
arguments are passed by assignment to their respective parameters. As you can observe, here, the
position didn't matter.
Important Point:
o Keyword arguments must always follow positional arguments. If not, Python will raise a
syntax error:

If we write: details("Santhosh", age = 6, 12)


details("Santhosh", age = 6, 12)
SyntaxError: positional argument follows keyword argument
Call by Value and Call by Reference:
This is the most important concept on arguments and parameters. Based on the type of arguments
passed to the parameters, there are two methods of invoking/ calling functions-Call by value and Call
by reference.
When the values of arguments are passed into parameters in the function, the values are copied into
parameters. This method is called "Call by value".
In this method, arguments and parameters are different and are stored in different memory locations.
o Changes done on parameters inside the function do not affect the arguments in the program
and vice versa.
o Java functions/ methods follow only Call by value.

When the addresses of the arguments are passed into parameters instead of values, this method of
invoking a function is called "Call by Reference".
o Both the arguments and parameters refer to the same memory location.
o Changes to the parameters (pointers) will affect the values of the arguments in the program.
o By default, C language follows Call by value, but using the indirection operator and pointers;
we can simulate Call by reference.

Which Method does Python Follow?


Python doesn't use Call by value or Call by reference. It follows a method called "Call by
assignment". In Python, every single entity is an object. Objects are divided into Mutable and
Immutable objects. What happens in Python when we assign a value to a variable is different from
other low-level languages like C or Java.
Suppose, in the statement:
a = 20
a is the variable, and 20 is the value assigned. Here in a memory location, 20 is saved, and a is the
name we're giving to the reference we're making to the memory location. Now, if we say:
a = 21
The name stops referring to the memory location with 20 and starts to refer to another memory
location with 21.
In other languages like C, variables are the memory locations that store the values.
Example:
In C:
#include<stdio.h>
int main()
{
int a;
a = 20;
printf("%p", (void*)&a);
a = 22;
printf("\n%p", (void*)&a);
}
Output:

000000000062FE1C

000000000062FE1C
In Python:
a = 20
print(id(a))
a = 21
print(id(a))
Output:

140714950863232

140714950863264
o As you can observe: In C, after reassigning the value, the variable is still in the same memory
location, while in Python, it refers to a different memory location. (id -> address in Python).
o But that's not all. There are other types of objects too.

Now comes the concept of Mutable and Immutable objects in Python.


Mutable and Immutable Objects in Python:
1. Mutable objects are those objects/ data types in Python that we can modify after creating
them Ex: Lists, Dictionaries, Sets
2. Immutable objects, on the other hand, are objects that can't be modified once created. Ex: int,
float, strings, tuples
Example:
Mutable Objects:
a = [23, 45, 89]
print(id(a))
a.append(49)
print(id(a))
Output:

2253724439168

2253724439168
Understanding:
A list is immutable, which means we can alter or modify it after creating it. As you can observe,
when created with the name a, it is saved in the address "2253724439168". Using append(), we
altered it by appending another value. It is still in the same memory location, meaning the same
object is modified.
Immutable Objects:

a = 20
print(id(a))
a += 23
print(id(a))
Output:

140714950863232

140714950863968
Understanding:
This is the case we discussed before in the tutorial. An int object is immutable, meaning we can't
modify it once created. You might wonder we still added 23 in the above code. Observe that the
object when created is not the same object after adding. Both are in different memory locations
which means they are different objects.
So, how are arguments passed to the parameters when a function is invoked?
With all the knowledge about assignment operation in Python:
1. The passing is like a "Call by Reference" if the arguments are mutable.
2. The passing is like "Call by Value" if the arguments are immutable.
Example:
def details(name, age, grade, marks):
marks.append(26)
name += " Styles"
print("Details of the student: ")
print("name: ",name)
print("age: ",age)
print("grade: ", grade)
print("marks: ", marks)
name = "Harry"
age = 15
grade = 10
marks = [25, 29, 21, 30]
details (name, age, grade, marks)
print(grade)
print(marks)
Output:

Details of the student:

name: Harry Styles

age: 15

grade: 10

marks: [25, 29, 2F1, 30, 26]

10

[25, 29, 21, 30, 26]

Variable Length Arguments in Python:


We have tried and learned the different ways of defining and calling a function in our program.
In this article, we will discuss what are the variable-length arguments in Python.
Here we will cover two types-
1. Non - Keyworded Arguments (*args)
2. Keyworded Arguments (**kwargs)

Non - Keyworded Arguments (*args)


First let us understand the properties of *args,
1. The * in *args indicates that we can pass variable number of arguments in a function in
Python.
2. We can pass any number of arguments during the function call.

The program given below illustrates the same,


#program to demonstrate *args in python
def my_func(*argp):
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Output:

Let

us

study

Data Science

and

Blockchain
Explanation-
Let's understand what we have done in the above program,
1. In the first step, we have created a function that will take variable arguments as its
parameters.
2. After this, we have used a for loop that will take each element or parameter in this case and
print it.
3. Finally, we have passed six strings as the parameters in our function.
4. On executing the program, the desired output is displayed.

Let's have a look at one more program based on *args.


#program to demonstrate *args in python
def my_func(par1,par2,*argp):
#displaying the first parameter
print("The first parameter is: ",par1)
#displaying the second parameter
print("The second parameter is: ",par2)
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Output:

The first parameter is: Let

The second parameter is: us

study

Data Science

and

Blockchain
Explanation-
It's time to have a glance at the explanation of this program.
1. In the first step, we have created a function that will take two parameters and then rest as
variable arguments as its parameters.
2. In the next step, we have defined the function in which we have displayed the values of the
first two parameters.
3. After this, we have used a for loop that will take each element or parameter in this case and
print it.
4. Finally, we have passed six strings as the parameters in our function.
5. On executing the program, the desired output is displayed.

Now let us understand what is a keyworded argument or **kwargs in Python.


Keyworded Arguments (**kwargs)
Here we can pass a keyworded variable-length argument.
Some of its characteristics are-
1. The double star indicates that any number of keyworded arguments can be passed in a
function.
2. It is analogous to a dictionary where each key is mapped to a value.

Consider the program given below,


#program to demonstrate **kwargs in python
def my_func(**kwargs):
for k,v in kwargs.items():
print("%s=%s"%(k,v))
#passing the parameters in function
my_func(a_key="Let",b_key="us",c_key="study",d_key="Data Science",e_key="and",f_key
="Blockchain")
Output:

a_key=Let

b_key=us

c_key=study

d_key=Data Science

e_key=and

f_key=Blockchain
Explanation-
Let us see what we have done in the above program.
1. In the first step, we have created a function that takes keyworded arguments as its parameters.
2. After this, in the function definition we have specified that a for loop will be used to fetch the
key-value pair.
3. Finally, we have passed six key value pairs inside the function.
4. On executing this program, the desired output is displayed.

Consider one more program given below based on **kwargs.


#program to demonstrate **kwargs in python
def my_func(p1,**kwargs):
for k,v in kwargs.items():
print("%s=%s"%(k,v))
#passing the parameters in function
my_func("Let",b_key="us",c_key="study",d_key="Data Science",e_key="and",f_key="Bloc
kchain")
Output:

b_key=us

c_key=study

d_key=Data Science

e_key=and

f_key=Blockchain
Explanation-
Check out the explanation of this program,
1. In the first step, we have created a function that takes one parameter and rest as keyworded
arguments as its parameters.
2. After this, in the function definition, we have specified that a for loop will be used to fetch
the key-value pair.
3. Finally, we have passed five key-value pairs inside the function and so it displays only those
pairs in the output and doesn't consider the first string.
4. On executing this program, the desired output is displayed.

We will conclude this article with a program that illustrates how *args and **kwargs can be used in a
single program.
#program to demonstrate **kwargs in python
def my_func(*args,**kwargs):
#displaying the value of args
print("The value of args is:",args)
#displaying the value of kwargs
print("The value of kwargs is:",kwargs)
#passing the values in function
my_func("Let","us","study",a_key="Data Science",b_key="and",c_key="Blockchain")
Output:

The value of args is: ('Let', 'us', 'study')

The value of kwargs is: {'a_key': 'Data Science', 'b_key': 'and', 'c_key': 'Blockchain'}
Explanation-
1. In the first step, we have created a function that takes *args and **kwargs (non-keyworded
and keyworded arguments) as its parameters.
2. After this, we have the function definition where we have displayed the values of both
parameters.
3. Finally, we have passed six parameters in the function, from which three are strings and the
other three are key-value pairs.

On executing this program, the desired output is disp..


Python Strings:
A String is a group of characters.If you want to use text in Python,you have to use a string.you
can use a string in the following ways in a python program.
Using Single Quotes(‘):For example,a string can be written as ‘HELLO’.
Using Double Quotes(“): Strings in double quotes are exactly same as those in single
quotes.Therefore,’HELLO’ is same as “HELLO”.
Using Triple Quotes(‘’’ ‘’’):You can specify multi-line strings using triple quotes.you can use as
many single quotes and double quotes as you want in a string within triple quotes.An example of a
multi-line string can be given as,
‘’’Good morning everyone.
“Welcome to the world of python’.”
Happy Reading.’’’
String Concatenation:To concatenate, or combine, two strings you can use the + operator.
Example:
a = "Hello"
b = "World"
c=a+b
print(c)
Output:
HelloWorld
Unicode Strings:
Unicode is a standard encoding system that is used to represent characters from almost all
languages. Every Unicode character is encoded using a unique integer code point between 0 and
0x10FFFF . A Unicode string is a sequence of zero or more code points.
Example:
Use Unicode code points in strings: \x , \u , \U.It should be 2, 4, or 8 digits like \xXX , \
uXXXX , and \UXXXXXX , respectively. An error is raised if the number of digits is not correct.
Each code is treated as one character. You can check it with the built-in function len() which returns
the number of characters.

Escape Sequences:

To insert characters that are illegal in a string, use an escape character.An escape character is
a backslash \ followed by the character you want to insert.

Example:
txt = "We are the so-called \"Vikings\" from the north."

Output:

We are the so-called “Vikings” from the north.

Raw Strings:
Raw strings are particularly useful when working with regular expressions, as they allow
you to specify patterns that may contain backslashes without having to escape them. They are also
useful when working with file paths, as they allow you to specify paths that contain backslashes
without having to escape them. Raw strings can also be useful when working with strings that
contain characters that are difficult to type or read, such as newline characters or tabs. In general,
raw strings are useful anytime you need to specify a string that contains characters that have
special meaning in Python, such as backslashes, and you want to specify those characters literally
without having to escape them.
Example:
str = r'Python\nis\easy\to\learn'
Output: Python\nis\easy\to\learn
Explanation: As we can see that the string is printed as raw,
and it neglected all newline sign(\n) or tab space (\t).

String Formatting:
String formatting in Python allows you to create dynamic strings by combining variables
and values. String formatting in Python allows you to create dynamic strings by combining
variables and values.

There are five different ways to perform string formatting in Python:

 Formatting with % Operator.


 Formatting with format() string method.
 Formatting with string literals, called f-strings.
 Formatting with String Template Class
 Formatting with center() string method.

Formatting string using % Operator


It is the oldest method of string formatting. Here we use the modulo % operator. The
modulo % is also known as the “string-formatting operator”.In this code, the % operator is used
for string formatting. The expression “%s gobbled down” % hurriedly formats the string by
replacing the %s placeholder with the value hurriedly.

Example:
print("The mangy, scrawny stray dog %s gobbled down" %'hurriedly' +
"the grain-free, organic dog food.")

Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog
food.
Python Operators:
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators:

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example Tr

+ Addition x+y Tr

- Subtraction x-y Tr

* Multiplication x*y Tr

/ Division x/y Tr

% Modulus x%y Tr

** Exponentiation x ** y Tr
// Floor division x // y Tr

Python Assignment Operators:

Assignment operators are used to assign values to variables:

Python Comparison Operators:

Comparison operators are used to compare two values:

Operator Name Example Tr

== Equal x == y Tr

!= Not equal x != y Tr

> Greater than x>y Tr

< Less than x<y Tr

>= Greater than or equal to x >= y Tr

<= Less than or equal to x <= y Tr


Python Logical Operators:

Logical operators are used to combine conditional statements:

Operator Description Example T

and Returns True if both statements are true x < 5 and x < 10 T

or Returns True if one of the statements is true x < 5 or x < 4 T

not Reverse the result, returns False if the result not(x < 5 and x < 10) T
is true

Python Identity Operators:

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example T

is Returns True if both variables are the same x is y T


object

is not Returns True if both variables are not the same x is not y T
object

Python Membership Operators:


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is x not in y


not present in the object

Python Bitwise Operators:

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from x >> 2
shift the left, and let the rightmost bits fall off

Operator Precedence:

Operator precedence describes the order in which operations are performed.

Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:

print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence at
the top:

Operator Description T

() Parentheses T

** Exponentiation T

+x -x ~x Unary plus, unary minus, and bitwise NOT T

* / // % Multiplication, division, floor division, and modulus T


+ - Addition and subtraction T

<< >> Bitwise left and right shifts T

& Bitwise AND T

^ Bitwise XOR T

| Bitwise OR T

== != > >= < <= is is Comparisons, identity, and membership operators T


not in not in

not Logical NOT T

and AND T

or OR T

If two operators have the same precedence, the expression is evaluated from left to right.

Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the
expression from left to right:

print(5 + 4 - 7 + 3)
Formatting using format() Method
Format() method was introduced with Python3 for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders defined
by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put
into the placeholders and concatenate with the string passed as parameters into the format
function.

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)


Example:
print('We all are {}.'.format('equal'))

Output:
We all are equal
Understanding Python f-string
PEP 498 introduced a new string formatting mechanism known as Literal String
Interpolation or more commonly as F-strings (because of the leading f character preceding the
string literal). The idea behind f-String in Python is to make string interpolation simpler.
To create an f-string in Python, prefix the string with the letter “f”. The string itself can be
formatted in much the same way that you would with str. format(). F-strings provide a concise
and convenient way to embed Python expressions inside string literals for formatting.

String Formatting with F-Strings:In this code, the f-string f”My name is {name}.” is
used to interpolate the value of the name variable into the string.

Example:
name = 'Ele'
print(f"My name is {name}.")

Output:
My name is Ele
Python String Template Class

In the String module, Template Class allows us to create simplified syntax for output
specification. The format uses placeholder names formed by $ with valid
Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $
$ creates a single escaped $:

Formatting string using Template Class:

This code imports the Template class from the string module. The Template class allows us
to create a template string with placeholders that can be substituted with actual values. Here we are
substituting the values n1 and n2 in-place of n3 and n4 in the string n.
Example:
# Python program to demonstrate
# string interpolation
from string import Template

n1 = 'Hello'
n2 = 'GeeksforGeeks'

# made a template which we used to


# pass two variable so n3 and n4
# formal and n1 and n2 actual
n = Template('$n3 ! This is $n4.')

# and pass the parameters into the


# template string.
print(n.substitute(n3=n1, n4=n2))

Output:
Hello ! This is GeeksforGeeks.

Python String center() Method


The center() method is a built-in method in Python‘s str class that returns a new string that is
centered within a string of a specified width.

Formatting string using center() method:This code returns a new string padded
with spaces on the left and right sides.

Example:
string = "GeeksForGeeks!"
width = 30

centered_string = string.center(width)

print(centered_string)

Output:
GeeksForGeeks!
String Operations:
In python, String operators represent the different types of operations that can be employed
on the program's string type of variables. Python allows several string operators that can be applied
on the python string are as below: Assignment operator: “=.” Concatenate operator: “+.” String
repetition operator: “*.”
String operators with examples:
In python, String operators represent the different types of operations that can be employed on

the program’s string type of variables. Python allows several string operators that can be applied on

the python string are as below:


 Assignment operator: “=.”

 Concatenate operator: “+.”

 String repetition operator: “*.”

 String slicing operator: “[]”

 String comparison operator: “==” & “!=”

 Membership operator: “in” & “not in”

 Escape sequence operator: “\.”

 String formatting operator: “%” & “{}”

Example #1 – Assignment Operator “=”


Python string can be assigned to any variable with an assignment operator “= “. Python string

can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name =

“string” assigns “string” to variable var_name.

Code:

string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)

Output:

hello

hello

hello
Example #2 – Concatenate Operator “+”
Two strings can be concatenated or join using the “+” operator in python, as explained in

the below example code:

Code:

string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)

Output:

helloworld

Example #3 – String Repetition Operator “*”


The same string can be repeated in python by n times using string*n, as explained in the

below example.

Code:

string1 = "helloworld "


print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)

Output:

helloworld helloworld

helloworld helloworld helloworld


helloworld helloworld helloworld helloworld

helloworld helloworld helloworld helloworld helloworld

Example #4 – String slicing operator “[]”


Characters from a specific index of the string can be accessed with the string[index]

operator. The index is interpreted as a positive index starting from 0 from the left side and a negative

index starting from -1 from the right side.

 string[a]: Returns a character from a positive index a of the string from the left side as

displayed in the index graph above.

 string[-a]: Returns a character from a negative index a of the string from the right side as

displayed in the index graph above.

 string[a:b]: Returns characters from positive index a to positive index b of the as displayed

in index graph above.

 string[a:-b]: Returns characters from positive index a to the negative index b of the string as

displayed in the index graph above.

 string[a:]: Returns characters from positive index a to the end of the string.

 string[:b] Returns characters from the start of the string to the positive index b.

 string[-a:]: Returns characters from negative index a to the end of the string.

 string[:-b]: Returns characters from the start of the string to the negative index b.

 string[::-1]: Returns a string with reverse order.

Code:

string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])

Output:

ello

ellowo

lloworld

hello

hellowor

ld

dlrowolleh

Example #5 – String Comparison Operator “==” & “!=”


The string comparison operator in python is used to compare two strings.
 “==” operator returns Boolean True if two strings are the same and return Boolean False if

two strings are not the same.

 “!=” operator returns Boolean True if two strings are not the same and return Boolean False if

two strings are the same.

These operators are mainly used along with if condition to compare two strings where the

decision is to be taken based on string comparison.

Code:

string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)

Output:

False

True

True

False

Example #6 – Membership Operator “in” & “not in”


Membership operator is used to searching whether the specific character is part/member of

a given input python string.


 “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in

the string.

 “a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a”

is in the string.

A membership operator is also useful to find whether a specific substring is part of a given

string.

Code:

string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)

Output:

True

False

False

True

True
False

False

Example #7 – Escape Sequence Operator “\”


To insert a non-allowed character in the given input string, an escape character is used. An

escape character is a “\” or “backslash” operator followed by a non-allowed character. An example

of a non-allowed character in python string is inserting double quotes in the string surrounded by

double-quotes.

1. Example of non-allowed double quotes in python string:

Code:

string = "Hello world I am from "India""


print(string)

Output:

File “main.py”, line1

string=”Hello world I am from “India””

SyntaxError:invalid syntax

Example #8 – String Formatting Operator “%”


String formatting operator is used to format a string as per requirement. To insert another type of

variable along with string, the “%” operator is used along with python string. “%” is prefixed to

another character indicating the type of value we want to insert along with the python string.

Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)

Output:

Hey india

my age is 19

Hey india,my age is 19

Hey india,my subject mark is 20.560000

Mutable and Immutable in Python:

In Python, the terms “mutable” and “immutable” refer to the ability of an object to be
changed after it is created.An object is considered mutable if its state or value can be modified after
it is created. This means that you can alter its internal data or attributes without creating a new
object. Examples of mutable objects in Python include lists, dictionaries, and sets. If you modify a
mutable object, any references to that object will reflect the changes.Both of these states are integral
to Python data structure.

What is Mutable?

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’
is the ability of objects to change their values. These are often the objects that store a collection of
data.
What is Immutable?

Immutable is the when no change is possible over time. In Python, if the value of an object
cannot be changed over time, then it is known as immutable. Once created, the value of these objects
is permanent.

List of Mutable and Immutable objects:

Objects of built-in type that are mutable are:

 Lists
 Sets
 Dictionaries
 User-Defined Classes (It purely depends upon the user to define the characteristics)
Objects of built-in type that are immutable are:

 Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)


 Strings
 Tuples
 Frozen Sets
 User-Defined Classes (It purely depends upon the user to define the characteristics)
Object mutability is one of the characteristics that makes Python a dynamically typed language.
Though Mutable and Immutable in Python is a very basic concept, it can at times be a little
confusing due to the intransitive nature of immutability.

Mutable Objects in Python

#Creating a list which contains name of Indian cities

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:

print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

Immutable Objects in Python

#Creating a Tuple which contains English name of weekdays


weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

Python String Methods

Python has a set of built-in methods that you can use on strings.All string methods returns new
values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string


find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was fou

rindex() Searches the string for a specified value and returns the last position of where it was fou

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case


translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

Python Built in Functions:

Python has a set of built-in functions.

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

ascii() Returns a readable version of an object. Replaces none-ascii characters

with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes


bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the specified object

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is divided by

argument2

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object


eval() Evaluates and executes an expression

exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or method)

globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute

(property/method)

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value


id() Returns the id of an object

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current local symbol table

map() Returns the specified iterator with the specified function applied to each item

max() Returns the largest item in an iterable


memoryview() Returns a memory view object

min() Returns the smallest item in an iterable

next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of the specified character

pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increments by 1

(by default)

repr() Returns a readable version of an object


reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list

staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

super() Returns an object that represents the parent class

tuple() Returns a tuple


type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators

String Comparison in Python:


Python string equals Using Relational Operators

The relational operators compare the Unicode values of the characters of the strings from
the zeroth index till the end of the string. It then returns a boolean value according to the operator
used.
Example:

print("Geek" == "Geek")

print("Geek" < "geek")

print("Geek" > "geek")

print("Geek" != "Geek")

Output:
True
True
False
False

String Comparison in Python Using is and is not:

The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same is
the case for != and is not.
Example:
str1 = "Geek"

str2 = "Geek"

str3 = str1

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

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

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

print(str1 is str1)

print(str1 is str2)

print(str1 is str3)

str1 += "s"

str4 = "Geeks"

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

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

print(str1 is str4)

Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True

ID of changed str1 = 0x7f60356137d8

ID of str4 = 0x7f60356137a0

False
The object ID of the strings may vary on different machines. The object IDs of str1, str2
and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is
changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as
in the new str1, the answer will be false as their object IDs are different.
Vice-versa will happen with is not.
String Comparison in Python Creating a user-defined function.

By using relational operators we can only compare the strings by their unicodes. In order
to compare two strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the
number of digits.
 Python3

# function to compare string

# based on the number of digits

def compare_strings(str1, str2):

count1 = 0

count2 = 0

for i in range(len(str1)):

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

count1 += 1

for i in range(len(str2)):
if str2[i] >= "0" and str2[i] <= "9":

count2 += 1

return count1 == count2

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

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

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

Output:
False
False
True

Python Modules:

What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:
Example

Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)
Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module:

The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):

Example

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)
Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

Import and use the platform module:

import platform

x = platform.system()
print(x)

Using the dir() Function:


There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:

Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Namespaces and Modules:


(a) Object reference

 It is of paramount importance in learning Python to clearly understand what


happens 'under the hood' when an assignment command is executed. So:

What happens when 'x = 1' is executed?

 Three actions are taken:


 (a) a name 'x' (a simple sequence of characters, an
identifier) is created somewhere in the system memory
 (b) an object (a specific data structure) with value '1' is
created somewhere in memory
 (c) a binding between name x and object '1' is
established (that is: a pointer is created directing from
'x' to '1')

This binding is typically called 'object reference'

Pythontutor
 It is advisable to use online pythontutor to visualize execution of Python code
 See how pythontutor visualizes object reference
Shared object reference

 See that two (or even more names, a and c in this example) may reference the same
object (integer '1'). This is typically called "shared object reference"

(b) Namespaces

What is a namespace?

 In Python a 'namespace' is a mapping from names to their objects (values) in a


specific programming context. For example, the mapping of names a, b, c, d in the
example above on objects 1, 3 and 'spam' constructs a namespace.
 A namespace can be also conceptualized as the 'ecosystem' where a name is born,
lives and dies.
 A concrete example:
 x = 1 (a name is almost always created ('is born') by
some assignment command)
 x = 'spam' (other assignments may alter the name
binding, that is its 'object reference')
 del x (one way for a name to 'die' - that is, expelled
from the namespace- is by using the 'del' command)

In [7]:
x=1
x='spam'
print(x)

del x
print(x)
spam
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-2bb509689422> in <module>()
4
5 del x
----> 6 print(x)

NameError: name 'x' is not defined

 x=1 introduces 'x' in the namespace but name 'x' is not recognized after executing
the 'del x' command. 'x' is deleted from the namespace.

Printing values onscreen

 Please note that when working interactively in a Python shell (like, for example,
jupyter notebook) you may either use the print() function to present values
onscreen or simply write the name or expression whose value you want in the
output.
 In the latter case only the last expression in the cell will be presented in the output
unless you define otherwise by adjusting the notebook settings

In [1]:
x=1
y = 2.5
x+y
# Just writing the expression will present the outcome
Out[1]:
3.5
In [5]:
x=1
y = 2.5
print(x, y, 2*x**y)
# Better use print() when you want to present more than one values
1 2.5 2.0
(c) Modules

What is a module?

 A module is practically any .py file containing useful code (for example:
statements, functions, and classes) that can be used for code development.
 As the name implies, modules promote the idea of modular development in
practice. Python offers a simple yet powerful way to link modules and use/reuse
code in many different situations

How to connect modules

 Modules are connected using the 'import' command


 Typically you write the import command in the beginning (not necessarily though)
of your main program module, as follows:

import module_name

 The 'import' command imports the namespace of the module to the namespace of
the code you are writing in your main program. For example:

In [ ]:
import random

print(random.randint(1,10))

 The 'random' module offers functions for generating and managing random
numbers. The 'import random' command imports the namespace of 'random' in your
program code. We shall see more of that later.
 Note the use of 'dot notation' to refer to the imported
names: 'module_name.imported_name'. This is a practical way to visualize
namespaces and import them safely in your code.

 There are two other common ways to write the 'import' command. One you should
avoid; the other you should follow.

 Avoid this:

In [4]:
from random import *
print(randint(1,10))

 The benefit here is that you import the entire module namespace and you can use it
without writing the module name as a prefix.
 However: this technique provides no visual cues as to the origin of the names and it
may confuse you - so avoid it unless you are completely confident about your code!

 Follow this:
In [6]:
import random as rn
print(rn.randint(1,10))

 This technique allows you to:


 (a) Use a two-letter alias for the imported module, so
the overload from writing the prefix is minimized
 (b) You still have a visual cue about the namespace.
You easily understand, for example, that the 'randint'
function comes from the 'rn' module and this is a very
very useful information in developing and debugging.
 Create your own Python Modules

 Python is a multi-purpose, high level, and dynamic programming language. It provides many
built-in modules and functions to perform various types of tasks. Aside from that, we can also
create our own modules using Python. A module is like a library in Java, C, C++, and C#. A
module is usually a file that contains functions and statements. The functions and statements
of modules provide specific functionality. A Python module is saved with the .py extension.
In this article, we will learn to create our own Python modules.

 A module is typically used to divide the large functionality into small manageable files. We
can implement our most used functions in a separate module, and later on, we can call and
use it everywhere. The module’s creation promotes reusability and saves a lot of time.
 Create Python modules
 To create a Python module, open a Python script, write some statements and functions, and
save it with .py extension. Later on, we can call and use these modules anywhere in our
program.
 Let’s create a new module named “MathOperations”. This module contains functions to
perform addition, subtraction, multiplication, and division.

 #creating MathOperation module

#the module provides addition, subtraction, multiplication, and division functions

#all the functions take two numbers as argument

#creating addition function

def addition(num1,num2):

return num1+num2
#creating subtraction function

def subtraction(num1,num2):

return num1-num2

#creating multiplication function

def multiplication(num1,num2):

return num1*num2

#creating division function

def division(num1,num2):

return num1/num2

Part- A
Choose the best answer:

1. What will be the output of above Python code?

str1="6/4"

print("str1")

a). 1
b). 6/4
c). 1.5
d). str1

2. Which of the following is False?

a). String is immutable.


b). capitalize() function in string is used to return a string by converting the whole given string into
uppercase.
c). lower() function in string is used to return a string by converting the whole given string into
lowercase.
d). None of these.

3. What is called when a function is defined inside a class?

a). class
b). function
c). method
d). module

4. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity

5.How to connect namespace?


a) import
b) syntax
c) method
d) module

6. What will be the output of below Python code?

str1="poWer"

str1.upper()

print(str1)

a). POWER
b). Power
c). power
d). poWer

7.What will following Python code return?

str1="Stack of books"

print(len(str1))

a). 13
b). 14
c). 15
d). 16

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

str1="Information"

print(str1[2:8])

a). format
b). formatio
c). orma
d). ormat

9.Which keyword is use for function?

a). define
b). fun
c). def
d). function

10. Which of the following items are present in the function header?

a). function name


b). parameter list
c). return value
d). Both A and B

11. Which of the following will print the pi value defined in math module?

a). print(pi)
b). print(math.pi)
c). from math import pi
print(pi)
d). from math import pi
print(math.pi)

12. Which operator is used in Python to import modules from packages?

a). .
b). *
c). ->
d). &

13. What is a variable defined outside a function referred to as?

a). local variable


b). global variable
c). static Variable
d). automatic variable

14. What is the output of the following program?z = lambda x : x * x

print(z(6))
a). 6
b). 36
c). 0
d). error

15. What is the output of the following program?


print(chr(ord(chr(97))))

a). a
b). A
c). 97
d). error

Part – B
1. Explain about Python strings?
2. Explain about Python strings operators?
3. Explain about example of a string in Python?
4. How to do length of a string in Python?
5. Why strings are immutable with an example in Python?
6. What are immutable strings in Python?
7. What are immutable strings write a short note?
8. What are string function and method in Python?
9. What are the 5 string methods?
10. What are the 2 string method in Python?

Part-C
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

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

Open the file for reading and writing in binary format. Raises an I/O error if the file does
‘rb+’
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

Keywor Description
d

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