I Python Notes
I Python Notes
STUDY MATERIAL
QUESTION PAPER PATTERN
TIME: 3 Hours
Max.Ma
rks:75
HISTORY of PYTHON:
Usage of Python
Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.
➢ Desktop Applications
➢ Web Applications
➢ Data Science
➢ Artificial Intelligence
➢ Machine Learning
➢ Scientific Computing
➢ Robotics
➢ Internet of Things (IoT)
➢ Gaming
➢ Mobile Apps
➢ Data Analysis and Preprocessing
➢ Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release.
➢ Latest version of Python 3.11.4 released on 24 October 2022.
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential features.
1) Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines the code block. It is the recommended programming language
for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute, while
Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop
the software for several competing platforms by writing a program only once.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly working
towards make new python modules and functions. Anyone can contribute to the Python community.
The open-source means, "Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our Python code. It converts the program into byte code, and any platform can use
that byte code.
8) Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as Tensor
flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework
for Python web development.
9) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language into our
code.
12. Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign some value
to the variable, it automatically allocates the memory to the variable at run time. Suppose we are
assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
PYTHON LITERAL:
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as
double quotes to create a string.
Example:
"Aman" , '12345'
TYPES OF STRINGS:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as Single line
Strings.
Example: text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
II. Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical
types.
Int(signed Long(long float(floating Complex(complex)
integers) integers) point)
Numbers can be Integers of Real numbers with In the form of a+bj where a
both positive and unlimited size both integer and forms the real part and b forms
negative) with no followed by fractional part eg: - the imaginary part of the
fractional part.eg: lowercase or 26.2 complex number. eg: 3.14j
100 uppercase L eg:
87032845L
Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
❖ Tuple:
o Python tuple is a collection of different data-type. It is immutable which means it cannot be
modified after creation.
o It is enclosed by the parentheses () and each element is separated by the comma(,).
Example
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
❖ Set:
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the comma(,).
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}
CONSTANT:
✓ a constant term is used in Mathematics, a value or quantity that never changes.
✓ In programming, a constant refers to the name associated with a value that never changes during
the programming execution.
✓ Programming constant is different from other constants, and it consists of two things - a name
and an associated value.
✓ A real-life example is - The speed of light, the number of minutes in an hour, and the name of a
project's root folder.
Advantages of constant:
o Improved Readability - It helps to improve the readability of the code. For example, it is
easier to read and understand a constant named MAX_SPEED than the substantial speed
value itself.
o Clear communication of intent - Most developers consider the 3.14 as the pi constant.
However, the Pi, pi, or PI name will communicate intent more clearly. This practice will
allow another developer to understand our code.
o Better Maintainability - Constants allow us to use the same value throughout your code.
Suppose we want to update the constant's value; we don't need to change every instance.
o Low risk of errors - A constant representing a given value throughout a program is less
error-prone. If we want to change the precision in the calculations, replacing the value can be
risky. Instead of replacing it, we can create different constants for different precision levels
and change the code where we needed.
o Thread-safe data storage - A constants are thread-safe objects, meaning several threads can
simultaneously use a constant without risking losing data.
Built-in Constants:
In the official documentation, the True and False are listed as the first constant. These are Python Boolean values
and are the instance of the int. A True has a value of 1, and False has a value 0.
Example -
>>> True
True
>>> False
False
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> int(True)
1
>>> int(False)
0
>>> True = 42
...
SyntaxError: cannot assign to True
>>> True is True
True
>>> False is False
True
PYTHON VARIABLES:
Variables
Variables are containers for storing data values.
Creating Variables
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
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
➢ LOCAL VARIABLE:
Local variables are the variables that declared inside the function and have scope within the function.
Let's understand the following example.
Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
Explanation:
In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside the
function. If we try to use them outside the function, we get a following error.
add()
# Accessing local variable outside the function
print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw the NameError.
➢ GLOBAL VARIABLES:
✓ Global variables can be used throughout the program, and its scope is in the entire program. We
can use global variables inside or outside the function.
✓ A variable declared outside the function is the global variable by default.
✓ Python provides the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable.
Let's understand the following example.
Example -
Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we defined a function
and accessed the declared variable using the global keyword inside the function. Now we can modify
its value. Then, we assigned a new string value to the variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.
Delete a variable:
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x, and
print it, we get the error "variable x is not defined". The variable x will no longer use in future.
Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
BASIC FUNDAMENTALS:
i)Tokens and their types.
ii) Comments
a)Tokens:
➢ The tokens can be defined as a punctuator mark, reserved words, and each word in a
statement.
➢ The token is the smallest unit inside the given program.
There are following tokens in Python:
o Keywords.
o Identifiers.
o Literals.
o Operators.
KEYWORDS:
✓ Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions.
✓ You'll never need to import any keyword into your program because they're permanently present.
✓ Python's built-in methods and classes are not the same as the keywords.
✓ Built-in methods and classes are constantly present; however, they are not as limited in their
application as keywords.
✓ False ✓ await ✓ else ✓ import ✓ pass
Output:
Code
help("keywords")
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
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:
X Y X and Y
X not X
True False
False True
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
# 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
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:
Examples
Here are some examples of numbers −
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.
# float variable.
b=20.345print("The type of variable having value", b, " is ", type(b))
# complex variable.
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:
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"
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')
Hello, World
Syntax of print()
Here,
end (optional) - allows us to add add specific values like new line "\n", tab "\t"
file (optional) - where the values are printed. It's default value is sys.stdout (screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default: False
INPUT:
Python input() Function
Python input() function is used to get input from the user. It prompts for the user input and reads a
line. After reading data, it converts it into a string and returns that. It throws an error EOF Error if
EOF is read.
Signature
input ([prompt])
Parameters
prompt: It is a string message which prompts for the user input.
Return
It returns user input after converting into a string.
Let's see some examples of input() function to understand it's functionality.
Python input() Function Example 1
we are using this function get user input and display to the user as well.
# Python input() function example
# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
Python Comments:
learn about single-line comments, multi-line comments, documentation strings, and other Python
comments.
Introduction to Python Comments
We may wish to describe the code we develop. We might wish to take notes of why a section of
script functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and
sophisticated business logic are typically explained with comments. The Python interpreter overlooks
the remarks and solely interprets the script when running a program. Single-line comments, multi-
line comments, and documentation strings are the 3 types of comments in Python.
Advantages of Using Comments
Our code is more comprehensible when we use comments in it. It assists us in recalling why specific
sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other code
sections. This simple technique stops some lines from running or creates a fast pseudo-code for the
program.
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.
EXPRESSIONS:
Example :
x = 25 # a statementx = x + 10 # an expressionprint(x)
Output :
35
An expression in Python is very different from statements in Python. A statement is not evaluated for
some results. A statement is used for creating variables or for displaying values.
Example :
a = 25 # a statementprint(a) # a statement
Output :
25
An expression in Python can contain identifiers, operators, and operands. Let us briefly discuss
them.
An identifier is a name that is used to define and identify a class, variable, or function in Python.
An operand is an object that is operated on. On the other hand, an operator is a special symbol that
performs the arithmetic or logical computations on the operands. There are many types of operators
in Python, some of them are :
• + : add (plus).
• - : subtract (minus).
• x : multiply.
• / : divide.
• ** : power.
• % : modulo.
• << : left shift.
• >> : right shift.
• & : bit-wise AND.
• | : bit-wise OR.
• ^ : bit-wise XOR.
• ~ : bit-wise invert.
• < : less than.
• > : greater than.
• <= : less than or equal to.
• >= : greater than or equal to.
• == : equal to.
• != : not equal to.
• and : boolean AND.
• or : boolean OR.
• not : boolean NOT.
The expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on their
precedence. We have various types of expression in Python, refer to the next section for a more
detailed explanation of the types of expression in Python.
Types of Expression in Python:
We have various types of expression in Python, let us discuss them along with their respective
examples.
1. Constant Expressions:
A constant expression in Python that contains only constant values is known as a constant expression.
In a constant expression in Python, the operator(s) is a constant. A constant is a value that cannot be
changed after its initialization.
Example :
x = 10 + 15# Here both 10 and 15 are constants but x is a variable.print("The value of x is: ", x)
Output :
The value of x is: 25
2. Arithmetic Expressions:
An expression in Python that contains a combination of operators, operands, and sometimes
parenthesis is known as an arithmetic expression. The result of an arithmetic expression is also a
numeric value just like the constant expression discussed above. Before getting into the example of
an arithmetic expression in Python, let us first know about the various operators used in the
arithmetic expressions.
Operator Syntax Working
+ x+y Addition or summation of x and y.
- x-y Subtraction of y from x.
X xxy Multiplication or product of x and y.
/ x/y Division of x and y.
// x // y Quotient when x is divided by y.
% x%y Remainder when x is divided by y.
** x ** y Exponent (x to the power of y).
Example :
x = 10y = 5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
print("The sum of x and y is: ", addition)print("The difference between x and y is: ",
subtraction)print("The product of x and y is: ", product)print("The division of x and y is: ",
division)print("x to the power y is: ", power)
Output :
The sum of x and y is: 15The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions:
An integral expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). An integral expression always produces an integer value as a resultant.
Example :
x = 10 # an integer numbery = 5.0 # a floating point number# we need to convert the floating-point number into
an integer or vice versa for summation.result = x + int(y)print("The sum of x and y is: ", result)
Output :
The sum of x and y is: 15
4. Floating Expressions:
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer numbery = 5.0 # a floating point number# we need to convert the integer
number into a floating-point number or vice versa for summation.result = float(x) + yprint("The sum
of x and y is: ", result)
Output :
The sum of x and y is: 15.0
5. Relational Expressions:
A relational expression in Python can be considered as a combination of two or more arithmetic
expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in
Python (>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10+15>2010+15>20
In this example, first, the arithmetic expressions (i.e. 10+1510+15 and 2020) are evaluated, and then
the results are used for further comparison.
Example :
a = 25b = 14c = 48d = 45# The expression checks if the sum of (a and b) is the same as the
difference of (c and d).result = (a + b) == (c - d)print("Type:", type(result))print("The result of the
expression is: ", result)
Output :
Type: <class 'bool'>The result of the expression is: False
6. Logical Expressions:
As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical expressions
in Python, let us discuss them briefly.
Operator Syntax Working
and x and y The expression return True if both x and y are true, else it returns False.
or x or y The expression return True if at least one of x or y is True.
not Not x The expression returns True if the condition of x is False.
Note :
In the table specified above, x and y can be values or another expression as well.
Example :
from operator import and_
x = (10 == 9) y = (7 > 5)
and_result = x and yor_result = x or ynot_x = not xprint("The result of x and y is: ",
and_result)print("The result of x or y is: ", or_result)print("The not of x is: ", not_x)
Output :
The result of x and y is: FalseThe result of x or y is: True
The not of x is: True
7. Bitwise Expressions:
The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.
Example :
x = 25left_shift = x << 1right_shift = x >> 1print("One right shift of x results: ",
right_shift)print("One left shift of x results: ", left_shift)
Output :
One right shift of x results: 12One left shift of x results: 50
8. Combinational Expressions:
As the name suggests, a combination expression can contain a single or multiple expressions which
result in an integer or boolean value depending upon the expressions involved.
Example :
x = 25y = 35result = x + (y << 1)print("Result obtained : ", result)
Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are resolved based on their
precedence or priority. Let us learn about the precedence of various operators in the following
section.
Multiple Operators in Expression (Operator Precedence) ?
The operator precedence is used to define the operator's priority i.e. which operator will be executed
first. The operator precedence is similar to the BODMAS rule that we learned in mathematics. Refer
to the list specified below for operator precedence.
Precedence Operator Name
1. ()[]{} Parenthesis
2. ** Exponentiation
3. -value , +value , ~value Unary plus or minus, complement
4. / * // % Multiply, Divide, Modulo
5. +– Addition & Subtraction
6. >> << Shift Operators
7. & Bitwise AND
8. ^ Bitwise XOR
9. pipe symbol Bitwise OR
10. >= <= > < Comparison Operators
11. == != Equality Operators
12. = += -= /= *= Assignment Operators
13. is, is not, in, not in Identity and membership operators
14. and, or, not Logical Operators
Let us take an example to understand the precedence better :
x = 12y = 14z = 16
result_1 = x + y * zprint("Result of 'x + y + z' is: ", result_1)
result_2 = (x + y) * zprint("Result of '(x + y) * z' is: ", result_2)
result_3 = x + (y * z)print("Result of 'x + (y * z)' is: ", result_3)
Output :
Result of 'x + y + z' is: 236Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236
✓ 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.
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.
ARRAY METHODS:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
PART - A
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.
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.
a) wo
b) world
c) sn
d) rl
Explanation: Execute in the shell and verify.
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
PART - B (5 MARK)
….……………………………………..UNIT 1 COMPLETED………….…………………………..
UNIT II
Control Statements:
Control Statements
• Control statements in python are used to control the order of execution of the program based on
the values and logic.
• Loops are employed in Python to iterate over a section of code continually.
• Control statements are designed to serve the purpose of modifying a loop's execution from its
default behaviors.
• Based on a condition, control statements are applied to alter how the loop executes.
Conditional Statements
A conditional statement as the name suggests itself, is used to handle conditions in program. These
statements guide the program while making decisions based on the conditions encountered by the
program.
Like every other programming language, Python also has some predefined conditional statements.
These statements guide the program while making decisions based on the conditions encountered
by the program.
Python has 4 key Conditional Statements that you should know:
1. if statement
2. if-else statement
3. Nested if
4. if-elif-else ladder
if Statement
• if – It help us to run a particular code, but only when a certain condition is met or satisfied.
A if only has one condition to check.
• Meaning if the program finds the condition defined in the if statement to be true, it will go ahead
and execute the code block inside the if statement.
Syntax:
if condition:
# execute code block
Example:
# list of numbers
list_of_numbers = [2,4,6,9,5]
# for loop to iterate through the list and check each elements of the list
for i in list_of_numbers:
# check if no. is odd
if i % 2 != 0:
# if condition is True print "odd"
print (i, "is an odd number")
# check if no. is even
if i % 2 == 0:
# if condition is false print "even"
print (i, "is an even number")
Output:
SYNTAX:
# for loop to iterate through the list and check each element of the list
for i in list_of_numbers:
# if the no. is not odd then the no. is even therfore print "even"
else:
if-elif-else ladder
• The elif statement is used to check for multiple conditions and execute the code block
within if any of the conditions evaluate to be true.
• The elif statement is similar to the else statement in the context that it is optional but unlike
the else statement, there can be multiple elif statements in a code block following
an if statement.
Syntax:
Output:
Nested if Statements:
if condition1:
if condition2:
# execute code if both condition1and
condition2 are True
# list of numbers
list_of_numbers = [4,5,9,17,21]
# for loop to iterate through the list and check each element of the list
for i in list_of_numbers:
# condition1: check if no. is odd
# if yes execute the code block inside the first if statement
if i%2!=0:
# if condition2 is true
# execute the below code block
print (i,"is an odd number & divisible by 3")
# if codition2 if False
# execute the below code block
else:
print (i, "is an odd number but not divisible by 3")
# if condition1 is False
# execute the below code block
else:
print(i,"is an even number")
Output:
Loops in Python
Python programming language provides the following types of loops to handle looping
requirements. Python provides three ways for executing the loops. While all the ways
provide similar basic functionality, they differ in their syntax and condition-checking time.
There are 2 types of Loops in Python.
1. While loop
2. For loop
While Loop in Python
In python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately after the
loop in the program is executed.
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements.
Example:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Using else statement with While Loop in Python
The else clause is only executed when your while condition becomes false. If you break out of
the loop, or if an exception is raised, it won’t be executed.
Syntax of While Loop with else statement:
Example:
# Python program to illustrate
# combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")
Output
Hello Geek
Hello Geek
Hello Geek
In Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of time, we can use the while loop in
Python to do so.
# Python program to illustrate
# Single statement while block
count = 0
while (count == 0):
print("Hello Geek")
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or array
etc. In Python, there is “for in” loop which is similar to for each loop in other languages. Let us
learn how to use for in loop for sequential traversals. It can be used to iterate over a range
and iterators.
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
Set Iteration
1
2
3
4
5
6
Iterating by the index of sequences
We can also use the index of elements in the sequence to iterate. The key idea is to first
calculate the length of the list and in iterate over the sequence within the range of this
length. See the below example:
# Python program to illustrate
# Iterating by index
The syntax for a nested while loop statement in the Python programming language is as
follows:
A final note on loop nesting is that we can put any type of loop inside of any other type of
loop. For example, a for loop can be inside a while loop or vice versa.
# Python program to illustrate
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
2 2
3 3 3
4 4 4 4
JUMP STATMENTS
Loop Control Statements
Loop control statements change execution from their normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed. Python
supports the following control statements.
• Continue Statement
• Break Statement
• Pass Statement
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement
The break statement in Python brings control out of the loop.
for letter in 'geeksforgeeks':
A. for loop
B. while loop
C. do-while loop
D. None of the above
View Answer
Ans : C
Explanation: While loop is used when multiple statements are to executed repeatedly until the
given condition becomes False statement is False regarding loops in Python.
Explanation: Keyword break can be used to bring control out of the current loop statement is
True regarding loops in Python.
4. What will be the output of given Python code?
n=7
c=0
while(n):
if(n>5):
c=c+n-1
n=n-1
else:
break
print(n)
print(c)
A. 5 11
B. 5 9
C. 7 11
D. 5 2
View Answer
Ans : A
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print(c)
A. 2
B. 0
C. 4
D. 3
View Answer
Ans : D
A. for i in range(0,5):
print(i)
B. for j in [0,1,2,3,4]:
print(j)
C. for k in [0,1,2,3,4,5]:
print(k)
D. for l in range(0,5,1):
print(l)
View Answer
Ans : C
Explanation: Option C python code will give different output from the others.
i=2
while(i>0):
i=i-1
A. 2
B. 3
C. 1
D. 0
View Answer
Ans : A
list1 = [3 , 2 , 5 , 6 , 0 , 7, 9]
sum = 0
sum1 = 0
if (elem % 2 == 0):
continue
if (elem % 3 == 0):
A. 8 9
B. 8 3
C. 2 3
D. 8 12
View Answer
Ans : D
str1="learn python"
str2=""
str3=""
for x in str1:
str2+=x
pass
str3+=x
print(str2,end=" ")
print(str3)
A. rnpn ea
B. rnpn ear
C. rnp ea
D. rnp ear
View Answer
Ans : B
for i in range(0,2,-1):
print("Hello")
A. Hello
B. Hello Hello
C. No Output
D. Error
View Answer
Ans : C
A. if a>=2 :
B. if (a >= 2)
C. if (a => 22)
D. if a >= 22
View Answer
12. What keyword would you use to add an alternative condition to an if statement?
A. else if
B. elseif
C. elif
D. None of the above
View Answer
Ans : C
A. Yes
B. No
C. if/else not used in python
D. None of the above
View Answer
Ans : A
Explanation: Yes, we can write if/else in one line. For eg i = 5 if a > 7 else 0. So, option A is
correct.
14. In a Python program, a control structure:
Explanation: Control structures determine which statements in the program will be executed
and in what order, allowing for statements to be skipped over or executed repeatedly. So,
option B is correct.
15. What will be output of this expression:
'p' + 'q' if '12'.isdigit() else 'r' + 's'
A. pq
B. rs
C. pqrs
D. pq12
View Answer
Ans : A
A. if a = b:
B. if a == b:
C. if a === c:
D. if a == b
View Answer
Ans : B
A. True
B. False
C. Python has switch statement but we can not use it.
D. None of the above
View Answer
Ans : B
Explanation: Python does not have switch case statement. So, option B is correct.
Explanation: For statment always ended with colon (:). So, option B is correct.
19. Which of the following sequences would be generated bt the given line of code?
A. 5 4 3 2 1 0 -1
B. 5 4 3 2 1 0
C. 5 3 1
D. None of the above
View Answer
Ans : C
Explanation: The initial value is 5 which is decreased by 2 till 0 so we get 5, then 2 is decreased
so we get 3 then the same thing repeated we get 1 and now when 2 is decreased we get -1
which is less than 0 so we stop and hence we get 5 3 1. So, option C is correct.
A. indefinite
B. discriminant
C. definite
D. indeterminate
View Answer
Ans : A
Explanation: A while loop implements indefinite iteration, where the number of times the loop
will be executed is not specified explicitly in advance. So, option A is correct.
21. When does the else statement written after loop executes?
Explanation: Else statement after loop will be executed only when the loop condition becomes
false. So, option B is correct.
22. What will be the output of the following code?
x = "abcdef"
i = "i"
while i in x:
Explanation: There will be no output since there is no i in the string x. So, option D is correct.
x = "abcd"
for i in range(len(x)):
print(i)
A. abcd
B. 0 1 2 3
C. 1 2 3 4
D. a b c d
View Answer
Ans : B
Explanation: len(x) will give 4 and the loop will run for 4 times starting from 0. Hence output
will be 0 1 2 3. So, option B is correct.
x = 12
for i in x:
print(i)
A. 12
B. 1 2
C. Error
D. None of the above
View Answer
Ans : C
Explanation: Objects of type int are not iterable. So, option C is correct.
25. A loop becomes infinite loop if a condition never becomes ________.
A. TRUE
B. FALSE
C. Null
D. Both A and C
View Answer
Ans : B
Explanation: A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to
a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
26. If the else statement is used with a while loop, the else statement is executed when the
condition becomes _______.
A. TRUE
B. FALSE
C. Infinite
D. Null
View Answer
Ans : B
Explanation: If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
27. Python programming language allows to use one loop inside another loop known as?
A. switch
B. foreach
C. nested
D. forall
View Answer
Ans : C
Explanation: Python nested loops : Python programming language allows to use one loop
inside another loop.
A. break
B. exit
C. return
D. pass
View Answer
Ans : D
Explanation: The pass statement is a null operation; nothing happens when it executes.
29. The continue statement can be used in?
A. while loop
B. for loop
C. do-while
D. Both A and B
View Answer
Ans : D
Explanation: The continue statement can be used in both while and for loops.
UNIT III - Functions:
Function Definition – Function Call – Variable Scope and its Lifetime-Return Statement.
Function Arguments: Required Arguments, Keyword Arguments, Default Arguments and
Variable Length Arguments Recursion. Python Strings: String operations- Immutable Strings
- Built-in String Methods and Functions - String Comparison. Modules: import statement-
The Python module – dir() function – Modules and Namespace – Defining our own modules.
PYTHON FUCTIONS
Fundamentals of Python functions, including what they are, their syntax, their primary parts,
return keywords, and significant types. We'll also look at some examples of Python function
definitions.
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.
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.
Syntax
We will define a function that returns the argument number's square when called.
Output:
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.
Function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result. function is a block of code
which only runs when it is called.
Features of Functions
To create a function, we need to use a def keyword to declare or write a function in Python.
Here is the syntax for creating a function:
Syntax
Myfun.py
1. def myFun(): # define function name
2. print(" Welcome to JavaTpoint")
3. myFun() # call to print the statement
Output:
Welcome to JavaTpoint
Creating a Function
Example
def my_function():
print("Hello from a function")
my_function()
Function Calling in Python
Syntax:
1. def function_name():
2. Statement1
3. function_name() # directly call the function
4.
5. # calling function using built-in function
6. def function_name():
7. str = function_name('john') # assign the function to call the function
8. print(str) # print the statement
Consider the following example to print the Welcome Message using a function in Python.
CallFun.py
1. def MyFun():
2. print("Hello World")
3. print(" Welcome to the JavaTpoint")
4.
5. MyFun() # Call Function to print the message.
Output:
Hello World
Welcome to the JavaTpoint
In the above example, we call the MyFun() function that prints the statements
The scope of variable is a region of the program where a variable is visible or accessible.
Lifetime of a variable is the duration for which a variable exists in the memory. The existence
and accessibility depend on the declaration of a variable in the program.
For example, the lifetime of a variable declared inside a function is as long as the function is
alive. When the execution of function body is finished, then the variable defined inside a
function will destroy.
There are two basic types of scope of variables in Python. They are:
• Global scope
• Local scope
Let’s understand each type of variable scope with the help of examples.
When we define a variable inside the main program but outside the function body, then it has
a global scope. The variable declared in the main body of the program or file is a global
variable.
In the global scope, the global variable will be visible throughout the program or file, and
also inside any file which imports that file. We can easily access a variable defined in global
scope from all kinds of functions and blocks.
Let’s take some important example programs based on the global scope in Python.
Example 2:
Let’s write a program in Python in which we will define a global variable and access it from
both inside the function and main program body.
# Declaring a global variable in the global scope.
x = 50
def showMe():
print('Value of x from local scope = ',x) # calling variable x inside the function.
# Main program.
Output:
In this example, variable x is a global variable. We have accessed it from both inside the
function and outside the function because it has a global scope.
Local Scope
A variable defined or created inside a function body or a block has a local scope. We can
access it only within the declared function or block and not from outside that function or
block.
As the execution of function body or block is finished, Python destroys the local variable
from the memory. In other words, local variable exists in the memory as long as the function
is executing.
Consider the following example code below in which we will define a local variable within in
a function and we will access it inside a function and from outside the function.
Example 3:
def my_funct():
my_funct()
print(msg) # accessing local variable from outside the function.
Output:
Good morning!
print(msg) # accessing local variable from outside the function.
NameError: name 'msg' is not defined
RETURN STATEMENT
The return Statement
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as
follows −
#!/usr/bin/python
The return statement in python is an extremely useful statement used to return the flow of
program from the function to the function caller. The keyword return is used to write the
return statement.
Since everything in python is an object the return value can be any object such as – numeric
(int, float, double) or collections (list, tuple, dictionary) or user defined functions and classes
or packages.
The return statement has the following features -
• Return statement cannot be used outside the function.
• Any code written after return statement is called dead code as it will never be
executed.
• Return statement can pass any value implicitly or explicitly, if no value is given then
None is returned.
Syntax
Following is the syntax of return statement in python -
def some_function(parameters):
return <expression>
print(some_function)
Example
Following is the simple example of return statement -
def welcome(str):
return str + " from TutorialsPoint"
print(welcome("Good morning"))
Output
Following is an output of the above code
The return statement is useful in multiple ways and the below sections discuss the different
use case of return statement along with examples.
Use of return statement in Python
Functions are core of any programming language as they allow for code modularity thereby
reducing program complexity. Functions can display the result within itself, but it makes the
program complex, hence it is best to pass the result from all the functions to a common
place.
It is in this scenario that the return statement is useful as it terminates the currently executing
function and passes control of the program to the statement that invoked the function.
Example
In the below code the sum_fibonacci function is used to calculate the sum of the first 15
terms in the fibonacci series. After calculating the sum, it prints and returns the sum to the
sum_result variable. This is to show that printing inside the function and returning the value
give the same output.
# Defining function to calculate sum of Fibonacci series
def sum_fibonacci(terms):
first_term = 0
second_term = 1
sum_series = 0
# Finding the sum of first 15 terms of Fibonacci series
for i in range(0, terms):
sum_series = sum_series + first_term
next_term = first_term + second_term
first_term = second_term
second_term = next_term
# Printing the sum inside the function
print("Sum of Fibonacci series inside the function is = {}".format(sum_series))
Function Arguments
You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows −
Live Demo
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
#!/usr/bin/python
Python string
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string. Consider the following example in Python to create a string.
Syntax:
1. str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.
We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
Like other languages, the indexing of the Python strings starts from 0. For example,
The string "HELLO" is indexed as given in the below figure.
Output:
H
E
L
L
O
IndexError: string index out of range
String Operators
Operator Description
not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified
string.
r/R It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such
as "C://python". To define any string as a raw string, the character r or
R is followed by the string.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
IMMUTABLE
the string data types are immutable. Which means a string value cannot be updated. We can
verify this by trying to update a part of the string which will led us to an error.
# Can not reassign
t= "Tutorialspoint"
print type(t)
t[0] = "M"
When we run the above program, we get the following output −
t[0] = "M"
TypeError: 'str' object does not support item assignment
We can further verify this by checking the memory location address of the position of the
letters of the string.
.
x = 'banana'
Immutable refers to a state in which no change can occur over time. A Python object is
referred to as immutable if we cannot change its value over time. The value of these Python
objects is fixed once they are made.
Since int in Python is an immutable data type, we cannot change or update it.
As we previously learned, immutable objects shift their memory address whenever they are
updated.
Output:
Since the float object in Python is an immutable data type, we cannot alter or update it. As we
previously learned, immutable objects shift their memory address whenever they are updated.
Code
Output:
Since strings in Python are immutable data structures, we cannot add or edit any data. We
encountered warnings stating that strings are not changeable when modifying any section of
the string.
Code
Output:
Because tuples in Python are immutable by nature, we are unable to add or modify any of
their contents. Here is an illustration of that:
Code
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-e011ebc4971e> in <module>
5
6 # Trying to modify the tuple object
----> 7 tuple_[0] = 'X'
8 print(tulple_)
9
10 isalnum()Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
11 isalpha()Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Sr.No Function & Description
13 islower()Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.
16 istitle()
compare strings in Python using the equality (==) and comparison (<, >, !=, <=, >=)
operators. There are no special methods to compare two strings. In this article, you’ll learn
how each of the operators work when comparing strings.
Python string comparison compares the characters in both strings one by one. When different
characters are found, then their Unicode code point values are compared. The character with
the lower Unicode value is considered to be smaller.
fruit1 = 'Apple'
Copy
The following table shows the results of comparing identical strings (Apple to Apple) using
different operators.
Both the strings are exactly the same. In other words, they’re equal. The equality operator and
the other equal to operators return True.
If you compare strings of different values, then you get the exact opposite output.
If you compare strings that contain the same substring, such as Apple and ApplePie, then the
longer string is considered larger.
Comparing User Input to Evaluate Equality Using Operators
This example code takes and compares input from the user. Then the program uses the results
of the comparison to print additional information about the alphabetical order of the input
strings. In this case, the program assumes that the smaller string comes before the larger
string.
Here’s an example of the potential output when you enter different values:
Output
Enter the name of first fruit:
Apple
Enter the name of second fruit:
Banana
Apple comes before Banana in the dictionary.
Here’s an example of the potential output when you enter identical strings:
Output
Enter the name of first fruit:
Orange
Enter the name of second fruit:
Orange
Orange and Orange are the same.
Python Modules
In this tutorial, we will explain how to construct and import custom Python modules.
Additionally, we may import or integrate Python's built-in modules via various methods.
Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.
Simplification: A module often concentrates on one comparatively small area of the overall
problem instead of the full task. We will have a more manageable design problem to think
about if we are only concentrating on one module. Program development is now simpler and
much less vulnerable to mistakes.
Flexibility: Modules are frequently used to establish conceptual separations between various
problem areas. It is less likely that changes to one module would influence other portions of
the program if modules are constructed in a fashion that reduces interconnectedness. (We
might even be capable of editing a module despite being familiar with the program beyond
it.) It increases the likelihood that a group of numerous developers will be able to collaborate
on a big project.
Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.
In Python, modularization of the code is encouraged through the use of functions, modules,
and packages.
A document with definitions of functions and various statements written in Python is called a
Python module.
Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.
Let's construct a module. Save the file as example_module.py after entering the following.
Example:
1. # Here, we are creating a simple Python program to show how to create a module.
2. # defining a function in the module to reuse it
3. def square( number ):
4. # here, the above function will square the number passed as the input
5. result = number ** 2
6. return result # here, we are returning the result of the function
Here, a module called example_module contains the definition of the function square(). The
function returns the square of a given number.
In Python, we may import functions from one module into our program, or as we say into,
another module.
For this, we make use of the import Python keyword. In the Python window, we add the next
to import keyword, the name of the module we need to import. We will import the module
we defined earlier example_module.
Syntax:
1. import example_module
The functions that we defined in the example_module are not immediately imported into the
present program. Only the name of the module, i.e., example_ module, is imported here.
We may use the dot operator to use the functions using the module name. For instance:
Example:
1. # here, we are calling the module square method and passing the value 4
2. result = example_module.square( 4 )
3. print("By using the module square of number is: ", result )
Output:
There are several standard modules for Python. The complete list of Python standard modules
is available. The list can be seen using the help command.
Similar to how we imported our module, a user-defined module, we can use an import
statement to import other standard modules.
Using the import Python keyword and the dot operator, we may import a standard module
and can access the defined functions within it. Here's an illustration.
Code
1. # Here, we are creating a simple Python program to show how to import a standard m
odule
2. # Here, we are import the math module which is a standard module
3. import math
4. print( "The value of euler's number is", math.e )
5. # here, we are printing the euler's number from the math module
Output:
While importing a module, we can change its name too. Here is an example to show.
Code
1. # Here, we are creating a simple Python program to show how to import a module and
rename it
2. # Here, we are import the math module and give a different name to it
3. import math as mt # here, we are importing the math module as mt
4. print( "The value of euler's number is", mt.e )
5. # here, we are printing the euler's number from the math module
Output:
The math module is now named mt in this program. In some situations, it might help us type
faster in case of modules having long names.
Please take note that now the scope of our program does not include the term math. Thus,
mt.pi is the proper implementation of the module, whereas math.pi is invalid.
We can import specific names from a module without importing the module as a whole. Here
is an example.
Code
1. # Here, we are creating a simple Python program to show how to import specific
2. # objects from a module
3. # Here, we are import euler's number from the math module using the from keyword
Output:
Only the e constant from the math module was imported in this case.
We avoid using the dot (.) operator in these scenarios. As follows, we may import many
attributes at the same time:
Code
1. # Here, we are creating a simple Python program to show how to import multiple
2. # objects from a module
3. from math import e, tau
4. print( "The value of tau constant is: ", tau )
5. print( "The value of the euler's number is: ", e )
Output:
Python dir() function returns the list of names in the current local scope. If the object on
which method is called has a method named __dir__(), this method will be called and must
return the list of attributes. It takes a single object type argument. The signature of the
function is given below.
Signature
1. dir ([object])
Parameters
Return
Let's create a simple example to get a list of valid attributes. It takes a single parameter which
is optional.
Output:
If we pass a parameter to this function, it returns attributes related to that object. See an
example below.
Output:
Modular Programming
Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.
Modules in Python
A document with definitions of functions and various statements written in Python is called a
Python module.
Example:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function
In Python, we may import functions from one module into our program, or as we say into,
another module.
Syntax:
import example_module
Example:
# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
Output:
Namespace in Python
the structure used to organize the symbolic names assigned to objects in a Python program,
why namespace is important, and how we can use them in our Python program. To put it
another way, it is a collection of the known symbolic names and the details about the thing
that each name refers to. A name can be thought of as a key in a dictionary, and objects are
the values in a namespace.
o Built-in
o Global
o Enclosing
o Local
As its name suggests, it contains pre-defined names of all of Python's built-in objects already
available in Python. Let's list these names with the following command.
Command -
1. dir(__builtins__)
The built-in namespace creates by the Python interpreter when its starts up. These are
terminated when Python interpreter terminates.
The global namespace consists of any names in Python at any level of the main program. It is
created when the main body executes and remains in existence until the interpreter
terminates.
The Python interpreter creates a global namespace for any module that our Python loads with
the import statement. To get more information, visit our Python Module.
The Local and Enclosing Namespaces
The local namespaces are used by the function; When the function is run, the Python
interpreter creates a new namespace. The local namespaces continue to exist after the
function has finished running. The capability can likewise comprise of another capability. As
shown below, we can define one function within another.
Example -
1. def f():
2. print('Initiate f()')
3.
4. def g():
5. print('Initiate g()')
6. print('End g()')
7. return
8.
9. g()
10.
11. print('Initiate f()')
12. return
13. f()
In the above model, the capability g() is characterized inside the collection of f(). We called
the g() function within the f() and the main f() function. Let's look at how the above function
works:
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.
Example
Create a List:
List Items:
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:
List Length:
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
Example
A list with strings, integers and boolean values:
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?
It is also possible to use the list() constructor when creating a new list.
Example:
Using the list() constructor to make a List:
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.
List items are indexed and you can access them by referring to the index number:
Example
Negative Indexing:
-1 refers to the last item, -2 refers to the second last item etc.
Example
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
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":
By leaving out the end value, the range will go on to the end of the list:
Example
Specify negative indexes if you want to start the search from the end of the list:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last item etc.
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.
By leaving out the start value, the range will start at the first item:
Example
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:
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.
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])
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']
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:
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
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
• 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:
Example
Create a Tuple:
Tuple Items:
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:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
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
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
String, int and boolean data types:
From Python's perspective, tuples are defined as objects with the data type 'tuple':
*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.
You can access tuple items by referring to the index number, inside square brackets:
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is
created.
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.
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:
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:
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:
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
Dictionaries are used to store data values in key:value pairs.
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:
type()
The dict() Constructor
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”
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method
a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
a) Error, invalid syntax
b) A
c) 5
d) 4
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
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’}
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
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) { }
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}
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
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():
>>> 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
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 - 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 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.
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.
Opening a file refers to getting the file ready either for reading or for writing.
This can be done using the open() function. This function returns a file object and
takes two arguments, one that accepts the file name and another that accepts the
mode(Access Mode). Now, the question arises what is the access mode? Access
modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File
Handle in the file. The file handle is like a cursor, which defines where the data has
to be read or written in the file. There are 6 access modes in Python.
Mode Description
‘r’ Open text file for reading. Raises an I/O error if the file does not exist.
‘r+’ Open the file for reading and writing. Raises an I/O error if the file does not exist.
Open the file for writing. Truncates the file if it already exists. Creates a new file if it does
‘w’
not exist.
Open the file for reading and writing. Truncates the file if it already exists. Creates a new
‘w+’
file if it does not exist.
Open the file for writing. The data being written will be inserted at the end of the file.
‘a’
Creates a new file if it does not exist.
Open the file for reading and writing. The data being written will be inserted at the end of
‘a+’
the file. Creates a new file if it does not exist.
‘rb’ Open the file for reading in binary format. Raises an I/O error if the file does not exist.
‘rb+’ Open the file for reading and writing in binary format. Raises an I/O error if the file does
Mode Description
not exist.
Open the file for writing in binary format. Truncates the file if it already exists. Creates a
‘wb’
new file if it does not exist.
Open the file for reading and writing in binary format. Truncates the file if it already
‘wb+’
exists. Creates a new file if it does not exist.
Open the file for appending in binary format. Inserts data at the end of the file. Creates a
‘ab’
new file if it does not exist.
Open the file for reading and appending in binary format. Inserts data at the end of the file.
‘ab+’
Creates a new file if it does not exist.
Syntax:
File_object = open(r"File_Name", "Access_Mode")
Note: The file should exist in the same directory as the Python script, otherwise full address
of the file should be written. If the file is not exist, then an error is generated, that the file
does not exist.
Output:
Welcome to GeeksForGeeks!!
Note: In the above example, we haven’t provided the access mode. By default, the open()
function will open the file in read mode, if no parameter is provided.
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
# Writing to file
file1.write("\nWriting to file:)" )
# Closing file
file1.close()
Sample Run:
writelines() function
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.
# my_list
my_list = ['geeks', 'for']
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]
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
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
Output:
[3, 4, 5, 6]
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:
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.
After opening the file using the open() method, we can simply use these methods.
Explore Curriculum
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.
Let us suppose we have a text file with the name examples.txt with the following content.
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.
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 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.
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.
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:
Pros:
Cons:
Cons:
Python readlines():
Pros:
Cons:
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")
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()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
• Python3
# Program to show various ways to
# read data from a file.
# 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
Output:
Hello
This is Delhi
This is Paris
This is London
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")
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"
# Closing file
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()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today
• Python3
# Program to show various ways to
# write data to a file using with statement
# Writing to file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
Output:
Hello
This is Delhi
This is Paris
This is London
Note: To know more about with statement click here.
using for statement:
steps:
To write to a file in Python using a for statement, you can follow these steps:
Open the file using the open() function with the appropriate mode (‘w’ for writing).
Use the for statement to loop over the data you want to write to the file.
Use the file object’s write() method to write the data to the file.
Close the file using the file object’s close() method.
In this example, the file is opened for writing using the with open(‘file.txt’, ‘w’) as f
statement. The data to be written is stored in a list called data. The for statement is used to
loop over each line of data in the list. The f.write(line + ‘\n’) statement writes each line of
data to the file with a newline character (\n) at the end. Finally, the file is automatically
closed when the with block ends.
• Python3
# Open the file for writing
with open('file.txt', 'w') as f:
# Define the data to be written
data = ['This is the first line', 'This is the second line', 'This is the third line']
# Use a for loop to write each line of data to the file
for line in data:
f.write(line + '\n')
# Optionally, print the data as it is written to the file
print(line)
# The file is automatically closed when the 'with' block ends
Output
This is the first line
This is the second line
This is the third line
Keyword Description
as To create an alias
finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not
or A logical operator
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.
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:
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:
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
>>> 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
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
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
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):
…
def function_name(parameters):
…
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 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
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
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
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
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
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.
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).
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
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
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
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
class example:
pass
return
def func_return():
a = 10
return a
def no_return():
a = 10
print(func_return())
print(no_return())
Output
10
None
while
i=5
while(i):
print(i)
i=i–1
Output
5
4
3
2
1
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.
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,
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 .
example
example
The following Python program reading a text file and splitting it into single words in python
example
This
is
a
test
After Split
['This', 'is', 'a', 'test']
This is a test
After Split
['This', 'is', 'a', 'test']
str = "This,is,a,test"
print(str.split(","))
output
example
import re
str = "This,isa;test"
print(re.split(",;",str))
output
example
This
is
a
test
maxsplit parameter
In the above program maxsplit is 2, the first two string are split and rest of them are in a same
string.
characters = "abcdef"
result = list(characters)
print (result)
output
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.
Method Description
fileno() Returns a number that represents the stream, from the operating system's perspective
seekable() Returns whether the file allows us to change the file position
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
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.
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
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
# 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
•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 :
"""
"""
object=open("itvoyagers.txt",'w')
object=open("itvoyagers.txt",'r')
s=11
c=object.read(s)
g=object.read()
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)
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 :
"""
"""
with open("itvoyagers.txt","r") as f:
s=10
c=f.read(s)
print(c)
c=f.read(s)
print(c)
c=f.read(s)
print(c)
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
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
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.
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.
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
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:
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:
Output:
Now, as the directory was empty, rmdir() method deleted the directory successfully.
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
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.
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.
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()
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()
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
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
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
10- Marks
….……………………………………..UNIT -5 Completed…………………………………………