PYTHON_NOTES
PYTHON_NOTES
UNIT-I
Basics of Python Programming: History of Python-Features of Python-Literal-Constants-
Variables - Identifiers–Keywords-Built-in Data Types-Output Statements – Input Statements-
Comments – Indentation- Operators-Expressions-Type conversions. Python Arrays: Defining
and Processing Arrays – Array methods.
UNIT II
Control Statements: Selection/Conditional Branching statements: if, if-else, nested if and if-
elif-else statements. Iterative Statements: while loop, for loop, else suite in loop and nested
loops. Jump Statements: break, continue and pass statements.
UNIT III
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-Return
Statement. Function Arguments: Required Arguments, Keyword Arguments, Default
Arguments and Variable Length Arguments- Recursion. Python Strings: String operations-
Immutable Strings - Built-in String Methods and Functions - String Comparison. Modules:
import statement- The Python module – dir() function – Modules and Namespace – Defining our
own modules
UNIT IV
Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic list
operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a
tuple – Nested tuples– Difference between lists and tuples. Dictionaries: Creating, Accessing,
Updating and Deleting Elements in a Dictionary – Dictionary Functions and Methods -
Difference between Lists and Dictionaries.
UNIT V
Python File Handling: Types of files in Python - Opening and Closing files-Reading and
Writing files: write() and writelines() methods- append() method – read() and readlines()
methods – with keyword – Splitting words – File methods - File Positions- Renaming and
deleting files.
1
UNIT-I
Basics of Python Programming
What is Python
Python’s simplicity, readability, and versatility make it an excellent choice for
beginners and experienced programmers alike.
Python History and Versions
Python laid its foundation in the late 1980s.
The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
Python 2.0 added new features such as list comprehensions, garbage collection systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
The following programming languages influence Python:
o ABC language.
o Modula-3
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.
2
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a
time. The advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to
develop the software for several competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official website It has
a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source
means, "Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it
can be used further in our Python code. It converts the program into byte code, and any platform
can use that byte code.
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.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.
3
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code
line by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can
use Python source code in another programming language as well. It can embed other language
into our code.
In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
Python Literals
The data which is being assigned to the variables are called as Literal.
In Python, Literals are defined as raw data which is being assigned to the variables or
constants.
Let us understand this by looking at a simple example,
Here, we have declared a variable ‘str’, and the value assigned to it ‘How are you, Sam?’ is a literal
of type string.
Numeric Literals
Numeric Literals are values assigned to the Variables or Constants which cannot be changed
i.e., they are immutable. There are a total of 3 categories in Numeric Literals. They are – Integer,
Float, and Complex.
4
Example
a = 30
b = 40.67
c = 10+4j
print(a)
print(b)
print(c)
print(c.real, c.imag)
Output
30
40.67
(10+4j)
10.0 4.0
String Literals
A string literal is a series of characters surrounded by quotation marks. For a string, we can
use single, double, or triple quotations. We can write multi-line strings or display them in the
desired format by using triple quotes. A single character surrounded by single or double quotations
is also known as a character literal.
Example
multi_line = '''Hey
There!!'''
5
char = 'Z'
print(string)
print(multi_line)
print(char)
Output –
Hello Guys
Hey
There!!
Boolean Literals
A Boolean Literal has either of the 2 values – True or False. Where True is considered as
1 and False is considered as 0.
Example
boolean1 = (1 == True)
boolean2 = (1 == False)
num = 20
age = 20
x = True + 10
y = False + 50
print(boolean1)
print(boolean2)
print(num==age)
print('Value of x:', x)
print('Value of y:', y)
6
Output
True
False
True
Value of x: 11
Value of y: 50
Special Literals
Python provides a special kind of literal known as None. We use this type of Literal in
order to specify the field has not been created. It also denotes the end of a list in Python.
Literal Collections
In Python, there are 4 different types of Literal Collections. They represent more complicated
and complex data and assist Python scripts to be more extensible. Let us look at each one of
them in detail.
1. List Literals
The elements in a list are of many data types. The values in the List are surrounded by square
brackets ([]) and separated by commas (,). List values can be changed i.e., they are mutable.
2. Tuple Literals
Just like a List, a tuple is also a collection of various data types. It is surrounded by parentheses
‘(),’ and each element is separated by a comma (,). It is unchangeable (immutable).
3. Dict Literals
The data is stored in the dictionary as a key-value pair. It is surrounded by curly braces ‘{}‘, and
each pair is separated by commas (,). A dictionary can hold various types of data. Dictionaries
are subject to change.
4. Set Literals
Set is an unordered data set collection. It is surrounded by and each element is separated by a
comma (,).
7
Python Constants
A Python Constant is a variable whose value cannot be changed throughout the program.
Certain values are fixed and are universally proven to be true. These values cannot be
changed over time. Such types of values are called as Constants. We can think of Python
Constants as a bag full of fruits, but these fruits cannot be removed or changed with other fruits.
1. Python Constants and variable names should contain a combination of lowercase (a-
z) or capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT
= 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized
when declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for
example, makes more sense than V. It simplifies the coding process.
Constants are typically declared and assigned in a module in Python. In this case, the
module is a new file containing variables, functions, and so on that is imported into the main file.
Constants are written in all capital letters with underscores separating the words within the
module.
We create a separate file for declaring constants. We then use this file to import the
constant module in the main.py file from the other file.
Example:
PI = 3.14
GRAVITY = 9.8
Output
8
Python Variables
A Variable is a location that is named in order to store data while the program is being
run.
In a programming language, Variables are words that are used to store values of any
data type.
In simple words, when you create a variable, it takes up some memory space based on the
value and the type you set to it. The Python interpreter allocates RAM to the variable based on
its data type. The variables’ values can be altered at any time during the program.
An Identifier is a term used in programming language in order to denote unique name given
to these variables.
Syntax
variable_name = data values
where, variable_name = combination of letters, numbers and an underscore
1. A Variable’s name cannot begin with a number. Either an alphabet or the underscore
character should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well as the
underscore character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables in
Python.
There are few different methods to assign data elements to a Variable. The most common ones
are described below –
In this type, the data values are directly assigned to the Variables in the declaration statement.
Example
num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'
print(num)
print(numlist)
print(str)
9
Output
10
[1, 3, 5, 7, 9]
Hello World
Here, we have created 3 variables named as ‘num’, ‘numlist’, and ‘str’. We have assigned all the
3 variables an int value 10, a list of integers, and a string of characters respectively.
Data values assigned to the variables can be changed at any time. In Layman language, you can
think of a Variable as a bag to store items and these items can be replaced at any time.
Example
val = 50
Output
Initial value: 50
In the above program, initially the value of Variable ‘val’ was 50. Later it was reassigned to a
value of 100.
In Python, we can assign multiple values to multiple variables in the same declaration statement
by using the following method –
Example
print(name)
print(age)
print(city)
10
Output
David
27
New York
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming
practice to give meaningful names to identifiers to make the code understandable.
Rules for Naming Python Identifiers
Valid identifiers:
var1
_var1
_1_var
var_1
Invalid Identifiers
!var1
1var
1_var
var#1
var 1
print(not False)
Output
True
True
True
Keywords in Python
Python Keywords are some predefined and reserved words in Python that have special
meanings. Keywords are used to define the syntax of the coding. The keyword cannot be used as
an identifier, function, or variable name. All the keywords in Python are written in lowercase
except True and False. There are 35 keywords in Python 3.11.
Keywords Description
This is a logical operator which returns true if both the operands are true else returns
and
false.
This is also a logical operator which returns true if anyone operand is true else returns
or
false.
not This is again a logical operator it returns True if the operand is false else returns false.
Elif is a condition statement used with an if statement. The elif statement is executed if
elif
the previous conditions were not true.
12
Keywords Description
Else is used with if and elif conditional statements. The else block is executed if the
Else
given condition is not true.
This function is used for debugging purposes. Usually used to check the correctness of
assert
code
13
Keywords Description
Finally is used with exceptions, a block of code that will be executed no matter if there
finally
is an exception or not.
in It’s used to check whether a value is present in a list, range, tuple, etc.
This is a special constant used to denote a null value or avoid. It’s important to
none
remember, 0, any empty container(e.g empty list) do not compute to None
14
Keywords Description
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
15
The data types will be briefly discussed in this tutorial section. We will talk about every single
one of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities
have a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
a=5
b = 40.5
c = 1+3j
Output:
1. Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with
int.
2. Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
3. Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
16
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in
capabilities and administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and
the operator + is used to combine two strings.
Example - 1
print(str)
s = '''''A multiline
string'''
print(s)
Output:
A multiline
string
List
Lists in Python are like arrays in C, but lists can contain data of different types. The
things put away in the rundown are isolated with a comma (,) and encased inside square sections
[].
To gain access to the list's data, we can use slice [:] operators. Like how they worked
with strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
print(type(list1))
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
print (list1 * 3)
Output:
[2]
[1, 'hi']
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items
from various data types. A parenthetical space () separates the tuple's components from one
another.
18
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
Example:
print (type(tup))
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
print (tup * 3)
t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
19
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for
each key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
dict_keys([1, 2, 3, 4])
Boolean
True and False are the two default values for the Boolean type. These qualities are
utilized to decide the given assertion valid or misleading. The class book indicates this. False can
be represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.
print(type(True))
print(type(False))
print(false)
20
Output:
<class 'bool'>
<class 'bool'>
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence.
Either a sequence of elements is passed through the curly braces and separated by a
comma to create the set or the built-in function set() is used to create the set. It can contain
different kinds of values.
set1 = set()
print(set2)
set2.add(10)
print(set2)
set2.remove(2)
print(set2)
Output:
Though it is not necessary to pass arguments in the print() function, it requires an empty
parenthesis at the end that tells Python to execute the function rather than calling it by name.
Now, let’s explore the optional arguments that can be used with the print() function.
Example
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
Output
Name: John
Age: 30
They are just meant for the coders themselves or other developers to understand a piece
of code, especially since the Python interpreter completely ignores comments in Python.
Comments in Python are identified with a hash symbol, #, and extend to the end of the
line. Hash characters in a string are not considered comments, however. There are three ways to
write a comment - as a separate line, beside the corresponding statement of code, or as a multi-
line comment block.
There are multiple uses of writing comments in Python. Some significant uses include:
Increasing readability
Explaining the code to others
Understanding the code easily after a long-term
Including resources
Re-using the existing code
There are three types of comments: single-line, multi-line, and docstring comments.
23
1. Single-Line Comments
Single-line comments begin with the “#” character. Anything that is written in a single line after
‘#’ is considered as a comment. The syntax for writing single-line comments is:
# comments here
There are two ways of using single-line comments in Python. You can use it before the code or
next to the code.
2. Multi-Line Comments
Python does not support multi-line comments. However, there are multiple ways to overcome
this issue. None of these ways are technically multi-line comments, but you can use them as one.
The first way is by using # at the beginning of each line of the comment
The next way is by using string literals but not assigning them to any variables. If you do not
assign a string literal to a variable, the Python interpreter ignores it. Use this to your advantage to
write multi-line comments. You can either use a single (‘’) quotation or double (“”) quotation.
3. Python Docstrings
Python provides an in-built feature called docstrings for commenting on modules, methods,
functions, objects, and classes. They are written in the first line after defining a module, function,
method, etc., using three quotation marks (‘’ or “”). If you do not use it in the first line, the
interpreter will not take it as a docstring. You can also access docstrings using the __doc__
attribute.
Indentation in Python
Indentation is a very important concept of Python because without properly indenting
the Python code, you will end up seeing IndentationError and the code will not get compiled.
Python Indentation
Python indentation refers to adding white space before a statement to a particular block
of code. In another word, all the statements with the same space to the right, belong to the
same code block.
24
Example of Python Indentation
Statement (line 1), if condition (line 2), and statement (last line) belongs to the same
block which means that after statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the last statement for execution.
The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.
Statements inside nested if-else belong to block 3 and only one statement will be
executed depending on the if-else condition.
Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code. A block is a combination of all these statements. Block can
be regarded as the grouping of statements for a specific purpose. Most programming languages
like C, C++, and Java use braces { } to define a block of code. Python uses indentation to
highlight the blocks of code. Whitespace is used for indentation in Python.
Python Operators
The operator is a symbol that performs a specific operation between two operands, according
to one definition. Operators serve as the foundation upon which logic is constructed in a program
in a particular programming language.
1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are
many arithmetic operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0
25
* It is used to multiply one operand with the other. For example, if a = 20, b = 4
(Multiplication) => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an
exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two
division) operands.
Program Code:
a = 32 # Initialize the value of a
Output:
26
Comparison operator
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Program Code:
Now we give code examples of Comparison operators in Python. The code is given below
Output:
a is greater b: True
Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left operand, the left
operand receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal
to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal
to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will
be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal
to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to
a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Program Code:
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
28
Output:
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples
of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>). Consider the case below.
For example,
if a = 7
b=6
a | b = 0111
a ^ b = 0100
~ a = 1000
Binary of y = 1000
Bitwise OR = 1101
8421
1 1 0 1 = 8 + 4 + 1 = 13
29
Bitwise AND = 0000
0000 = 0
8421
1 1 0 1 = 8 + 4 + 1 = 13
~x = -6
Program Code:
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
Output:
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The
examples of logical operators are and, or, and not. In the case of logical AND, if the first one is
0, it does not depend upon the second one.
30
In the case of logical OR, if the first one is 1, it does not depend on the second one.
Python supports the following logical operators. In the below table, we explain the works of the
logical operators.
Operator Description
And The condition will also be true if the expression is true. If the two expressions a and b
are the same, then a and b must both be true.
Or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
Not If an expression a is true, then not (a) will be false and vice versa.
Program Code:
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Output:
Expression in python
The interpreter evaluates each operator and operand in the expression based on its
precedence and associativity.
31
For example, in the expression 2 + 3 4, the multiplication operator () has higher
precedence than the addition operator (+), so the interpreter will first evaluate the multiplication
of 3 and 4, resulting in 12, and then add 2 to that result. This results in the final value of 14.
There are several types of expression in Python, but in this article, we will majorly focus on
arithmetic, comparison, and logical expressions.
In Python expression, comparison expressions are used to compare the value of two or more
variables. These expressions return a Boolean value of either True or False, which can be used to
control the flow of a program. Comparison expressions are often used in conjunction with
control flow statements such as if-else and while loops, as well as in conjunction with other
comparison and logical operators.
In Python, logical expressions are used to combine comparison expressions and other logical
expressions. These expressions return a Boolean value of either True or False, which can be used
to control the flow of a program. Logical expressions are often used in conjunction with control
flow statements such as if-else and while loops, as well as in conjunction with other comparison
and logical operators.
32
Type Conversion in Python
The act of changing an object’s data type is known as type conversion. The Python
interpreter automatically performs Implicit Type Conversion. Python prevents Implicit Type
Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type
conversion, sometimes referred to as type casting. When type casting, data loss could happen if
the object is forced to conform to a particular data type.
In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement.
Example
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Output
20.6
In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type.
33
Converting integer to float
int(a, base): This function converts any data type to an integer. ‘Base’ specifies the base in
which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
Python Arrays
The Array is an idea of storing multiple items of the same type together, making it easier
to calculate the position of each element by simply adding an offset to the base value. A
combination of the arrays could save a lot of time by reducing the overall size of the code.
1. car1 = "Lamborghini"
2. car2 = "Bugatti"
3. car3 = "Koenigsegg"
The Array can be handled in Python by a module named Array. It is useful when we
must manipulate only specific data values.
34
The following are the terms to understand the concept of an array:
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:
Array operations
We can access the array elements using the respective indices of those elements.
Program code:
35
print("last element is:", a[-1])
Output:
24566542
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
36
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
37
UNIT II
Conditional Statements
if condition:
# Statements to execute if
# condition is true
Example of Python if Statement
i = 10
if (i > 15):
I am Not in if
#!/usr/bin/python
i = 20
if (i < 15):
39
print("i is smaller than 15")
print("i'm in if Block")
else:
Output:
i is greater than 15
i = 10
if (i == 10):
# First if statement
if (i < 15):
if (i < 12):
else:
Output:
i is smaller than 15
41
Flowchart of Elif Statement in Python
Let’s look at the flow of control in if-elif-else ladder:
if (i == 10):
print("i is 10")
elif (i == 15):
42
print("i is 15")
elif (i == 20):
print("i is 20")
else:
Output:
i is not present
Loops in Python
Python programming language provides two types of Python loopshecking time.
In this article, we will look at Python loops and understand their working with the help
of examp – For loop and While loop to handle looping requirements. Loops in Python
provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax
and condition-checking time. In this article, we will look at Python loops and
understand their working with the help of examples.
All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Example
count = 0
count = count + 1
print("Hello Geek")
43
Output
Hello Geek
Hello Geek
Hello Geek
count = 0
count = count + 1
print("Hello Geek")
else:
Output
Hello Geek
Hello Geek
Hello Geek
In Else Block
44
For Loop in Python
For loops are used for sequential traversal. For example: traversing
a list or string or array etc. In Python, there is “for in” loop which is similar
to foreach loop in other languages. Let us learn how to use for loops in Python for
sequential traversals with examples.
Example:
n=4
print(i)
Output
Example with List, Tuple, String, and Dictionary Iteration Using for Loops in
Python
The code showcases different ways to iterate through various data structures in
Python. It demonstrates iteration over lists, tuples, strings, dictionaries, and sets,
printing their elements or key-value pairs.
print("List Iteration")
for i in l:
print(i)
45
print("\nTuple Iteration")
for i in t:
print(i)
print("\nString Iteration")
s = "Geeks"
for i in s:
print(i)
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Output
List Iteration
geeks
for
geeks
46
Tuple Iteration
geeks
for
geeks
String Iteration
Dictionary Iteration
xyz 123
abc 345
Set Iteration
47
Nested Loops in Python
Python programming language allows to use one loop inside another loop which
is called nested loop. Following section shows few examples to illustrate the concept.
The syntax for a nested while loop statement in the Python programming
language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any
other type of loops in Python. For example, a for loop can be inside a while loop or vice
versa.
Example
for j in range(i):
print()
Output
22
333
4444
48
Loop Control Statements
Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.
Continue Statement
The continue statement in Python returns the control to the beginning of the
loop.
Example: This Python code iterates through the characters of the
string ‘geeksforgeeks’. When it encounters the characters ‘e’ or ‘s’, it uses
the continue statement to skip the current iteration and continue with the next
character. For all other characters, it prints “Current Letter :” followed by the
character. So, the output will display all characters except ‘e’ and ‘s’, each on a separate
line.
Python3
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement
49
Example: In this Python code, it iterates through the characters of the
string ‘geeksforgeeks’.
When it encounters the characters ‘e’ or ‘s’, it uses the break statement to exit
the loop. After the loop is terminated, it prints “Current Letter :” followed by the last
character encountered in the loop (either ‘e’ or ‘s’). So, the output will
display “Current Letter :” followed by the first occurrence of ‘e’ or ‘s’ in the string.
Output
Current Letter : e
Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for
empty control statements, functions and classes.
Example: This Python code iterates through the characters of the
string ‘geeksforgeeks’ using a ‘for' loop. However, it doesn’t perform any specific
action within the loop, and the ‘pass' statement is used. After the loop, it prints “Last
Letter :” followed by the last character in the string, which is ‘s’.
Output
Last Letter : s
50
UNIT-III
Python Functions
Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a function so
that instead of writing the same code again and again for different inputs, we can do
the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
We can define a function in Python, using the def keyword. We can add any type
of functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python
function definition by using def keyword.
51
Syntax
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.
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.
# Defining a function
return len(string)
52
Output:
The location where we can find a variable and also access it if required is called
the scope of a variable.
Local variables are those that are initialized within a function and are unique to
that function. It cannot be accessed outside of the function. Let’s look at how to make a
local variable.
def f():
# local variable
print(s)
# Driver code
f()
Output
I love Geeksforgeeks
If we will try to use this local variable outside the function then let’s see what will
happen.
def f():
# local variable
s = "I love Geeksforgeeks"
53
print("Inside Function:", s)
# Driver code
f()
print(s)
Output:
Global variables are the ones that are defined and declared outside any function
and are not specified to any function. They can be used by any part of the program.
Example:
def f():
print(s)
# Global scope
f()
Output:
I love Geeksforgeeks
54
Syntax:
def fun():
statements
return [expression]
Example:
def cube(x):
r=x**3
return r
Example:
# Python program to
return a + b
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
res = is_true(2<5)
55
Output:
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output:
even
odd
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following function argument types in Python:
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
56
1. Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default
arguments to write functions in Python.
# Python program to demonstrate
# default arguments
print("x: ", x)
print("y: ", y)
# argument)
myFun(10)
Output:
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a
default value. But once we have a default argument, all the arguments to its right must
also have default values.
2. Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
57
3. Positional Arguments
We used the Position argument during the function call so that the first argument
(or value) is assigned to name and the second argument (or value) is assigned to age.
By changing the position, or if you forget the order of the positions, the values can be
used in the wrong places, as shown in the Case-2 example below, where 27 is assigned
to the name and Suraj is assigned to the age.
def nameAge(name, age):
print("Case-1:")
nameAge("Suraj", 27)
print("\nCase-2:")
nameAge(27, "Suraj")
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special
symbols:
58
*args in Python (Non-Keyword Arguments)
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
Example
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
Output
59
In Python, *args is used to pass a variable number of arguments to a function. It is
used to pass a variable-length, non-keyworded argument list. These arguments are
collected into a tuple within the function and allow us to work with them.
Feature of Python *args
To accept a variable number of arguments, use the symbol *; by convention, it is
commonly used with the term args.
*args enables you to accept more arguments than the number of formal arguments
you previously defined. With *args, you can add any number of extra arguments to
your current formal parameters (including none).
Using the *, the variable that we associate with the * becomes iterable meaning you
can do things like iterate over it, run some higher-order functions such as map and
filter, etc.
In this example, we define a function sum_all that accepts any number of
arguments. The *args syntax collects all the arguments into a tuple named args. Inside
the function, we iterate through the args tuple and calculate the sum of all the
numbers passed to the function.
def sum_all(*args):
result = 0
result += num
return result
print(sum_all(1, 2, 3, 4, 5))
Output
15
A keyword argument is when you give the variable a name as you provide it into
the function.
60
Consider the kwargs to be a dictionary that maps each keyword to the value we
pass beside it. As a result, when we iterate through the kwargs, there appears to be no
sequence in which they were printed.
def display_info(**kwargs):
print(f"{key}: {value}")
Output
name: Alice
age: 30
Recursion in Python
The term Recursion can be defined as the process of defining something in
terms of itself. In simple words, it is a process in which a function calls itself directly or
indirectly.
A lot of memory and time is taken through recursive calls which makes it
expensive for use.
Recursive functions are challenging to debug.
The reasoning behind recursion can sometimes be tough to think through.
Syntax:
| (recursive call)
func() ----
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
if n_terms <= 0:
62
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
Output
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Python String
A String is a data structure in Python Programming that represents a sequence
of characters. It is an immutable data type, meaning that once you have created a
string, you cannot change it.
Python String are used widely in many different applications, such as storing
and manipulating text data, representing names, addresses, and other types of data
that can be represented as text.
Syntax of String Data Type in Python
print(string_0)
print(type(string_0))
Output:
63
A Computer Science portal for geeks
<class 'str'>
The below Python functions are used to change the case of the strings. Let’s look at
some Python string methods with examples:
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case
swapcase(): Swap the cases of all characters in a string
capitalize(): Convert the first character of a string to uppercase
string.digits
The string '0123456789'.
string.hexdigits
The string '0123456789abcdefABCDEF'.
string.octdigits
The string '01234567'.
string.punctuation
String of ASCII characters which are considered punctuation characters in
the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
string.printable
String of ASCII characters which are considered printable. This is a
combination of digits, ascii_letters, punctuation, and whitespace.
string.whitespace
A string containing all ASCII characters that are considered whitespace. This
includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
64
print("\nConverted String:")
print(text.upper())
Output
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Converted String:
GEEkS fOR GEeKs
Original String
geeKs For geEkS
Time complexity: O(n) where n is the length of the string ‘text’
Auxiliary space: O(1)
65
Python Strings Immutable
Strings in Python are “immutable” which means they can not be changed after
they are created. Some other immutable data types are integers, float, boolean, etc.
The article will explore the differences between mutable and immutable objects,
highlighting the advantages of using immutable objects. It will also compare
immutability with mutability, discussing various methods to handle immutability and
achieve desired outcomes.
name_1[0] = 'T'
Explanation: We cannot update the string after declaring it means once an immutable
the objects instantiated, its value cannot be changed
Example -1:
2. chr()
Example
# use chr() function to find the characters corresponding to the given Unicode
for i in num:
print(chr(i))
3. dict()
Example
D1 = {}
D2 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 }
D3 = dict(name='Jim', age=20, height = 6.1)
print("D1 is empty dictionary", D1)
print("creating 'dict' using curly braces and colons:", D2)
67
4. enumerate()
Enumerate in a built-in function of Python that helps you count each object of a
list, tuple, set, or any data structure that can be iterated.
It takes input as a collection of tuples and returns it as an enumerate object.
An enumerated object (returned as an output) can be used directly for loops
It can be converted as a list of tuples using the list method.
Example
e_car_list = enumerate(car_list)
print(list(e_car_list))
5. float()
Example
print(float(2))
print(float('3.5'))
print(float())
print(float('inf'))
print(float('NaN'))
print(float('InfoEdge'))
6. len()
The len() function is one of the built-in functions in python that counts the
number of items in an object (string, list, tuple, set, or sequence). It returns the number
of objects in an integer format.
The Python list object is the most general mutable sequence type provided by the
language. Python lists are mutable that is the contents of the list be modified in place.
Items in the list can be accessed, changed, new elements can be added, existing element
can be removed or deleted.
Example
List1[1] = 3.0
8. ord()
ord() function in Python converts a single Unicode character into its integer
representation.
i.e., it takes a single character as an input and returns the corresponding Unicode.
It is the opposite of chr() function.
Example
lowercase_char = ord('a')
Special_Char = ord('$')
num = ord('9')
9. range()
The range function in Python returns a sequence of numbers starting from the
given input value (by default: 0), increments the number at the defined step size
(by default: 1), and stops before the specified value.
range () functions are most commonly used for loops to iterate sequences on a
sequence of numbers.
69
range () function only takes integer values.
Example
print()
10. set()
Python sets are unordered collections of unique elements and immutable objects.
You can think of them as a dictionary with just the keys and its values thrown away.
Therefore, each item of a set should be unique. Similar, to the dictionary, you can access,
add, remove the element from the set.
Example
#create a set
set2 = {2, 2, 3, 4, 5, 5, 6, 6, 6, 7}
"Geek" != "Geek"
Output: True
True
70
False
False
Explanation: In this, we are comparing two strings if they are equal to each other.
The relational operators compare the Unicode values of the characters of the strings
from the zeroth index till the end of the string. It then returns a boolean value according
to the operator used. It checks Python String Equivalence.
print("Geek" == "Geek")
print("Geek" != "Geek")
Output
True
True
False
False
The == operator compares the values of both operands and checks for value
equality. Whereas is operator checks whether both the operands refer to the same object
or not. The same is the case for != and is not. Let us understand Python String
Equivalence with an example.
str1 = "Geek"
str2 = "Geek"
str3 = str1
71
print("ID of str1 =", hex(id(str1)))
print("ID of str2 =", hex(id(str2)))
print("ID of str3 =", hex(id(str3)))
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
str1 += "s"
str4 = "Geeks"
print("\nID of changed str1 =", hex(id(str1)))
print("ID of str4 =", hex(id(str4)))
print(str1 is str4)
Output
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of str4 = 0x7f60356137a0
False
72
count1 = 0
count2 = 0
for i in range(len(str1)):
if str1[i] >= "0" and str1[i] <= "9":
count1 += 1
for i in range(len(str2)):
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1
return count1 == count2
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Output
False
False
True
When we import a module with the help of the Python import module it
searches for the module initially in the local scope by calling __import__() function.
The value returned by the function is then reflected in the output of the initial code.
import math
pie = math.pi
Output
print(pi)
Output
3.141592653589793
import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
Output
Random Number: 5
In the above code module, math is not imported, rather just pi has been imported as a
variable.
print(factorial(6))
Output
3.141592653589793
720
74
dir() function in Python
In Python, the dir() function is a built-in function used to list the attributes
(methods, properties, and other members) of an object. In this article we will see about
dir() function in Python.
Syntax: dir({object})
Parameters :
object [optional] : Takes object name
Returns :
dir() tries to return a valid list of attributes of the object it is called upon. Also, dir()
function behaves rather differently with different type of objects, as it aims to
produce the most relevant one, rather than the complete information.
For Class Objects, it returns a list of names of all the valid attributes and base
attributes as well.
For Modules/Library objects, it tries to return a list of names of all the attributes,
contained in that module.
If no parameters are passed it returns a list of names in the current local scope.
dir() is a powerful inbuilt function in Python3, which returns a list of the attributes
and methods of any object (say functions, modules, strings, lists, dictionaries, etc.)
A namespace is a system that has a unique name for each and every object in
Python. An object might be a variable or a method. Python itself maintains a
namespace in the form of a Python dictionary.
Real-time example, the role of a namespace is like a surname. One might not
find a single “Alice” in the class there might be multiple “Alice” but when you
particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one
(time being don’t think of both first name and surname are same for multiple
students).
Types of namespaces :
When Python interpreter runs solely without any user-defined modules,
methods, classes, etc. Some functions like print(), id() are always present, these are
built-in namespaces.
When a user creates a module, a global namespace gets created, later the
creation of local functions creates the local namespace. The built-in
namespace encompasses the global namespace and the global namespace
encompasses the local namespace.
76
The lifetime of a namespace :
A lifetime of a namespace depends upon the scope of objects, if the scope of an
object ends, the lifetime of that namespace comes to an end. Hence, it is not possible
to access the inner namespace’s objects from an outer namespace.
Example:
77
But in some cases, one might be interested in updating or processing global
variables only, as shown in the following example, one should mark it explicitly as
global and the update or process. Note that the line “count = count +1” references the
global variable and therefore uses the global variable, but compare this to the same
line written “count = 1”. Then the line “global count” is absolutely needed according to
scope rules.
Writing your own Python modules is easy. Any file containing valid Python code
can be imported as a module. Let's assume we have a file named words.py with the
following contents:
import words
my_string = "Sheila sells seashells by the seashore"
print(words.first_word(my_string))
print(words.last_word(my_string))
print(words.number_of_words(my_string))
Output:
Sheila
Seashore
6
78
We can use our own modules just as we have learnt to use the modules from the
Python standard library:
Let's assume our words.py file also contained some test cases:
print(first_word("This is a test"))
print(last_word("Here we are still testing"))
print(number_of_words("One two three four five"))
79
Now, if we import the module with an import statement, all the code in the module
which is outside the defined functions is automatically executed:
import words
my_string = "Sheila sells seashells by the seashore"
print(words.first_word(my_string))
print(words.last_word(my_string))
print(words.number_of_words(my_string))
Output:
This
testing
5
Sheila
seashore
6
80
UNIT IV
Python Lists
Python Lists are just like dynamically sized arrays, declared in other languages
(vector in C++ and ArrayList in Java). In simple language, a list is a collection of
things, enclosed in [ ] and separated by commas.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
Example of the list in Python
print(Var)
Output:
Lists are the simplest containers that are an integral part of the Python language.
Lists need not be homogeneous always which makes it the most powerful tool in Python.
A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are
mutable, and hence, they can be altered even after their creation.
List = []
print(List)
print(List)
print(List[2])
Output
Blank List:
[]
List of numbers:
List Items:
Geeks
Geeks
print(List[0])
print(List[2])
Output
Geeks
Geeks
82
Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append() and insert()
methods can also add values to a list.
Consider the following example to update the values inside the List.
Code
list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
# Adding multiple-element
print(list)
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
Nested List
List Comprehension are one of the most amazing features of Python. It is a smart
and concise way of creating lists by iterating over an iterable object. Nested List
Comprehensions are nothing but a list comprehension within another list
comprehension which is quite similar to nested for loops.
83
Nested List Comprehension in Python Syntax
Parameters:
Example:
matrix = []
for i in range(5):
matrix.append([])
for j in range(5):
matrix[i].append(j)
print(matrix)
Output:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
84
# repetition of list
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
# concatenation operator +
l = list1 + list2
print(l)
Output:
3. Length
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
len(list1)
85
Output:
4. Iteration
# iterating
for i in list1:
print(i)
Output:
12
14
16
39
40
5. Membership
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
86
print(100 in list1)
print(500 in list1)
Output:
False
False
False
True
True
True
87
S.no Method Description
element appears.
Tuples in Python
A comma-separated group of items is called a Python triple. The ordering, settled items,
and reiterations of a tuple are to some degree like those of a rundown, but in contrast to
a rundown, a tuple is unchanging.
The main difference between the two is that we cannot alter the components of a tuple
once they have been assigned. On the other hand, we can edit the contents of a list.
88
Creating Python Tuples
There are various ways by which you can create a tuple in Python. They are as follows:
Using round brackets
With one item
Tuple Constructor
print(var)
Output:
Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
Each element in a tuple has a specific order that will never change because tuples
are ordered sequences.
Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.
empty_tuple = ()
89
print("Tuple with different data types: ", mixed_tuple)
Output:
Empty tuple: ()
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the index
starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be
raised assuming we attempt to get to a list from the Tuple that is outside the scope of the
tuple record. An index above four will be out of range in this scenario.
The method by which elements can be accessed through nested tuples can be seen in the
example below
# Creating a tuple
print(tuple_[0])
print(tuple_[1])
90
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
try:
print(tuple_[1.0])
except Exception as e:
print(e)
print(nested_tuple[0][3])
print(nested_tuple[1][1])
Output:
Python
Tuple
Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or
remove tuple components as a result.
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
del tuple_
try:
print(tuple_)
except Exception as e:
print(e)
Output:
tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is known as a
nested tuple since it is contained inside another tuple. The name of the main tuple with
the index value, tuple[index], can be used to obtain the nested tuple, and we can access
each item of the nested tuple by using tuple[index-1][index-2].
92
employee = ((10, "Itika", 13000),)
print(employee)
employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 20001), (40, "Peter",
16395))
print(employee)
Output:
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter', 16395))
Unexpected changes and errors are more Because tuples don’t change they
6
likely to occur are far less error-prone.
93
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a
given key.
A dictionary is, in other words, a group of key-value pairs, where the values can be any
Python object. The keys, in contrast, are immutable Python objects, such as strings,
tuples, or numbers.
Curly brackets are the simplest way to generate a Python dictionary, although there are
other approaches as well. With many key-value pairs surrounded in curly brackets and a
colon separating each key from its value, the dictionary can be built. (:). The following
provides the syntax for defining the dictionary.
Syntax:
In the above dictionary Dict, The keys Name and Age are the strings which comes
under the category of an immutable object.
94
Note – Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
print(Dict)
Output
print(type(Employee))
95
Output
<class 'dict'>
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.
Example: The code defines a dictionary, prints its original content, and then uses the
‘del’ statement to delete the element associated with key 1. After deletion, it prints the
updated dictionary, showing that the specified element has been removed.
print("Dictionary =")
print(Dict)
del(Dict[1])
print(Dict)
Output
96
Dictionary Methods
Here is a list of in-built dictionary functions with their description. You can use these
functions to operate on a dictionary.
Method Description
97
Difference Between List and Dictionary in Python
Here are the differences present between List and Dictionary in Python:
Creation We can create a list by placing We can create a dictionary by placing all the
all the available elements into a available elements into a { } in the form of a
[ ] and separating them using key:vale. Here, we have to separate each pair of
“,” commas. available key-values using the “,” commas.
Data Type The indices in the case of a list The keys present in a dictionary can easily be
are basically integers that start of any given data type.
from the value 0.
Mode of We can access the elements in We can access the elements present in a
Accessing a key using indices. dictionary using the key-values.
Order of The entered order of elements We don’t have any guarantee of maintaining
Elements is always maintained. the order of the available elements.
98
UNIT V
File Handling in Python
File handling in Python is a powerful and versatile tool that can be used to
perform a wide range of operations. However, it is important to carefully consider the
advantages and disadvantages of file handling when writing Python programs, to
ensure that the code is secure, reliable, and performs well.
The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related information.
We can access the stored information (non-volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character like a
comma (,) or a newline character. Python executes the code line by line. So, it works in
one line and then asks the interpreter to start the new line again. This is a continuous
process in Python.
Python supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. The
concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, like other concepts of Python, this
concept here is also easy and short.
Python treats files differently as text or binary and this is important. Each line
of code includes a sequence of characters, and they form a text file. Each line of a file is
terminated with a special character, called the EOL or End of Line characters
like comma {,} or newline character.
It ends the current line and tells the interpreter a new one has begun. Let’s start
with the reading and writing files.
99
Disadvantages of File Handling in Python
Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the file
system (e.g. file permissions, file locks, etc.).
Security risks: File handling in Python can also pose security risks, especially if
the program accepts user input that can be used to access or modify sensitive files
on the system.
Complexity: File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be paid to
the code to ensure that files are handled properly and securely.
Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.
Text Files: Easily readable by humans, text files find their purpose in storing textual
data, such as documents, configuration files, and Python source code. Python offers
seamless handling of these files, facilitating straightforward text-based operations.
Binary Files: Contrary to text files, binary files store non-textual data, including
images, audio, video, or any data that defies textual representation. Manipulating binary
files necessitates specialized functions.
Access modes govern the type of operations possible in the opened file. It refers to how
the file will be used once its opened. These modes also define the location of the File
Handle in the file. The file handle is like a cursor, which defines from where the data
has to be read or written in the file and we can get Python output in text file.
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning
of the file. If the file does not exist, raises the I/O error. This is also the default mode
in which a file is opened.
100
Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not exist.
Write Only (‘w’) : Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the beginning of the file.
Creates the file if the file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file,
data is truncated and over-written. The handle is positioned at the beginning of the
file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted
at the end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if
it does not exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.
Note: The file should exist in the same directory as the Python script, otherwise, the
full address of the file should be written.
In this example, we will be opening a file to read-only. The initial file looks like the be
file = open("sample.txt")
print(file.read())
101
Output:
Hello Geek!
Python has a close() method to close a file. The close() method can be called more
than once and if any operation is performed on a closed file it raises a ValueError. The
below code shows a simple use of close() method to close an opened file.
file = open("sample.txt")
print(file.read())
file.close()
Output:
Python provides built-in functions for creating, writing, and reading files. Two
types of files can be handled in Python, normal text files and binary files (written in
binary language, 0s, and 1s).
Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in Python
by default.
102
Binary files: In this type of file, there is no terminator for a line, and the data is
stored after converting it into machine-understandable binary language.
write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
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.read([n])
readline() : Reads a line of the file and returns in form of a string.For specified n,
reads at most n bytes. However, does not reads more than one line, even if n exceeds the
length of the line.
File_object.readline([n])
103
Reading a File Using readlines()
readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
In this example, a file named “myfile.txt” is created and opened in write mode
("w"). Data is written to the file using write and writelines methods. The file is then
reopened in read and append mode ("r+"). Various read operations,
including read, readline, readlines, and the use of seek, demonstrate different ways to
retrieve data from the file. Finally, the file is closed.
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes
file1 = open("myfile.txt", "r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# byte from the beginning.
file1.seek(0)
print("Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
104
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
Hello
Hello
Th
Hello
105
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Output:
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
['Tomorrow \n']
106
Python File Methods
❮ PreviousNext ❯
Method Description
fileno() Returns a number that represents the stream, from the operating system's
perspective
107
seekable() Returns whether the file allows us to change the file position
File Positions
There are two more methods of file objects used to determine or get files positions.
tell()
seek()
tell():
This method is used to tell us the current position within the file which means the next
read or write operation will be performed that many bytes away from the start of the file.
Syntax :
obj.tell()
Example :
#create file object and show the use tell()
object=open("itvoyagers.txt",'w')
object.write("first statement n")
object.write("second statement n")
object=open("itvoyagers.txt",'r')
108
s=11
c=object.read(s)
print(object.tell()) #tells the position based on parameter passed in read operation
g=object.read()
print(object.tell()) #tells position after performing read() on entire file
seek():
This method is used to change the current position of file.This method has two main
parameters offset and from.
Syntax :
obj.seek(offset,from)
if from is set to 1 ,it means use the current position of the file as reference
position
if from is set to 2 ,it means use the end of the file as reference position
Example :
#create file object and show the use seek()
with open("itvoyagers.txt","r") as f:
s=10
c=f.read(s) #reads till 10 char
print(c,end=' ') #adds space after first read()
f.seek(0,0) #goes to start position in file
c=f.read(s)
print(c)
f.seek(0,1) #goes to current position in file
c=f.read(s)
print(c)
f.seek(0,2) #goes to end position in file
c=f.read(s)
print(c)
109
Python - Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.
To use this module, you need to import it first and then you can call any related
functions.
rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python3
import os
remove() Method
You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax
os.remove(file_name)
Example
#!/usr/bin/python3
import os
os.remove("text2.txt")
Print Page
110