0% found this document useful (0 votes)
18 views10 pages

Python Dictionaries and Functions Guide

Unit III covers Python dictionaries, which are unordered collections of key-value pairs, and functions, which are reusable code blocks. It explains how to create, access, modify, and delete dictionary entries, as well as the definition, calling, and argument types of functions. Additionally, it introduces recursion, variable scope, modules, file handling, exception handling, and basic data analysis with Pandas.

Uploaded by

skekhero
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

Python Dictionaries and Functions Guide

Unit III covers Python dictionaries, which are unordered collections of key-value pairs, and functions, which are reusable code blocks. It explains how to create, access, modify, and delete dictionary entries, as well as the definition, calling, and argument types of functions. Additionally, it introduces recursion, variable scope, modules, file handling, exception handling, and basic data analysis with Pandas.

Uploaded by

skekhero
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

📚 Unit III: Dictionaries and Functions

🔑 Dictionaries
A dictionary in Python is an unordered, mutable collection
that stores data as key:value pairs. Keys must be unique and
immutable (e.g., strings, numbers, tuples).
1. Introduction and Accessing Values
 Creation: Defined by enclosing key-value pairs in curly

braces ({}).
Python
student_info = {
"roll_no": 101,
"name": "Alice",
"course": "MCA"
}
 Accessing:

o Square Brackets: dict[key] $\rightarrow$ Raises a

KeyError if the key is not found.


Python
print(student_info["name"]) # Output: Alice
o get() method: [Link](key, default) $\rightarrow$

Returns the value or a specified default (or None),


preventing a crash.
Python
print(student_info.get("city", "N/A")) # Output: N/A
2. Working with Dictionaries
 Adding/Updating: Use assignment with the key.

Python
student_info["city"] = "Noida" # Adds a new key
student_info["roll_no"] = 102 # Updates existing key
 Removing:
o del dict[key]: Deletes the item by key.
o [Link](key): Removes the item and returns its value.

o [Link](): Empties the dictionary.

3. Properties and Functions


Property/Function Description Example
Returns the
number of len(student_info) $\
len(dict)
key-value rightarrow$ 4
pairs.
Returns a
[Link]() view object of student_info.keys()
all keys.
Returns a
[Link]() view object of student_info.values()
all values.
Returns a
view object of
[Link]() student_info.items()
all items (key-
value tuples).
Merges dict2
[Link](dict2) [Link](d2)
into dict1.

⚙️Functions
A function is a reusable block of code that performs a specific
task.
1. Defining & Calling a Function
 Defining: Use the def keyword.
 Calling: Use the function name followed by parentheses ().
Python
def calculate_area(length, width): # length, width are
parameters
return length * width

area = calculate_area(5, 10) # 5, 10 are arguments


print(area) # Output: 50
2. Passing Arguments and Data Types
Python uses Pass by Object Reference.
 Immutable Types (int, string, tuple): Modifications inside

the function create a new local object; the original object


remains unchanged.
 Mutable Types (list, dictionary): Modifying the object in-

place (e.g., [Link]()) changes the original object


outside the function.
3. Different Types of Arguments
Argument
Description Example
Type
Matched by their
Positional func(10, 20)
order.
Matched by
Keyword name; order func(b=20, a=10)
doesn't matter.
Assigned a
Default default value in def func(a, b=5): ...
the definition.
Argument
Description Example
Type
Collects non-
Arbitrary
keyword
Positional def sum_all(*nums): ...
arguments into a
(*args)
tuple.
Collects
Arbitrary def
keyword
Keyword print_details(**details): .
arguments into a
(**kwargs) ..
dictionary.
4. Recursion
Recursion is when a function calls itself. It must have a base
case to terminate.
Example (Factorial):
Python
def factorial(n):
if n == 0: # Base Case
return 1
else: # Recursive Case
return n * factorial(n - 1)
5. Scope of Variables
Scope determines where a variable can be accessed, following
the LEGB Rule: Local, Enclosing, Global, Built-in.
 Use the global keyword to modify a global variable from

within a function.
 Use the nonlocal keyword to modify a variable in an

enclosing scope (nested functions).


