UNIT-2
UNIT II COMPONENTS OF PYTHON PROGRAMMING
Operator Basics - Numbers - String - List - Tuples - Dictionaries - Files - Object Storage -
Type Conversion - Type Comparison - Statements – Assignments.
1. Explain in detail about the various operators in python with suitable
examples.
Operators are special symbols that perform operations on variables and values.
Types of Python Operators
A. Arithmetic Operators
B. Assignment Operators
C. Comparison Operators
D. Logical Operators
E. Bitwise Operators
F. Identity Operators-
G. Membership Operators
H. Ternary Operator
A. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2 * 3 = 6
/ Division 4/2=2
// Floor 10 // 3 = 3
Division
% Modulo 5%2=1
** Power 4 ** 2 = 16
PROBLEM SOLVING USING PYTHON/ UNIT-2 1 R. SATHISHKUMAR/AP/CSE
Example program
x = 15
y=4 Output
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x ** y)
print(x // y)
B. Assignment Operators
Assignment operators are used to assign values to variables.
PROBLEM SOLVING USING PYTHON/ UNIT-2 2 R. SATHISHKUMAR/AP/CSE
Example program: (Assignment
operator)
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
C. Comparison Operators
Comparison operators compare two values/variables and return a boolean result: True or False.
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True
Example program(comparison operator)
PROBLEM SOLVING USING PYTHON/ UNIT-2 3 R. SATHISHKUMAR/AP/CSE
D. Logical Operators
Logical operators are used to check whether an expression is True or False.
They are used in decision-making.
Operator Example Meaning
and a and b Logical AND: True only if both the operands
are True
or a or b Logical OR: True if at least one of the operands
is True
not not a Logical NOT: True if the operand is False and
vice versa.
Example program (Logical operator)
E. Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit,
hence the name.
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
PROBLEM SOLVING USING PYTHON/ UNIT-2 4 R. SATHISHKUMAR/AP/CSE
Example program(Bitwise operator)
F. Identity Operators
In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that they
are identical.
Is True if the operands are identical
is not True if the operands are not identical
Example:
PROBLEM SOLVING USING PYTHON/ UNIT-2 5 R. SATHISHKUMAR/AP/CSE
G. Membership Operators
In Python, in and not in are the membership operators that are used to test whether a value
or variable is in a sequence.
H. Ternary Operator
In Python, Ternary operators also known as conditional expressions are operators that
evaluate something based on a condition being true or false. It was added to Python in version
2.5. It simply allows testing a condition in a single line replacing the multiline if-else, making
the code compact.
PROBLEM SOLVING USING PYTHON/ UNIT-2 6 R. SATHISHKUMAR/AP/CSE
PROBLEM SOLVING USING PYTHON/ UNIT-2 7 R. SATHISHKUMAR/AP/CSE
2. Explain briefly about Numbers, String, List, Tuples, Dictionaries in
python.
In Python, Data Types refers to the classification/type of variables like Numbers, Strings,
Lists, Booleans, Tuples, Dictionaries and Sets. Type of the data can be checked by type()
method in Python.
Example program
PROBLEM SOLVING USING PYTHON/ UNIT-2 8 R. SATHISHKUMAR/AP/CSE
Numbers:
There are different categories of numbers in Python. Mostly used are Integers and Floats.
Integers are numbers without decimal point. It can be either negative or positive. For
Example: +15, -20 , +1000 . Floats are numbers with decimal point. Example: 15.01 , -20.81
, 0.08. You can perform many operations: Addition, Subtraction, Multiplication, Power, and
Division on Integers and Floats.
PROBLEM SOLVING USING PYTHON/ UNIT-2 9 R. SATHISHKUMAR/AP/CSE
Strings:
Strings refers to the sequence of characters in Python. Strings are always written in quotation
marks (single, double, or triple) and are Immutable. It means that the elements of string
cannot be edited after definition. Different operations that can be performed on Strings are
Indexing, Slicing, Concatenation, Repetition. Also, there are various in-built method in
Strings such as upper(), lower(),split(),strip(),lstrip(),rstrip() and many others that can be
studied. Below are various examples and explanation of operations and methods in String
with comments(denoted as ‘#’ for understanding purpose).
PROBLEM SOLVING USING PYTHON/ UNIT-2 10 R. SATHISHKUMAR/AP/CSE
String Indexing is used to return elements of a string at a particular index. In the
below example, ‘a[0]’ returns ‘H’ which is at 0'th index of string ‘a’. Whereas, String
Slicing extract a range of characters by using the slice syntax. Syntax for slicing :- [start
index: end index:step size]
PROBLEM SOLVING USING PYTHON/ UNIT-2 11 R. SATHISHKUMAR/AP/CSE
Lists
List is a collection of items containing data of different types. The indexing of List starts
with zero. If a length of a list is three, indexes are 0,1,2. I have shared multiple examples of
different List operations with output and comments for better understanding.
PROBLEM SOLVING USING PYTHON/ UNIT-2 12 R. SATHISHKUMAR/AP/CSE
Tuples
Tuples are immutable data types with a collection of different types of data. It does not
support object assignment. They are used for passing objects without getting changed for
data integrity. It is written with a small bracket. Let us see an example for clarity.
Note: that Tuples operations are similar to the Lists. Except, Tuples are not mutable and
defined with small brackets.
Dictionaries
Dictionaries in Python are key-value pairs collection. Key and Value can be of any data
type. There is a mapping of the key with the corresponding value. Keys are used to look-up
for the values. Dictionaries are written within curly ‘{}’ braces.
In the second example dictionary ‘newd’ is created and key ‘India’ and ‘Indonesia’ are
PROBLEM SOLVING USING PYTHON/ UNIT-2 13 R. SATHISHKUMAR/AP/CSE
added. Hence new elements can be added in the dictionary.
3. Describe File Objects in Python.
A file object allows us to use, access and manipulate all the user accessible files. One can
read and write any such files. When a file operation fails for an I/O-related reason, the
exception IOError is raised. This includes situations where the operation is not defined for
some reason, like seek() on a tty device or writing a file opened for reading. Files have the
following methods:
Examples of accessing a file: A file can be opened with a built-in function called open().
This function takes in the file’s address and the access_mode and returns a file object. There
are different types of access_modes:
PROBLEM SOLVING USING PYTHON/ UNIT-2 14 R. SATHISHKUMAR/AP/CSE
When you add 'b' to the access modes you can read the file in binary format rather than
the default text format. It is used when the file to be accessed is not in text.
read([size]):
It reads the entire file and returns it contents in the form of a string. Reads at most size
bytes from the file (less if the read hits EOF before obtaining size bytes). If the size
argument is negative or omitted, read all data until EOF is reached.
# Reading a file
f = open(__file__, 'r')
#read()
text = [Link](10)
print(text)
[Link]()
readline([size]):
It reads the first line of the file i.e till a newline character or an EOF in case of a file having a
single line and returns a string. If the size argument is present and non-negative, it is a
maximum byte count (including the trailing newline) and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.
# Reading a line in a file
f = open(__file__, 'r')
#readline()
PROBLEM SOLVING USING PYTHON/ UNIT-2 15 R. SATHISHKUMAR/AP/CSE
text = [Link](20)
print(text)
[Link]()
readlines([sizehint]): It reads the entire file line by line and updates each line to a list
which is [Link] until EOF using readline() and return a list containing the lines
thus read. If the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after rounding up to an
internal buffer size) are read.
# Reading a file
f = open(__file__, 'r')
#readline()
text = [Link](25)
print(text)
[Link]()
write(string): It writes the contents of string to the file. It has no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.
# Writing a file
f = open(__file__, 'w')
line = 'Welcome Geeks\n'
#write()
[Link](line)
[Link]()
More Examples in different modes:
# Reading and Writing a file
f = open(__file__, 'r+')
lines = [Link]()
[Link](lines)
[Link]()
# Writing and Reading a file
f = open(__file__, 'w+')
PROBLEM SOLVING USING PYTHON/ UNIT-2 16 R. SATHISHKUMAR/AP/CSE
lines = [Link]()
[Link](lines)
[Link]()
# Appending a file
f = open(__file__, 'a')
lines = 'Welcome Geeks\n'
[Link](lines)
[Link]()
# Appending and reading a file
f = open(__file__, 'a+')
lines = [Link]()
[Link](lines)
[Link]()
writelines(sequence): It is a sequence of strings to the file usually a list of strings or any other
iterable data type. It has no return value.
# Writing a file
f = open(__file__, 'a+')
lines = [Link]()
#writelines()
[Link](lines)
[Link]()
tell(): It returns an integer that tells us the file object’s position from the beginning of the file
in the form of bytes
# Telling the file object position
f = open(__file__, 'r')
lines = [Link](10)
#tell()
print([Link]())
[Link]()
seek(offset, from_where): It is used to change the file object’s position. Offset indicates the
number of bytes to be moved. from_where indicates from where the bytes are to be moved.
PROBLEM SOLVING USING PYTHON/ UNIT-2 17 R. SATHISHKUMAR/AP/CSE
# Setting the file object position
f = open(__file__, 'r')
lines = [Link](10)
print(lines)
#seek()
print([Link](2,2))
lines = [Link](10)
print(lines)
[Link]()
flush(): Flush the internal buffer, like stdio‘s fflush(). It has no return value. close()
automatically flushes the data but if you want to flush the data before closing the file then you
can use this method.
# Clearing the internal buffer before closing the file
f = open(__file__, 'r')
lines = [Link](10)
#flush()
[Link]()
print([Link]())
[Link]()
fileno(): Returns the integer file descriptor that is used by the underlying implementation to
request I/O operations from the operating system.
# Getting the integer file descriptor
f = open(__file__, 'r')
#fileno()
print([Link]())
[Link]()
isatty(): Returns True if the file is connected to a tty(-like) device and False if not.
# Checks if file is connected to a tty(-like) device
f = open(__file__, 'r')
PROBLEM SOLVING USING PYTHON/ UNIT-2 18 R. SATHISHKUMAR/AP/CSE
#isatty()
print([Link]())
[Link]()
next(): It is used when a file is used as an iterator. The method is called repeatedly. This method
returns the next input line or raises StopIteration at EOF when the file is open for reading(
behaviour is undefined when opened for writing).
# Iterates over the file
f = open(__file__, 'r')
#next()
try:
while [Link]():
print([Link]())
except:
[Link]()
truncate([size]): Truncate the file's size. If the optional size argument is present, the file is
truncated to (at most) that size. The size defaults to the current position. The current file
position is not changed. Note that if a specified size exceeds the file's current size, the result is
platform-dependent: possibilities include that the file may remain unchanged, increase to the
specified size as if zero-filled, or increase to the specified size with undefined new content.
# Truncates the file
f = open(__file__, 'w')
#truncate()
[Link](10)
[Link]()
close(): Used to close an open file. A closed file cannot be read or written any more.
# Opening and closing a file
f = open(__file__, 'r')
#close()
[Link]()
PROBLEM SOLVING USING PYTHON/ UNIT-2 19 R. SATHISHKUMAR/AP/CSE
Attributes:
1. closed: returns a boolean indicating the current state of the file object. It returns
true if the file is closed and false when the file is open.
2. encoding: The encoding that this file uses. When Unicode strings are written to
a file, they will be converted to byte strings using this encoding.
3. mode: The I/O mode for the file. If the file was created using the open() built-
in function, this will be the value of the mode parameter.
4. name: If the file object was created using open(), the name of the file.
5. newlines: A file object that has been opened in universal newline mode have
this attribute which reflects the newline convention used in the file. The value
for this attribute are "\r", "\n", "\r\n", None or a tuple containing all the newline
types seen.
6. softspace: It is a boolean that indicates whether a space character needs to be
printed before another value when using the print statement.
f = open(__file__, 'a+')
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
4. Discuss Type Conversion in python.
Type conversion means changing the data type of a value. For example, converting an
integer (5) to a float (5.0) or a string ("10") to an integer (10). In Python, there are two types
of type conversion:
1. Implicit Conversion: Python changes the data type by itself while running the code,
to avoid mistakes or data loss.
2. Explicit Conversion: You change the data type on purpose using functions like int(),
float() or str().
Implicit Type Conversion
PROBLEM SOLVING USING PYTHON/ UNIT-2 20 R. SATHISHKUMAR/AP/CSE
In implicit conversion, Python automatically converts one data type into another during
expression evaluation. This usually happens when a smaller data type like int is combined
with a larger one like float in an operation.
Example:
Explicit Type Conversion
Explicit conversion (or type casting) is when you manually convert the data type of a value
using Python’s built-in functions. This is helpful when you want to control how the data is
interpreted or manipulated in your code. Some common type casting functions include:
int() converts a value to an integer
float() converts a value to a floating point number
str() converts a value to a string
bool() converts a value to a Boolean (True/False)
PROBLEM SOLVING USING PYTHON/ UNIT-2 21 R. SATHISHKUMAR/AP/CSE
Explanation: a = int(s), we explicitly convert it to an integer. This manual type change is
called explicit type conversion and a becomes 100 of type <class 'int'>.
Example 2: String to Tuple, Set and List
PROBLEM SOLVING USING PYTHON/ UNIT-2 22 R. SATHISHKUMAR/AP/CSE
tuple(s) keeps all characters including duplicates in order.
set(s) removes duplicates and returns an unordered collection.
list(s) returns a list of characters from the string.
Example 3: Other Conversions – Complex, String, Dictionary
PROBLEM SOLVING USING PYTHON/ UNIT-2 23 R. SATHISHKUMAR/AP/CSE
5. What is type comparison in python?
Comparing the type of data
Example program
>>> import types
>>> x = "mystring"
>>> isinstance(x, [Link]) True
>>> x = 5
>>> isinstance(x, [Link]) True
>>> x = None
>>> isinstance(x, [Link]) True
6. What is statements and assignments
Assignment operators are used to assigning values to the operands on the left-
hand side.
Assignment operators assign the right-hand side values to the operand that is present
on the left-hand side.
The assignment operator in Python is used as the "=" symbol.
Example,
X = 5 Y = b-c
Statements
Any instruction written in the source code and executed by the Python interpreter is
called a statement.
The Python language has many different types of statements like assignment
statements, conditional statements, looping statements, etc., that help a programmer
get the desired output.
7. What are the different types of assignments in python
Single assignment
Augmented assignment
Multiple assignment
Chained assignment
Unpacking assignment
PROBLEM SOLVING USING PYTHON/ UNIT-2 24 R. SATHISHKUMAR/AP/CSE