Python Data Structures, Modules, File Handling, and More

Mutable and Immutable Data Structures

Ans: Data types in Python are divided into two categories:

  • Immutable data types: Values cannot be changed.
    • Numbers
    • String
    • Tuple
  • Mutable data types: Values can be changed.
    • List
    • Dictionaries
    • Sets

1. Numbers

Python supports integers, floats, and complex numbers. An integer is a number without a decimal point, for example, 5, 6, 10, etc. A float is a number with a decimal point, for example, 6.7, 6.0, 10.99, etc. A complex number has a real and imaginary part, for example, 7+8j, 8+11j, etc.

Example:

  
# int
num1 = 10
num2 = 100

# float
a = 10.5
b = 8.9

# complex numbers
x = 3 + 4j
y = 9 + 8j
  

2. String

A string is usually a bit of text (a sequence of characters). In Python, we use ” (double quotes) or ‘ (single quotes) to represent a string. There are several ways to create strings in Python:

  1. We can use ‘ (single quotes), see the string str in the following code.
  2. We can use ” (double quotes), see the string str2 in the source code below.
  3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line strings in Python.

Example:

  
str = 'beginnersbook'
str2 = "Chaitanya"

# multi-line string
str3 = """Welcome to Pythonsbook"""
str4 = '''This is a tech paper'''
  

3. Tuple

In Python, a tuple is similar to a list, except that the objects in a tuple are immutable, which means we cannot change the elements of a tuple once assigned. On the other hand, we can change the elements of a list. To create a tuple in Python, place all the elements in a () parenthesis, separated by commas. A tuple can have heterogeneous data items; a tuple can have a string and a list as data items as well.

Example:

  
# tuple of strings
my_data = ("hi", "hello", "bye")

# tuple of int, float, string
my_data2 = (1, 2.8, "Hello World")

# tuple of string and list
my_data3 = ("Book", [1, 2, 3])

# tuples inside another tuple
# nested tuple
my_data4 = ((2, 3, 4), (1, 2, "hi"))
  

4. List

A list is a data type that allows you to store various types of data in it. A list is a compound data type, which means you can have different data types under a list; for example, we can have integer, float, and string items in the same list. To create a list, all you have to do is to place the items inside a square bracket [], separated by commas.

Example:

  
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]

# list of int, float and strings
mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]

# an empty list
nodata_list = []
  

5. Dictionaries

A dictionary is a mutable data type in Python. A Python dictionary is a collection of key and value pairs separated by a colon (:), enclosed in curly braces {}. The left side of the colon (:) is the key, and the right side of the : is the value.

Example:

  
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
  

6. Sets

A set is an unordered and unindexed collection of items in Python. Unordered means when we display the elements of a set, they will come out in a random order. Unindexed means we cannot access the elements of a set using the indexes like we can in lists and tuples. The elements of a set are defined inside curly brackets and are separated by commas.

Example:

  
myset = {1, 2, 3, 4, "hello"}
  

Python Modules: Definition and Usage

Ans: A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes, and variables. A module can also include runnable code.

Example:

The Python code for a module named aname normally resides in a file named aname.py. Here’s an example of a simple module, support.py:

  
def print_func(par):
  print("Hello : ", par)
  return
  

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

Example:

Save this code in a file named mymodule.py:

  
def greeting(name):
  print("Hello, " + name)
  

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

Example:

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

  
import mymodule

mymodule.greeting("ABC")
  

Character Frequency in a File

Ans: Here’s Python code to count the frequency of each character in a given file:

  
import collections
import pprint

file_input = input('File Name: ')

with open(file_input, 'r') as info:
  count = collections.Counter(info.read().upper())
  value = pprint.pformat(count)
  print(value)
  

Copy File Content in Python

Ans: Here’s a Python program to read the contents of abc.txt and write the same content to pqr.txt:

  
with open('abs.txt','r') as firstfile, open('prq.txt','w') as secondfile:
  for line in firstfile:
      secondfile.write(line)
  

Identity Operators in Python

Ans: Identity operators in Python are:

  • is
  • is not

Python Exception Handling

Ans: An exception in Python is an error that occurs during program execution, disrupting the normal flow of instructions. Instead of crashing, the program can “catch” the exception and handle it gracefully using try and except blocks. Common exceptions include ZeroDivisionError, IndexError, and FileNotFoundError. You can also define custom exceptions. The finally block can be used for cleanup actions, ensuring certain code runs regardless of whether an exception was raised.

File Opening Modes in Python

Ans: Different Modes of Opening a File:

1. Read Mode (‘r’)

  • Purpose: Opens a file for reading.
  • Behavior:
    • The file pointer is placed at the beginning of the file.
    • If the file does not exist, a FileNotFoundError is raised.
  • Example:
          
    file = open('example.txt', 'r')
    content = file.read()
    file.close()
          
        

2. Write Mode (‘w’)

  • Purpose: Opens a file for writing.
  • Behavior:
    • If the file already exists, its contents are truncated (i.e., deleted).
    • If the file does not exist, a new file is created.
  • Example:
          
    file = open('example.txt', 'w')
    file.write("This will overwrite the existing content.")
    file.close()
          
        

Python Modes

Python has two basic modes:

  • Script (Normal Mode)
  • Interactive Mode

Classes and Objects in Python

Ans:

Class: A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together.

Object: An object is an instance of a class that has some attributes and behavior. Objects can be used to access the attributes of the class.