📦 Unit IV: Modules, Packages, and File Handling
🧩 Modules and Packages
1. User-defined Modules and Packages
 Module: A Python file (.py) containing code. Use import

module_name.
 Package: A directory containing related modules and an

__init__.py file.
2. Standard Library Modules
Module Purpose Example
Generating random
random [Link](1, 10)
numbers.
Array/matrix
operations
numpy (fundamental for [Link]([1, 2, 3])
scientific
computing).
Advanced scientific
Scipy and technical [Link](0.95)
computing.
Mathematical
Math functions (e.g., sqrt, [Link](25)
pi).
Date and time
datetime [Link]()
manipulation.
Sys System-specific [Link]
Module Purpose Example
parameters and
functions.
3. Regular Expressions (re module)
Used to define search patterns.

Location of
Function Purpose Example
Match
Only at the
Check for a
beginning [Link](r"A",
[Link]() pattern
of the "ABC")
match.
string.
Search for
Anywhere
the first [Link](r"B",
[Link]() in the
pattern "ABC")
string.
occurrence.
Substitute all
[Link](r"\s", "-",
[Link]() occurrences
Anywhere. "a b") $\
(Replace) of the
rightarrow$ 'a-b'
pattern.

📁 File Handling
1. File Types, Modes, and Opening
 File Types: Text Files (sequence of characters, handles

EOL) and Binary Files (sequence of raw bytes, no EOL


handling).
 File Modes: Specify the operation.
o r: Read (default).
o w: Write (creates, overwrites if exists).

o a: Append (creates, adds to end).

o Append b for binary (e.g., rb, wb).

 Opening/Closing:

Python
# Recommended approach: 'with' ensures the file is closed
automatically
with open("[Link]", "w") as f:
[Link]("Hello MCA")
2. Accessing and Manipulating Files
 Reading:

o [Link](): Reads the entire file content.

o [Link](): Reads a single line.

o [Link](): Reads all lines into a list.

 File Pointers:

o [Link](): Returns the current position of the pointer.

o [Link](offset, whence): Moves the pointer. (whence=0

is start, 1 is current, 2 is end).


 Renaming/Deleting: Use the os module.

Python
import os
[Link]("[Link]", "[Link]")
[Link]("[Link]")
3. Binary Files
Binary files are used with the b mode. The pickle module is
used to serialize (dump) and deserialize (load) Python objects
into binary files.
Python
import pickle
data = {'a': 1}
with open("[Link]", "wb") as f:
[Link](data, f)

⚠️Unit V: Exception Handling and Data Analysis Basics


🚫 Exception Handling
1. Exception and Exception Handling
 An Exception is an event that occurs during program

execution that disrupts its normal flow (e.g., TypeError,


ZeroDivisionError).
 Exception Handling manages these events to prevent

program crashes.
2. try, except, finally
 try: Contains the "risky" code.

 except: Executes if an exception occurs in try. You can

specify the exception type.


 else: Executes only if the try block succeeds (no

exceptions).
 finally: Executes always, regardless of whether an

exception occurred or was handled (useful for cleanup).


Example:
Python
try:
result = 10 / int(input("Enter number: "))
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input.")
else:
print(f"Result: {result}")
finally:
print("Cleanup done.")
3. User Defined Exceptions
Create custom exceptions by defining a class that inherits from
the built-in Exception class. Use the raise keyword to trigger
them.
Python
class InsufficientFunds(Exception):
pass # Custom class for a specific scenario

amount = 50
if amount < 100:
raise InsufficientFunds("Minimum withdrawal is 100.")

📊 Basics of Python for Data Analysis


The Pandas library is key for data analysis, offering two main
structures: Series and DataFrames.
1. Introduction to Series
 A Series is a one-dimensional labeled array. It's like a

single column of data in a spreadsheet.


 It consists of data and an associated index (labels).

Python
import pandas as pd
s = [Link]([10, 20, 30], index=['A', 'B', 'C'])
2. Introduction to DataFrames
 A DataFrame is a two-dimensional, tabular data structure

(rows and columns). It's the most common object for data
manipulation.
 It can be viewed as a collection of Series objects that share

the same index.


Example (DataFrame Creation and Access):
Python
data = {
'Name': ['Mia', 'Joe'],
'Age': [28, 35]
}
df = [Link](data)

