DEV Community

Ram-Tech-cd
Ram-Tech-cd

Posted on

The Zero-Code Guide to Python: Functions, Built-in Errors & Clean File Handling

1. Functions & Parameters

Defining & Calling:Modular, reusable logic blocks created to run only when explicitly called by name.

Positional Arguments:Standard inputs passed in sequential order matching the parameter definition.

Default Values:Pre-set parameters that act as fallbacks whenever an input is omitted during invocation.

Keyword Arguments:Explicit inputs passed as name-value pairs, providing flexibility over parameter order.

Variable Positional Arguments (*args):Gathers any number of extra unnamed inputs into a single ordered collection.

Variable Keyword Arguments (**kwargs):Bundles any number of extra named inputs into a key-value dictionary collection.

Return Values:The output produced and passed back to the caller; multiple outputs automatically group into a sequence.

Local vs. Global Scope:Variables inside a function remain private to that run, while global variables require explicit declaration to be modified from within a local block.

Composability:Functions cleanly trigger or feed data into other functions to break logic into manageable steps.

2. Built-in Exceptions

ZeroDivisionError:Attempting to divide any number by zero.

ValueError:Supplying the correct data type containing an invalid value, such as parsing non-numeric text into an integer.

TypeError:Performing an operation across incompatible data types, like combining text directly with numbers.

IndexError:Accessing a sequential list index that sits beyond the boundaries of the list.

KeyError:Querying an identifier or key that does not exist in a dictionary.

NameError:Calling an identifier or variable name that was never initialized or defined.

AttributeError:Executing an unsupported action on an object type, such as appending items to an immutable tuple.

FileNotFoundError:Accessing or reading an external document that does not exist at the target path.

3. Error Handling & Flow Control

try / except: Intercepts and isolates specific runtime failures to prevent the script from crashing.

else:Executes secondary instructions strictly when the primary block finishes without any raised errors.

finally:Runs cleanup tasks unconditionally, regardless of whether failures occurred.

raise:Explicitly triggers built-in errors or user-defined custom exception classes when custom rules fail.

4. File Operations

File Access Modes: Read mode inspects content, Write mode creates or overwrites, and Append mode adds fresh data to the end without wiping existing entries.

Context Manager (with):Opens a temporary resource stream and guarantees automatic closure to prevent system memory leaks and locked files.

Colab Notebook: https://colab.research.google.com/drive/1YhGh7nGBKqfx1KlPY-ziJWxY7Gonuk-1?usp=sharing

GitHub Profile:
https://github.com/Ram-Tech-Cd/Functions-and-Error-Handling-/blob/main/function_errors.py

Top comments (0)