# Accessing a column (returns a Series)


print(df['Name'])

# Accessing a row by label (index)


print([Link][0])

# Accessing a row by integer position


print([Link][1])

Common questions

Powered by AI

Dictionaries in Python ensure data integrity and efficient retrieval of values through the use of unique and immutable keys. This property prevents duplicate entries, ensuring that each key:value pair is distinct, which maintains data integrity. The underlying hash table implementation allows for average O(1) time complexity in retrieving values by key, making the process efficient .

Arbitrary arguments in Python, *args and **kwargs, play a crucial role in enhancing function flexibility by allowing functions to accept varying numbers of positional and keyword arguments, respectively. *args collects extra positional arguments into a tuple, while **kwargs collects keyword arguments into a dictionary. This flexibility enables the creation of more generalized functions that can handle a variety of inputs without needing to specify the exact number or names of arguments in advance .

Function scopes in Python enhance program functionality by providing encapsulation, preventing variables from being accessed outside their intended scope, which reduces errors and unintended interactions. They restrict functionality by limiting a variable's access to only within its defined scope. The LEGB rule (Local, Enclosing, Global, Built-in) governs how names are resolved, allowing functions to modify global variables using the global keyword or modify enclosing scope variables using the nonlocal keyword, thus balancing functional enhancement and restriction .

Exception handling mechanisms in Python are significant for maintaining program stability as they provide a structured way to manage unexpected runtime errors, preventing programs from crashing and ensuring graceful degradation. Using try, except, else, and finally blocks allows developers to isolate 'risky' code, handle specific exceptions, execute code conditionally, and perform cleanup tasks reliably. This approach facilitates robust error handling and resource management, safeguard against program termination, and contribute to a smoother user experience .

File modes in Python dictate how files are accessed and manipulated, which directly affects operations. For instance, mode 'r' (read) opens a file for reading, 'w' (write) for overwriting, and 'a' (append) for adding data at the end. The choice of mode can impact data consistency, such as using 'w' can lead to data loss if not handled carefully because it overwrites the file content. On the other hand, 'a' ensures existing data isn't lost but may lead to unintended data duplication if not managed properly .

The advantages of recursion in Python include its ability to simplify code that deals with problems defined in terms of smaller subproblems, such as the calculation of factorials or performing tree traversals. Recursion can make code more intuitive and concise. However, potential challenges include the risk of a stack overflow due to excessive recursive depth, especially if there's no base case to terminate recursion. It also tends to have higher memory usage compared to iterative approaches, since each recursive call adds a new layer to the stack .

User-defined exceptions in Python enhance customization and clarity in error management by allowing developers to define specific error cases tailored to the application's context. By creating custom exception classes that inherit from Python's built-in Exception class, developers can raise meaningful error messages that convey precise details of what's wrong, improving code readability and maintainability. For instance, defining an InsufficientFunds exception makes it clear what the error represents, assisting in debugging and enforcing business logic .

The key advantages of using Pandas' DataFrame structure for data manipulation in Python include its tabular format, which closely resembles a spreadsheet, making it intuitive for data analysis. DataFrames allow for efficient handling of data operations such as filtering, grouping, and aggregation. They support heterogeneous data types and provide powerful data alignment and merging capabilities. Additionally, the extensive suite of methods and functions simplifies tasks like missing data handling and transformation, which enhances productivity and reduces code complexity .

Modules and packages in Python facilitate code reuse and organization by encapsulating related functions, classes, and variables into separate files (modules) and directories (packages). This structure allows for modular programming, where modules can be imported into various projects, enabling code reuse without redundancy. Packages aid in organizing modules into hierarchies, simplifying complex project structures and making code easier to manage, test, and maintain. The use of user-defined and standard library modules further enhances the functionality and reliability of software development projects .

The 'finally' block in Python's exception handling plays a crucial role in ensuring that clean-up actions are performed regardless of whether an exception was raised or handled. This guarantees that resources such as files or network connections are properly closed and released, preventing resource leaks and potential data corruption. As the 'finally' block executes every time, it provides a reliable way to maintain program integrity and ensure that the program's environment is left in a consistent state post-execution .

You might also like