<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged python-3</title>
<link>https://coderlegion.com/tag/python-3</link>
<description>Powered by Question2Answer</description>
<item>
<title>Building a survey-based ML pipeline to find out what's really holding SEE and +2 graduates back</title>
<link>https://coderlegion.com/24296/building-survey-based-ml-pipeline-to-find-out-whats-really-holding-see-and-graduates-back</link>
<description>&lt;p&gt;Building a survey-based ML pipeline to find out what's really holding SEE and +2 graduates back&lt;br&gt;
The question I couldn't stop thinking about&lt;br&gt;
Every year, hundreds of thousands of students in Nepal finish their SEE or +2 exams and hit the same fork in the road: keep studying, start building skills, or jump into the job market — usually with very little structured guidance. I'd heard the anecdotes a hundred times: &quot;graduates feel unprepared,&quot; &quot;the education system doesn't teach real skills,&quot; &quot;there's no mentorship.&quot; But I hadn't seen actual data behind any of it.&lt;/p&gt;
&lt;p&gt;So I built some.&lt;/p&gt;
&lt;p&gt;This post walks through a full data science project — survey design, cleaning, exploratory analysis, a custom scoring model, and machine learning — that tries to answer three questions:&lt;/p&gt;
&lt;p&gt;What skills are SEE/+2 graduates actually building, and how?&lt;/p&gt;
&lt;p&gt;What's really blocking them from feeling career-ready?&lt;/p&gt;
&lt;p&gt;What factors predict that readiness — effort, background, or something else?&lt;/p&gt;
&lt;p&gt;Getting the data&lt;br&gt;
I designed a 23-question Google Form covering demographics, current activity, skill-building habits (what, why, where, how many hours/week), four Likert-scale questions on career clarity/confidence/awareness, top challenges, career interests, and views on Nepal's education system. It went out primarily through an Instagram channel and pulled in 171 raw responses, cleaned down to 167 after dropping non-consenting and blank submissions.&lt;/p&gt;
&lt;p&gt;Worth being upfront about this from the start: Instagram distribution means the sample skews toward urban, digitally active students, disproportionately from Bagmati province. This isn't a nationally representative sample — and every result below should be read with that in mind.&lt;/p&gt;
&lt;p&gt;Cleaning: the unglamorous 80%&lt;br&gt;
Google Forms exports are messy by default — full question text as column headers, multi-select checkboxes crammed into single semicolon-separated strings, free-text &quot;Other&quot; answers full of near-duplicates (&quot;not learning&quot;, &quot;Not Learning&quot;, &quot;no where&quot; all meaning the same thing).&lt;/p&gt;
&lt;p&gt;The cleaning pipeline:&lt;/p&gt;
&lt;p&gt;Renamed all 23 columns to short, code-friendly names&lt;/p&gt;
&lt;p&gt;Converted bucketed answers (age ranges, GPA bands, weekly hours) into numeric midpoints for correlation/modeling, while keeping the original labels for display&lt;/p&gt;
&lt;p&gt;Exploded 4 multi-select questions into 34 individual binary columns, folding rare free-text answers into a single Other bucket instead of creating one noisy column per typo&lt;/p&gt;
&lt;p&gt;Dropped rows with no consent or with all four core Likert answers blank&lt;/p&gt;
&lt;p&gt;That left a clean 167×66 dataset, ready for analysis.&lt;/p&gt;
&lt;p&gt;What the data actually shows&lt;br&gt;
Who responded: the sample skews toward Bagmati (37%) and the 19–21 age group, split fairly evenly by gender, with Management and Science as the dominant academic streams.&lt;/p&gt;
&lt;p&gt;What they're learning: Programming/Coding (41 respondents) and Data Analyst/Data Science (40) lead, followed by Public Speaking/Communication (35), AI/ML (33), and Graphic Design (31). But 22% of respondents aren't learning any new skill at all — a real gap worth flagging.&lt;br&gt;
&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=14399909022811574711&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Top skills chart&lt;br&gt;
Why and where they learn: &quot;To get a job&quot; and &quot;personal interest&quot; dominate the motivation side. On the source side, YouTube and free content are by far the most common learning channel — institutes, mentors, and paid courses are comparatively underused, despite (as the modeling below shows) being associated with higher readiness.&lt;/p&gt;
&lt;p&gt;What's blocking them: financial problems are the single most common challenge (54% of respondents), followed by lack of guidance/mentorship and lack of networking. Poor internet access and family pressure are comparatively minor. This isn't uniform across provinces either — less-connected provinces like Karnali and Sudurpaschim lean more toward financial/infrastructure barriers, while Bagmati's challenge profile leans more toward networking and mentorship gaps.&lt;br&gt;
&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=281509087949082061&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Top challenges chart&lt;br&gt;
Building a Career Readiness Score&lt;br&gt;
There's no pre-existing &quot;readiness&quot; label in survey data like this — it has to be constructed. I built a transparent, weighted 0–100 score from seven normalized signals:&lt;/p&gt;
&lt;p&gt;weights = {&lt;br&gt;
'clarity': 0.20, 'market': 0.15, 'edu': 0.10, 'conf': 0.20,&lt;br&gt;
'hours': 0.15, 'breadth': 0.10, 'challenge_inv': 0.10,&lt;br&gt;
}&lt;/p&gt;
&lt;p&gt;Career clarity and confidence get the highest weight since they most directly represent &quot;feeling ready&quot;; active effort (hours invested, skill breadth) and challenge burden are supporting signals. I kept the weights explicit rather than hidden — this is the one place in the whole pipeline that's a judgment call rather than purely mechanical, and it deserves to be visible.&lt;/p&gt;
&lt;p&gt;The result: an average score of 50.5/100, with most students landing in the &quot;Medium&quot; band — engaged, but not confidently prepared.&lt;br&gt;
&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=260286769916593978&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Readiness score distribution&lt;br&gt;
Does GPA or effort predict readiness? Not really.&lt;br&gt;
Here's where it got interesting. I trained two models — Linear Regression as an interpretable baseline, and a Random Forest for non-linear patterns — to predict the readiness score using only context features (demographics, learning habits, career interest). I deliberately excluded the Likert questions that built the score itself, to avoid circular prediction.&lt;/p&gt;
&lt;p&gt;Model R² MAE RMSE&lt;br&gt;
Linear Regression -0.26 15.31 19.54&lt;br&gt;
Random Forest 0.12 13.15 16.36&lt;br&gt;
Random Forest beat Linear Regression on every metric — readiness depends on non-linear combinations of context, not a simple additive relationship. That said, an R² of 0.12 is modest, and with only 167 rows and no attitudinal predictors allowed, this model is exploratory and directional, not a precision instrument.&lt;/p&gt;
&lt;p&gt;What mattered most, according to feature importance:&lt;br&gt;
&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=15085888916690848928&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Feature importance chart&lt;br&gt;
GPA, whether a student thinks the education system is adequate, and their learning channel (institute or paid course vs. informal self-study) came out as the strongest predictors — ahead of age, gender, or province. Three of the top four predictors are about structural/environmental context, not personal effort. That lines up with the EDA finding that hours invested alone doesn't reliably predict how ready someone feels — how and where someone learns seems to matter more.&lt;/p&gt;
&lt;p&gt;So what actually helps?&lt;br&gt;
Putting it together, a few things stood out enough to act on:&lt;/p&gt;
&lt;p&gt;Mentorship and networking gaps matter more than skill access. Career-guidance programs should target these specifically rather than assuming more course content is the fix.&lt;/p&gt;
&lt;p&gt;Structured learning channels correlate with higher readiness than free YouTube content alone — worth encouraging alongside (not instead of) free resources.&lt;/p&gt;
&lt;p&gt;Financial barriers are the single biggest reported challenge. Scholarships and subsidized training pathways would likely move the needle more than another course catalog.&lt;/p&gt;
&lt;p&gt;The education-support gap is real. Of the four Likert measures, students rated their formal education as least helpful in preparing them for a career — a disconnect worth deeper, qualitative follow-up.&lt;/p&gt;
&lt;p&gt;Limitations, stated plainly&lt;br&gt;
Convenience sample via a single Instagram channel — urban/Bagmati skew, not nationally representative.&lt;/p&gt;
&lt;p&gt;Career clarity/confidence/awareness are self-reported and subjective.&lt;/p&gt;
&lt;p&gt;n=167 is small for machine learning — treat the model as directional, not predictive.&lt;/p&gt;
&lt;p&gt;Cross-sectional data (single point in time) — can't establish causality or track change over time.&lt;/p&gt;
&lt;p&gt;Closing thoughts&lt;br&gt;
This was as much an exercise in disciplined data cleaning and honest reporting as it was in modeling. The most useful output wasn't the R² score — it was being able to say, with actual evidence, that the story students tell about &quot;the system doesn't prepare us&quot; is more specific than it sounds: it's not a uniform failure, it's a mentorship and networking gap layered on top of financial constraints, and where someone learns matters more than how many hours they put in.&lt;/p&gt;
&lt;p&gt;The full notebook, cleaned dataset, report, and presentation are on GitHub — link below. If you work in EdTech, career guidance, or Nepali education policy, I'd genuinely like to hear what you think.&lt;/p&gt;
&lt;p&gt;Tools: Python (pandas, scikit-learn, matplotlib, seaborn) in Jupyter, Google Forms for data collection.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/24296/building-survey-based-ml-pipeline-to-find-out-whats-really-holding-see-and-graduates-back</guid>
<pubDate>Sat, 08 Aug 2026 12:00:31 +0000</pubDate>
</item>
<item>
<title>Fixed &quot;Indexerror: single positional indexer is out-of-bounds&quot;</title>
<link>https://coderlegion.com/12798/fixed-indexerror-single-positional-indexer-is-out-of-bounds</link>
<description>&lt;p&gt;The &quot;&lt;strong&gt;IndexError: single positional indexer is out-of-bounds&lt;/strong&gt;&quot; is a common error encountered while working with &lt;strong&gt;pandas DataFrames&lt;/strong&gt; in Python. It occurs when attempting to access elements using invalid row or column indices. In this article, we will explore the main causes of this error and provide practical solutions to fix it. Let's dive in!&lt;/p&gt;
&lt;h2 id=&quot;what-is-indexerror-single-positional-indexer-is-out-of-bounds-error-&quot;&gt;What is &quot;IndexError: single positional indexer is out-of-bounds&quot; error?&lt;/h2&gt;
&lt;p&gt;This is a specific type of &lt;code&gt;IndexError&lt;/code&gt; that occurs when working with pandas &lt;strong&gt;DataFrames&lt;/strong&gt;. It arises when attempting to access DataFrame elements using invalid integer-based indexers or using non-existent row or column indices. This error indicates that the index being used to access the DataFrame is either out of the valid range or does not exist in the DataFrame.&lt;/p&gt;
&lt;h3 id=&quot;how-is-this-error-different-from-other-indexerror-errors-&quot;&gt;How is this error different from other &lt;em&gt;IndexError&lt;/em&gt; errors?&lt;/h3&gt;
&lt;p&gt;While &quot;IndexError: single positional indexer is out-of-bounds&quot; is a subtype of the generic &lt;code&gt;IndexError&lt;/code&gt;, it has unique characteristics. Unlike other &lt;code&gt;IndexError&lt;/code&gt; errors, which may occur when working with lists, arrays, or sequences, this error is specific to pandas &lt;strong&gt;DataFrames&lt;/strong&gt;. It typically arises when using incorrect indexing methods like &lt;code&gt;iloc&lt;/code&gt; or &lt;code&gt;iat&lt;/code&gt; with non-existent or out-of-bounds indices.&lt;/p&gt;
&lt;h2 id=&quot;what-causes-the-error-in-python-&quot;&gt;What causes the error in Python?&lt;/h2&gt;
&lt;p&gt;This error is specific to DataFrame indexing methods, such as &lt;code&gt;iloc&lt;/code&gt;, &lt;code&gt;iat&lt;/code&gt;, &lt;code&gt;loc&lt;/code&gt; and &lt;code&gt;at&lt;/code&gt;. Let's explore several common scenarios that trigger this error and understand the root causes behind each one.&lt;/p&gt;
&lt;h3 id=&quot;dataframe-indexing-functions-&quot;&gt;DataFrame Indexing Functions:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;iloc&lt;/strong&gt;: Used for integer-based indexing, allowing us to access DataFrame elements using numeric row and column indices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;iat&lt;/strong&gt;: A faster version of iloc for scalar (single element) access, where we can provide numeric row and column indices to retrieve a single cell's value.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;loc&lt;/strong&gt;: Used for label-based indexing, allowing us to access DataFrame elements using row and column labels (index names) instead of numeric indices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;at&lt;/strong&gt;: A faster version of loc for scalar access, where we can provide row and column labels to retrieve a single cell's value.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Also, for every scenario in this article, we will use the small data set below to demonstrate our examples:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14644198102324885615&quot; alt=&quot;data set&quot;&gt;&lt;/p&gt;
&lt;p&gt;Notice that this DataFrame has 3 columns and 4 rows.&lt;/p&gt;
&lt;h3 id=&quot;scenario-1-invalid-row-index&quot;&gt;Scenario 1: Invalid Row Index&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=316213492713905044&quot; alt=&quot;invalid row index&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this scenario, the error occurs when trying to access a row in the DataFrame using an invalid row index. For instance, we attempt to access the 5th row in the data set using &lt;code&gt;iloc&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# The data set is stored in data
data = {'Name': ['John', 'Jane', 'Mike', 'Alice'],
        'Age': [25, 30, 22, 28],
        'City': ['New York', 'San Francisco', 'Chicago', 'Los Angeles']}

df = pd.DataFrame(data)

# Invalid row index access
print(df.iloc[4])  # Attempting to access the 5th row
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This occurs because the DataFrame only has four rows with valid indices 0 to 3, and attempting to access the 5th row (index 4) leads to the &quot;IndexError&quot;.&lt;/p&gt;
&lt;div class=&quot;div-purple&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Python indexes are zero-based, so the index of the first column is 0 and the index of the last column is -1. And it's totally fine to use negative indexes for accessing the data, as long as they are integers.&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;scenario-2-invalid-column-index&quot;&gt;Scenario 2: Invalid Column Index&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1447269002227969968&quot; alt=&quot;invalid column index&quot;&gt;&lt;/p&gt;
&lt;p&gt;The same error arises when trying to access a column in the DataFrame using an invalid column index. This time we attempt to access the 4th column (index 3) in a DataFrame with three columns:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

data = {'Name': ['John', 'Jane', 'Mike', 'Alice'],
        'Age': [25, 30, 22, 28],
        'City': ['New York', 'San Francisco', 'Chicago', 'Los Angeles']}

df = pd.DataFrame(data)

# Invalid column index access
print(df.iloc[:, 3])  # Attempting to access the 4th column
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, this occurs because the DataFrame has only three columns with valid indices 0 to 2, and we are attempting to access the 4th column (index 3).&lt;/p&gt;
&lt;h2 id=&quot;how-to-fix-this-problem-&quot;&gt;How to fix this problem?&lt;/h2&gt;
&lt;p&gt;Knowing the causes of the error is the first step to solving it. After that, you can follow these steps to resolve the issue:&lt;/p&gt;
&lt;h3 id=&quot;step-1-verify-dataframe-s-number-of-rows-and-columns&quot;&gt;Step 1: Verify DataFrame's Number of Rows and Columns&lt;/h3&gt;
&lt;p&gt;Before accessing elements using &lt;code&gt;iloc&lt;/code&gt;, ensure you know the number of rows in your DataFrame. You can use the &lt;strong&gt;shape&lt;/strong&gt; attribute to obtain the dimensions of the DataFrame.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Get the number of rows and columns in DataFrame
num_rows = df.shape[0]
num_columns = df.shape[1]
print(&quot;Number of rows: &quot;, num_rows, &quot;\nNumber of columns: &quot;, num_columns)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;step-2-ensure-the-index-is-within-bounds&quot;&gt;Step 2: Ensure the Index is Within Bounds&lt;/h3&gt;
&lt;p&gt;You should make sure to verify that the index falls within the valid range (&lt;code&gt;0&lt;/code&gt; to &lt;code&gt;num - 1&lt;/code&gt;). Use conditional statements to check the index before accessing the row or column.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;num_rows = df.shape[0]
row_index = 4  # The row index to access

if row_index &amp;gt;= 0 and row_index &amp;lt; num_rows:
    print(df.iloc[row_index])
else:
    print(&quot;Invalid row index. Index should be between 0 and&quot;, num_rows - 1)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;step-3-avoid-hardcoding-indices&quot;&gt;Step 3: Avoid Hardcoding Indices&lt;/h3&gt;
&lt;p&gt;Instead of hardcoding row indices, use loop constructs or iterators to iterate over the DataFrame rows. This prevents the need to access specific rows by index.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Loop all rows
for index, row in df.iterrows():
    print(&quot;Row&quot;, index, &quot;:&quot;, row)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;step-4-handle-potential-exceptions&quot;&gt;Step 4: Handle Potential Exceptions&lt;/h3&gt;
&lt;p&gt;To avoid the &quot;IndexError&quot; altogether, consider using exception handling when working with user-provided or uncertain data. Use try-except blocks to catch and handle potential exceptions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;try:
    print(df.iloc[5]) # Attempting to access the 6th row
except IndexError:
    print(&quot;Invalid row index. Please ensure the index is within the valid range.&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;some-tips-to-avoid-this-error&quot;&gt;Some tips to avoid this error&lt;/h2&gt;
&lt;h3 id=&quot;use-csv-reading-with-error-handling&quot;&gt;Use CSV Reading with Error Handling&lt;/h3&gt;
&lt;p&gt;When reading data from CSV files, use Python's built-in file handling and error handling mechanisms to check if the file is empty or does not exist before attempting to create a DataFrame.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

file_path = 'data.csv'
try:
    with open(file_path) as f:
        first_line = f.readline()
        if not first_line:
            print(&quot;File is empty!&quot;)
        else:
            df = pd.read_csv(file_path)
except FileNotFoundError:
    print(&quot;File not found!&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;consider-alternatives-to-dataframes&quot;&gt;Consider alternatives to DataFrames&lt;/h3&gt;
&lt;p&gt;While pandas DataFrames are a powerful tool for data manipulation and analysis, there are instances where you might prefer alternatives to avoid potential errors like &quot;IndexError: single positional indexer is out-of-bounds.&quot;&lt;/p&gt;
&lt;h4 id=&quot;use-dictionaries-or-namedtuples&quot;&gt;Use Dictionaries or NamedTuples&lt;/h4&gt;
&lt;p&gt;If you need labeled data and a DataFrame is not necessary, consider using dictionaries or &lt;code&gt;collections.namedtuple&lt;/code&gt;. These data structures can provide similar functionality without the overhead of a DataFrame.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Use dictionaries
data = [{'Name': 'John', 'Age': 25, 'City': 'New York'},
        {'Name': 'Jane', 'Age': 30, 'City': 'San Francisco'},
        {'Name': 'Mike', 'Age': 22, 'City': 'Chicago'},
        {'Name': 'Alice', 'Age': 28, 'City': 'Los Angeles'}]
        
# Use NamedTuples
from collections import namedtuple

Person = namedtuple('Person', ['Name', 'Age', 'City'])
data = [Person('John', 25, 'New York'),
        Person('Jane', 30, 'San Francisco'),
        Person('Mike', 22, 'Chicago'),
        Person('Alice', 28, 'Los Angeles')]
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;for-simple-lists&quot;&gt;For Simple Lists&lt;/h4&gt;
&lt;p&gt;For simple operations on lists or arrays, use native Python lists or &lt;strong&gt;NumPy&lt;/strong&gt; arrays. DataFrame overhead might not be necessary, and it reduces the risk of DataFrame-related errors.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Use native Python lists
data = [1, 2, 3, 4, 5]
mean_value = sum(data) / len(data)

# Or NumPy arrays
import numpy as np

data = np.array([1, 2, 3, 4, 5])
mean_value = np.mean(data)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &quot;&lt;strong&gt;IndexError: single positional indexer is out-of-bounds&lt;/strong&gt;&quot; error is a specific type of &lt;em&gt;IndexError&lt;/em&gt; that occurs when accessing elements in &lt;strong&gt;pandas DataFrames&lt;/strong&gt; using invalid indices. This error can arise due to various scenarios, such as invalid row or column indices with &lt;code&gt;iloc&lt;/code&gt;, &lt;code&gt;iat&lt;/code&gt;, &lt;code&gt;loc&lt;/code&gt;, and &lt;code&gt;at&lt;/code&gt;. By understanding these scenarios and the functions' behavior, we can effectively troubleshoot and resolve the errors. To avoid encountering this error, it is essential to verify DataFrame dimensions, use valid indices and labels, and handle potential exceptions gracefully. Additionally, employing loop constructs for safer row access and being cautious when reading data from CSV files can prevent DataFrame-related issues. Implementing these best practices ensures smoother data manipulation and analysis with pandas, enhancing the overall reliability and efficiency of our Python programs.&lt;/p&gt;
&lt;p&gt;That's it for today. Have fun coding!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12798/fixed-indexerror-single-positional-indexer-is-out-of-bounds</guid>
<pubDate>Wed, 11 Mar 2026 21:25:33 +0000</pubDate>
</item>
<item>
<title>Which method can be used to add a group of elements to a set?</title>
<link>https://coderlegion.com/9693/which-method-can-be-used-to-add-a-group-of-elements-to-a-set</link>
<description>&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Adding a group of elements to a set in &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.python.org/doc/&quot;&gt;Python&lt;/a&gt; is a common task encountered in programming when dealing with collections of unique elements. This problem arises when there's a need to incorporate multiple items into an existing set efficiently. Sets in Python ensure uniqueness, meaning duplicate elements are automatically filtered out. However, adding a group of elements to a set requires special attention to maintain this uniqueness while achieving the desired functionality. Fortunately, Python offers various methods to address this challenge, providing flexibility and efficiency in managing sets. By understanding these methods, programmers can effectively manipulate sets to accommodate new elements while preserving their distinctiveness.&lt;/p&gt;
&lt;h3 id=&quot;what-is-a-set-&quot;&gt;What is a Set?&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;In Python, sets are a fundamental data structure used for &lt;strong&gt;storing collections of unique elements&lt;/strong&gt;. Unlike lists or tuples, sets do not allow duplicate values, ensuring that each element within the set is unique. Sets are unordered, meaning that the elements are not stored in any particular order, and they are mutable, allowing for dynamic changes to the set's contents.&lt;/li&gt;
&lt;li&gt;Sets in Python are like containers that holds a collection of unique items.&lt;/li&gt;
&lt;li&gt;Imagine you have an empty bag where you can only keep unique items; that's essentially what a set is.&lt;/li&gt;
&lt;li&gt;Each item in a set is distinct, and the order doesn't matter. If you try to put a duplicate item, it simply won't go in.&lt;/li&gt;
&lt;li&gt;Sets in Python are denoted by curly braces &lt;code&gt;{}&lt;/code&gt; enclosing a comma-separated list of elements, or by using the &lt;code&gt;set()&lt;/code&gt; constructor. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's look at a small example to understand what a set is,&lt;/p&gt;
&lt;h3 id=&quot;example&quot;&gt;EXAMPLE&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  # Unique Elements
     fruits_1 = {'mango', 'apple', 'orange', 'kiwi'}
     print(&quot;Set of Fruits-1 : &quot;, fruits_1)

     # Even if I repeat elements, it will consider that element to be unique only
     fruits_2 = {'mango', 'apple', 'orange', 'kiwi','orange'}
     print(&quot;Set of Fruits-2: &quot;, fruits_2)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1266818688928413254&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;adding-a-group-of-elements-to-a-set&quot;&gt;Adding a group of elements to a set&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Using &lt;code&gt;update()&lt;/code&gt; method&lt;/li&gt;
&lt;li&gt;Using &lt;code&gt;|&lt;/code&gt; Operator&lt;/li&gt;
&lt;li&gt;Using Set Union Method - &lt;code&gt;union()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Using Set Comprehension&lt;/li&gt;
&lt;li&gt;Using Set Constructor&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These methods offer flexibility in adding a single element or a group of elements to a set in Python-3.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt; &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Define a set
my_set = {1, 2, 3}

# Define a list of elements to add
to_add_elements = [4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;method---1&quot;&gt;Method - 1&lt;/h2&gt;
&lt;h3 id=&quot;using-update-method&quot;&gt;Using &lt;code&gt;'update()'&lt;/code&gt; method&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;This method directly adds multiple elements to a set in Python-3.&lt;/li&gt;
&lt;li&gt;It takes an iterable (such as a list, tuple, or set) as input and modifies the set by adding all elements from the iterable.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set.update(elements_to_add)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 1: Using update() method
my_set.update(to_add_elements)
print(&quot;my_set&quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Use `update()` method when you want to directly add multiple elements to a set.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;method---2&quot;&gt;Method - 2&lt;/h2&gt;
&lt;h3 id=&quot;using-operator&quot;&gt;Using &lt;code&gt;'|'&lt;/code&gt; Operator&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The set union operator (|) performs a union operation between two sets, adding elements from both sets to create a new set.&lt;/li&gt;
&lt;li&gt;It combines the existing set with another set created from an iterable using the set() constructor.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set |= set(elements_to_add)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 2: Using '|' operator
my_set |= set(to_add_elements)
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;method---3&quot;&gt;Method - 3&lt;/h2&gt;
&lt;h3 id=&quot;using-set-union-method---union-&quot;&gt;Using Set Union Method - &lt;code&gt;'union()'&lt;/code&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The union() method returns a new set containing all the elements from the existing set and an iterable.&lt;/li&gt;
&lt;li&gt;It doesn't modify the original set but creates a new set with the&lt;br&gt;
 combined elements.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set = my_set.union(elements_to_add)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 3: Using union() method
my_set = my_set.union(to_add_elements)
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;method---4&quot;&gt;Method - 4&lt;/h2&gt;
&lt;h3 id=&quot;using-set-comprehension&quot;&gt;Using Set Comprehension&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Set comprehension is a concise way to create sets in Python by iterating over an iterable.&lt;/li&gt;
&lt;li&gt;It allows for adding elements from the iterable to the set while creating it.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set = {element for element in my_set} | set(elements_to_add)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 4: Using set comprehension
my_set = {element for element in my_set} | set(to_add_elements)
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Employ set comprehension for a concise way to create sets by iterating over an iterable.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;method---5&quot;&gt;Method - 5&lt;/h2&gt;
&lt;h3 id=&quot;using-set-constructor&quot;&gt;Using Set Constructor&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The set() constructor creates a new set from an iterable, automatically removing any duplicate elements.&lt;/li&gt;
&lt;li&gt;It can be combined with set operations like union to add elements from the iterable to the existing set.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set = my_set.union(set(elements_to_add))&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 5: Using set constructor
my_set = my_set.union(set(to_add_elements))
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;all-the-5-methods-in-one-go-&quot;&gt;All the 5 Methods in One Go!&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# Define a set
my_set = {1, 2, 3}

# Define a list of elements to add
elements_to_add = [4, 5, 6]

# Method 1: Using update() method
my_set.update(elements_to_add)

# Method 2: Using set union (| operator)
my_set |= set(elements_to_add)

# Method 3: Using union() method
my_set = my_set.union(elements_to_add)

# Method 4: Using set comprehension
my_set = {element for element in my_set} | set(elements_to_add)

# Method 5: Using set constructor
my_set = my_set.union(set(elements_to_add))
&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Pay attention to the performance implications of each method, especially when dealing with large sets.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;best-practices&quot;&gt;Best Practices&lt;/h2&gt;
&lt;p&gt;Here are some best practices to follow when adding elements to a set:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Choose the most appropriate method:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;Depending on your specific use case and preference, choose the method that best suits your needs. Each method has its advantages, but some might be more efficient or readable depending on the context.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Use update() for simplicity:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;When you want to add multiple elements to an existing set and modify it in place, update() is the simplest and most straightforward method. It directly modifies the original set without creating a new one.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Document your code:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;Clearly document your code, especially if you're using less common methods or if the purpose of the code might not be immediately obvious. Documenting your code helps other developers understand your intentions and use your code effectively.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Test thoroughly:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;Test your code with various inputs and edge cases to ensure it behaves as expected. Consider writing unit tests to automate testing and catch regressions.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Ensure that the elements you're adding to the set are unique to maintain set's uniqueness property.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Be cautious when using set comprehension with large iterables, as it may lead to increased memory usage.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Sets in Python are collections of unique elements, akin to a bag where each item is distinct.&lt;/li&gt;
&lt;li&gt;They are useful for tasks requiring uniqueness, like removing duplicates or finding unique elements.&lt;/li&gt;
&lt;li&gt;Various methods exist to add a group of elements to a set, including update(), set union (| operator), union() method, set comprehension, and set constructor.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;conclusion-1&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In simpler terms, when working with sets in Python, you have different methods for adding multiple items. You can choose the one that suits your needs best:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If you want a straightforward approach, you can use update().&lt;/li&gt;
&lt;li&gt;For a more elegant solution, you can use | (the pipe symbol).&lt;/li&gt;
&lt;li&gt;If you need more flexibility, union() is a good option.&lt;/li&gt;
&lt;li&gt;If you prefer concise code, you can use set comprehension.&lt;/li&gt;
&lt;li&gt;And if you need to build a set from other iterable types, you can use the set constructor.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these methods helps you manage sets effectively, ensuring that each item you add remains unique.&lt;/p&gt;
&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Python documentation:&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.python.org/doc/&quot;&gt;https://www.python.org/doc/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9693/which-method-can-be-used-to-add-a-group-of-elements-to-a-set</guid>
<pubDate>Wed, 14 Jan 2026 11:54:37 +0000</pubDate>
</item>
<item>
<title>Building an Intelligent Contract Assistant with OpenAI Agents SDK</title>
<link>https://coderlegion.com/3311/building-an-intelligent-contract-assistant-with-openai-agents-sdk</link>
<description>&lt;h2 id=&quot;building-an-intelligent-contract-assistant-with-openai-agents-sdk&quot;&gt;Building an Intelligent Contract Assistant with OpenAI Agents SDK&lt;/h2&gt;
&lt;p&gt;In this article, we explore how we leveraged the OpenAI Agents SDK to create a sophisticated contract management system that combines multiple AI agents working in harmony. Let's dive into the key architectural decisions and technical implementations that make this system powerful and efficient.&lt;/p&gt;
&lt;h3 id=&quot;-multi-agent-architecture&quot;&gt;️ Multi-Agent Architecture&lt;/h3&gt;
&lt;p&gt;At the heart of our system lies a multi-agent collaboration pattern, orchestrated by a supervisor agent that intelligently routes requests to specialized sub-agents. This architecture enables us to handle complex contract-related tasks with precision and efficiency.&lt;/p&gt;
&lt;h4 id=&quot;the-supervisor-agent&quot;&gt;The Supervisor Agent&lt;/h4&gt;
&lt;p&gt;The supervisor agent serves as the frontline interface, managing the conversation flow and making intelligent routing decisions. It's equipped with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Advanced intent classification capabilities&lt;/li&gt;
&lt;li&gt;Knowledge of contract templates and guidelines&lt;/li&gt;
&lt;li&gt;Ability to handle general queries directly&lt;/li&gt;
&lt;li&gt;Smart routing to specialized sub-agents using the handoff mechanism&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;specialized-sub-agents&quot;&gt;Specialized Sub-Agents&lt;/h4&gt;
&lt;h5 id=&quot;1-contract-drafting-agent&quot;&gt;1.  Contract Drafting Agent&lt;/h5&gt;
&lt;p&gt;This agent demonstrates the power of combining LLMs with structured workflows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;️ Uses function tools to implement a three-step process:&lt;ol&gt;
&lt;li&gt;Contract type determination&lt;/li&gt;
&lt;li&gt;Dynamic question generation based on contract type&lt;/li&gt;
&lt;li&gt;Contract generation using GPT-4&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Supports three contract types:&lt;ul&gt;
&lt;li&gt;Purchase Agreements&lt;/li&gt;
&lt;li&gt;Franchise Agreements&lt;/li&gt;
&lt;li&gt;Time and Materials Contracts&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Leverages template files for consistent structure&lt;/li&gt;
&lt;/ul&gt;
&lt;h5 id=&quot;2-existing-contract-agent&quot;&gt;2.  Existing Contract Agent&lt;/h5&gt;
&lt;p&gt;Handles all aspects of contract management:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Contract status retrieval&lt;/li&gt;
&lt;li&gt;Detailed contract information&lt;/li&gt;
&lt;li&gt;❓ Query resolution for existing agreements&lt;/li&gt;
&lt;/ul&gt;
&lt;h5 id=&quot;3-general-contract-assistant&quot;&gt;3.  General Contract Assistant&lt;/h5&gt;
&lt;p&gt;Provides expert guidance on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Contract type selection&lt;/li&gt;
&lt;li&gt;❓ General contract-related queries&lt;/li&gt;
&lt;li&gt;Best practices and guidelines&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;-technical-implementation-highlights&quot;&gt;⚙️ Technical Implementation Highlights&lt;/h3&gt;
&lt;h4 id=&quot;1-handoff-mechanism&quot;&gt;1.  Handoff Mechanism&lt;/h4&gt;
&lt;p&gt;We implemented the Agent Pattern of Routing using the handoff_description feature, enabling seamless transitions between agents while maintaining context.&lt;/p&gt;
&lt;h4 id=&quot;2-function-tools-integration&quot;&gt;2. ️ Function Tools Integration&lt;/h4&gt;
&lt;p&gt;The system extensively uses function tools to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Determine contract types&lt;/li&gt;
&lt;li&gt;❓ Generate relevant questions&lt;/li&gt;
&lt;li&gt;Draft contracts using GPT-4&lt;/li&gt;
&lt;li&gt;Retrieve contract details and status&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;3-streaming-outputs&quot;&gt;3. ⚡ Streaming Outputs&lt;/h4&gt;
&lt;p&gt;Implemented real-time response streaming for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Smooth conversation flow&lt;/li&gt;
&lt;li&gt;⚡ Immediate feedback&lt;/li&gt;
&lt;li&gt;Enhanced user experience&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;usage&quot;&gt;Usage&lt;/h3&gt;
&lt;p&gt;Try out with these sample prompts -&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&quot;I need help with a purchase agreement.&quot;&lt;/li&gt;
&lt;li&gt;&quot;Can you show me the status of contract #12345?&quot;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;key-technologies&quot;&gt;Key Technologies&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;OpenAI Agents SDK for agent management &lt;a rel=&quot;nofollow&quot; href=&quot;https://openai.github.io/openai-agents-python&quot;&gt;OpenAI Agents SDK&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;GPT-4 for contract generation &lt;a rel=&quot;nofollow&quot; href=&quot;https://openai.com/api/pricing/&quot;&gt;GPT-4&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;️ Function tools for structured operations &lt;a rel=&quot;nofollow&quot; href=&quot;https://openai.github.io/openai-agents-python/function_tools/&quot;&gt;Function tools&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;⚡ Streaming for real-time responses &lt;a rel=&quot;nofollow&quot; href=&quot;https://openai.github.io/openai-agents-python/streaming/&quot;&gt;Streaming&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This implementation demonstrates how modern AI technologies can be combined to create sophisticated, practical applications that solve real-world business problems.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/r123singh/openai-agents-workshop/tree/main/Contract-Assistant&quot;&gt; View the implementation on GitHub&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;captured-below-are-the-sample-conversation-screenshots--&quot;&gt;Captured below are the sample conversation screenshots -&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=7848380285633293855&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=4649272812859576260&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</description>
<category>Python</category>
<guid isPermaLink="true">https://coderlegion.com/3311/building-an-intelligent-contract-assistant-with-openai-agents-sdk</guid>
<pubDate>Tue, 10 Jun 2025 13:20:38 +0000</pubDate>
</item>
<item>
<title>A multi-agent HR assistant that handles various HR-related queries and actions using OpenAI- Agents Framework</title>
<link>https://coderlegion.com/3147/multi-agent-assistant-handles-various-related-queries-actions-openai-agents-framework</link>
<description>&lt;h2 id=&quot;building-an-ai-powered-hr-assistant-with-openai-agents-sdk&quot;&gt;Building an AI-Powered HR Assistant with OpenAI Agents SDK&lt;/h2&gt;
&lt;h3 id=&quot;introduction-1&quot;&gt;Introduction&lt;/h3&gt;
&lt;p&gt;In the era of digital transformation, automating HR queries and processes can significantly enhance employee experience and operational efficiency. In this project, I built an intelligent HR Assistant using the &lt;a rel=&quot;nofollow&quot; href=&quot;https://openai.github.io/openai-agents-python/&quot;&gt;OpenAI Agents SDK&lt;/a&gt; that can handle a variety of HR-related queries, triage requests, and even trigger backend actions such as leave requests or complaint registration. The assistant features a conversational UI built with &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.gradio.app/&quot;&gt;Gradio&lt;/a&gt;, making it accessible and user-friendly.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;key-features&quot;&gt;Key Features&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Multi-Agent Architecture:&lt;/strong&gt; Specialized agents handle different HR domains (leaves, benefits, policies, complaints).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Guardrails:&lt;/strong&gt; Input guardrails ensure only HR-related queries are processed, improving safety and relevance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tool Integration:&lt;/strong&gt; Backend functions (tools) are registered with agents, allowing the assistant to perform actions like creating leave requests or registering complaints.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Context Management:&lt;/strong&gt; The assistant maintains conversation history, enabling context-aware, multi-turn conversations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;User Interface:&lt;/strong&gt; A Gradio-based web UI provides a seamless chat experience.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;project-structure-amp-important-aspects&quot;&gt;Project Structure &amp;amp; Important Aspects&lt;/h3&gt;
&lt;h4 id=&quot;1-agent-design&quot;&gt;1. Agent Design&lt;/h4&gt;
&lt;p&gt;Each HR domain is managed by a dedicated agent:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Leaves Agent:&lt;/strong&gt; Handles leave policies and requests.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefits Agent:&lt;/strong&gt; Answers questions about employee benefits.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Policy Agent:&lt;/strong&gt; Provides information on company policies.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Complaints Agent:&lt;/strong&gt; Registers and tracks complaints.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A &lt;strong&gt;Triage Agent&lt;/strong&gt; routes user queries to the appropriate specialist agent.&lt;/p&gt;
&lt;h4 id=&quot;2-guardrails&quot;&gt;2. Guardrails&lt;/h4&gt;
&lt;p&gt;A guardrail agent checks if the user’s query is HR-related before passing it to the triage agent, ensuring the assistant stays on topic.&lt;/p&gt;
&lt;h4 id=&quot;3-tool-functions&quot;&gt;3. Tool Functions&lt;/h4&gt;
&lt;p&gt;Tools are Python functions registered with agents. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;@function_tool
def create_leave_request(employee_id: str, department: str, leave_type: str, start_date: str, end_date: str):
    return f&quot;Leave request created for {employee_id} in {department} from {start_date} to {end_date} for {leave_type}.&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Agents invoke these tools when appropriate, enabling real actions beyond just answering questions.&lt;/p&gt;
&lt;h4 id=&quot;4-context-management&quot;&gt;4. Context Management&lt;/h4&gt;
&lt;p&gt;The assistant maintains a persistent conversation history, which is included in each prompt to ensure context continuity across multiple turns. This is crucial for handling follow-up questions and multi-step workflows.&lt;/p&gt;
&lt;h4 id=&quot;5-gradio-ui&quot;&gt;5. Gradio UI&lt;/h4&gt;
&lt;p&gt;A simple yet effective chat interface was built using Gradio, allowing users to interact with the HR assistant in real time.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;example-queries&quot;&gt;Example Queries&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;“I need to take a leave next week.”&lt;/li&gt;
&lt;li&gt;“What is the company’s life insurance policy?”&lt;/li&gt;
&lt;li&gt;“How many sick leaves do I have left?”&lt;/li&gt;
&lt;li&gt;“I want to register a complaint about my manager.”&lt;/li&gt;
&lt;li&gt;“Tell me about the gym membership benefit.”&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;demo&quot;&gt;Demo&lt;/h3&gt;
&lt;h3 id=&quot;video-demo&quot;&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://youtu.be/nB1-SzeqjzE&quot;&gt;Video Demo&lt;/a&gt;&lt;/h3&gt;
&lt;h3 id=&quot;try-it-yourself&quot;&gt;Try it Yourself&lt;/h3&gt;
&lt;p&gt;The full project is available on GitHub:&lt;br&gt;
&lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/r123singh/openai-agents-workshop/tree/main/HR-Agent&quot;&gt;GitHub Repository&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;demo-queries&quot;&gt;Demo Queries&lt;/h3&gt;
&lt;p&gt;Try these in the chat UI:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;“Can I get parental leave?”&lt;/li&gt;
&lt;li&gt;“How do I register a complaint?”&lt;/li&gt;
&lt;li&gt;“What are the food coupon benefits?”&lt;/li&gt;
&lt;li&gt;“Tell me about the weekend shift policy.”&lt;/li&gt;
&lt;li&gt;“I want to apply for sick leave from tomorrow.”&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;conclusion-2&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;This project demonstrates how the OpenAI Agents SDK can be leveraged to build robust, context-aware, and action-oriented assistants for enterprise use cases. With modular agents, tool integration, and a user-friendly UI, the HR Assistant is a step towards smarter, more efficient HR operations.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;For more details and to contribute, visit the &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/r123singh/openai-agents-workshop/tree/main/HR-Agent&quot;&gt;GitHub repository&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;hr&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/3147/multi-agent-assistant-handles-various-related-queries-actions-openai-agents-framework</guid>
<pubDate>Sat, 24 May 2025 11:37:31 +0000</pubDate>
</item>
<item>
<title>&quot;Dive Deep, Code Smart—Master the Waves of DSA!&quot;</title>
<link>https://coderlegion.com/836/dive-deep-code-smart-master-the-waves-of-dsa</link>
<description>&lt;h2 id=&quot;diving-into-the-pool-of-data-structures-and-algorithms-a-swimmer-s-guide-to-problem-solving&quot;&gt;Diving into the Pool of Data Structures and Algorithms: A Swimmer’s Guide to Problem-Solving&lt;/h2&gt;
&lt;hr&gt;
&lt;p&gt;Welcome to the world of Data Structures and Algorithms (DSA), where every concept is like a swimming technique and every challenge is an opportunity to swim deeper. In this guide, we will explore the basic and advanced elements of DSA, helping you navigate this vast ocean of knowledge. Just like swimming, mastering DSA takes practice, patience, and the right approach.&lt;/p&gt;
&lt;h3 id=&quot;the-shallow-end-foundations-of-data-structures&quot;&gt;&lt;strong&gt;The Shallow End: Foundations of Data Structures&lt;/strong&gt;&lt;/h3&gt;
&lt;h4 id=&quot;arrays-the-swimming-lanes&quot;&gt;&lt;strong&gt;Arrays: The Swimming Lanes&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Arrays act like swimming lanes that offer direct access to any point. Each element has a defined index, allowing you to precisely navigate your data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cpp
int arr[5] = {10, 20, 30, 40, 50}; // Initializing an array
cout &amp;lt;&amp;lt; arr[2]; // Accessing third element (Output: 30)
```
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;linked-lists-the-relay-race&quot;&gt;&lt;strong&gt;Linked Lists: The Relay Race&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Linked Lists are like a relay race where each node points to the next, ensuring continuous movement of data. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cpp
struct Node {
    int data;
    Node* next;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;stacks-the-diving-board-lifo-&quot;&gt;&lt;strong&gt;Stacks: The Diving Board (LIFO)&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Stacks are like diving boards, where the Last In, First Out (LIFO) principle governs the order of operations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
stack = []
stack.append(10) # Push an element
stack.append(20)
print(stack.pop()) # Pop the last inserted element (Output: 20)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;queues-the-diving-platform-line-fifo-&quot;&gt;&lt;strong&gt;Queues: The Diving Platform Line (FIFO)&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Queues operate like a line at a diving platform, where the First In, First Out (FIFO) order dictates the flow of data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
from collections import deque
queue = deque([1, 2, 3])
queue.append(4) # Enqueue
print(queue.popleft()) # Dequeue (Output: 1)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-deep-end-advanced-data-structures&quot;&gt;&lt;strong&gt;The Deep End: Advanced Data Structures&lt;/strong&gt;&lt;/h3&gt;
&lt;h4 id=&quot;trees-the-towering-platforms&quot;&gt;&lt;strong&gt;Trees: The Towering Platforms&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Binary Search Trees (BST) guide you through organized data, ensuring efficient depth searches.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
class Node:
    def __init__(self, key):
        self.left = self.right = None
        self.key = key
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;graphs-the-interconnected-pools&quot;&gt;&lt;strong&gt;Graphs: The Interconnected Pools&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Graphs are like interconnected pools where each node can follow multiple paths.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;heaps-the-underwater-safety-zones&quot;&gt;&lt;strong&gt;Heaps: The Underwater Safety Zones&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Heaps allow for optimal retrieval of the highest or lowest value, much like safety zones at varying depths.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
import heapq
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 5)
print(heapq.heappop(heap)) # Output: 5 (Min-Heap)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;hash-tables-the-underwater-lockers&quot;&gt;&lt;strong&gt;Hash Tables: The Underwater Lockers&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Hash Tables are like underwater lockers that provide instant access to data through keys.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
hash_table = {}
hash_table['name'] = 'Alice'
print(hash_table['name']) # Output: Alice
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;mastering-the-strokes-algorithms&quot;&gt;&lt;strong&gt;Mastering the Strokes: Algorithms&lt;/strong&gt;&lt;/h3&gt;
&lt;h4 id=&quot;sorting-algorithms&quot;&gt;&lt;strong&gt;Sorting Algorithms&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Bubble Sort&lt;/strong&gt;: Slow paddling.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Merge Sort&lt;/strong&gt;: Graceful strokes.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Quick Sort&lt;/strong&gt;: Swift dives.&lt;/p&gt;
&lt;p&gt;  python&lt;br&gt;
  def quick_sort(arr):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  if len(arr) &amp;lt;= 1:
      return arr
  pivot = arr[len(arr) // 2]
  left = [x for x in arr if x &amp;lt; pivot]
  right = [x for x in arr if x &amp;gt; pivot]
  return quick_sort(left) + [pivot] + quick_sort(right)
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;searching-algorithms&quot;&gt;&lt;strong&gt;Searching Algorithms&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Linear Search&lt;/strong&gt;: Exhaustive exploration.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Binary Search&lt;/strong&gt;: Precise diving.&lt;/p&gt;
&lt;p&gt;  python&lt;br&gt;
  def binary_search(arr, target):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  low, high = 0, len(arr) - 1
  while low &amp;lt;= high:
      mid = (low + high) // 2
      if arr[mid] == target:
          return mid
      elif arr[mid] &amp;lt; target:
          low = mid + 1
      else:
          high = mid - 1
  return -1
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;dynamic-programming-dp-&quot;&gt;&lt;strong&gt;Dynamic Programming (DP)&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Dynamic Programming is akin to endurance swimming—breaking problems into subproblems and storing results.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
def fibonacci(n, memo={}):
    if n in memo:
        return memo[n]
    if n &amp;lt;= 1:
        return n
    memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, memo)
    return memo[n]
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;greedy-algorithms&quot;&gt;&lt;strong&gt;Greedy Algorithms&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Greedy Algorithms are like swimmers choosing the shortest path to their goal.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python
def coin_change(coins, amount):
    coins.sort(reverse=True)
    count = 0
    for coin in coins:
        while amount &amp;gt;= coin:
            amount -= coin
            count += 1
    return count if amount == 0 else -1
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;overcoming-the-tides-complexity-analysis&quot;&gt;&lt;strong&gt;Overcoming the Tides: Complexity Analysis&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Understanding time and space complexity is crucial for smooth sailing in DSA:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;O(1)&lt;/strong&gt;: Best-case efficiency (e.g., hash table lookups).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(log n)&lt;/strong&gt;: Efficient algorithms (e.g., binary search).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(n)&lt;/strong&gt;: Linear time (e.g., traversing an array).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(n log n)&lt;/strong&gt;: Sorting algorithms (e.g., quicksort, mergesort).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;O(n²)&lt;/strong&gt; or more: Inefficient approaches (e.g., bubble sort).&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-ultimate-dive-real-world-applications&quot;&gt;&lt;strong&gt;The Ultimate Dive: Real-World Applications&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;DSA powers many real-world applications:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Google’s Search Algorithms&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Uber’s Shortest Route Calculations&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Social Media Friend Suggestions&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Database Indexing&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;conclusion-the-endless-ocean&quot;&gt;&lt;strong&gt;Conclusion: The Endless Ocean&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Mastering DSA is like swimming through an ocean of opportunities. The more you practice, the deeper you dive into problem-solving and the better you become at navigating complex challenges. Whether you’re a beginner or an expert, DSA offers endless possibilities for growth. Dive in, explore, and become a master of the tides of problem-solving!&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;strong&gt;References:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/&quot;&gt;GeeksforGeeks - Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.w3schools.com/dsa/dsa_intro.php&quot;&gt;W3 Schools - Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.programiz.com/dsa&quot;&gt;Programiz - DSA&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Python3</category>
<guid isPermaLink="true">https://coderlegion.com/836/dive-deep-code-smart-master-the-waves-of-dsa</guid>
<pubDate>Thu, 16 Jan 2025 17:07:17 +0000</pubDate>
</item>
<item>
<title>Django TemplateDoesNotExist Solved</title>
<link>https://coderlegion.com/311/django-templatedoesnotexist-solved</link>
<description>&lt;p&gt;While working in Django, you might encounter the &lt;strong&gt;&quot;TemplateDoesNotExist&quot;&lt;/strong&gt; error. This issue typically arises due to &lt;strong&gt;incorrect configuration&lt;/strong&gt; of &lt;strong&gt;template&lt;/strong&gt; &lt;strong&gt;settings&lt;/strong&gt; or &lt;strong&gt;paths&lt;/strong&gt;. Fortunately, you can easily solve this error by properly configuring your settings.py file to include the correct template directories. In this article, I will guide you through the steps to set up your template directories correctly, how to debug potential issues, and ensure your templates are correctly recognized by Django a &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/189/history-and-features-of-python?show=189#q189&quot;&gt;Python&lt;/a&gt; framework, all presented straightforwardly and practically.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14579476459226401271&quot; alt=&quot;TemplateDoesNotExist&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;configuring-django-template-settings&quot;&gt;&lt;strong&gt;Configuring Django Template Settings&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;The settings file of Django (&lt;code&gt;settings.py&lt;/code&gt;) determines where the framework should look for templates. In this sense, it is the first step towards the successful resolution of all errors related to templates, since making sure that it is correctly set up is the first step. &lt;/p&gt;
&lt;h3 id=&quot;template-directories&quot;&gt;&lt;strong&gt;Template Directories&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Ensure your &lt;code&gt;TEMPLATES&lt;/code&gt; configuration in &lt;code&gt;settings.py&lt;/code&gt; includes the correct path to your templates. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
    },
]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;: Inside the &lt;code&gt;TEMPLATES&lt;/code&gt; setting, the value of the &lt;code&gt;DIRS&lt;/code&gt; option should be the absolute path to the directory of your templates. &lt;code&gt;BASE_DIR&lt;/code&gt; is a variable that holds the path to your project directory combined with &lt;code&gt;'templates'&lt;/code&gt; to point Django to the correct location.&lt;/p&gt;
&lt;h2 id=&quot;common-scenarios-and-solutions&quot;&gt;&lt;strong&gt;Common Scenarios and Solutions&lt;/strong&gt;&lt;/h2&gt;
&lt;h3 id=&quot;scenario-1-template-misplacement&quot;&gt;&lt;strong&gt;Scenario 1: Template Misplacement&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Your &lt;strong&gt;template&lt;/strong&gt; is not in a &lt;strong&gt;directory&lt;/strong&gt; recognized by Django.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Move your &lt;strong&gt;template&lt;/strong&gt; into one of the directories identified by the &lt;code&gt;DIRS&lt;/code&gt; option in the &lt;code&gt;TEMPLATES&lt;/code&gt; setting, or make sure the directory of your template appears in the appropriate application's &lt;code&gt;templates&lt;/code&gt; directory if &lt;code&gt;APP_DIRS&lt;/code&gt; is set to &lt;code&gt;True&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;scenario-2-typographical-errors-in-template-name&quot;&gt;&lt;strong&gt;Scenario 2: Typographical Errors in Template Name&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: There is a &lt;strong&gt;typo&lt;/strong&gt; in the template name used in your view.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Verify the template name in your view matches exactly with the filename in your templates directory, including &lt;strong&gt;case sensitivity&lt;/strong&gt;.&lt;/p&gt;
&lt;h3 id=&quot;scenario-3-incorrect-app-structure&quot;&gt;&lt;strong&gt;Scenario 3: Incorrect App Structure&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Django cannot find the template because the &lt;strong&gt;app structure&lt;/strong&gt; does not conform to Django's expectations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Ensure each app in your project contains a &lt;strong&gt;templates directory&lt;/strong&gt;. Django looks for templates inside the templates directory of each installed app if APP_DIRS is True.&lt;/p&gt;
&lt;h2 id=&quot;demonstrating-a-solution&quot;&gt;&lt;strong&gt;Demonstrating a Solution&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;Create a Django project and start an app with the command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python manage.py startapp app
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Create a &lt;strong&gt;templates&lt;/strong&gt; folder in the app folder and inside that create a &lt;strong&gt;my_template.html&lt;/strong&gt;. Your folder structure should look something like the following.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=10929676237945187277&quot; alt=&quot;FolderStructure&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;urls-py&quot;&gt;urls.py&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;from django.contrib import admin
from django.shortcuts import render
from django.urls import path

def sample_view(request):
    return render(request, &quot;this_template_does_not_exist.html&quot;)

def my_view(request):
    return render(request, &quot;app/my_template.html&quot;)

urlpatterns = [
    path(&quot;admin/&quot;, admin.site.urls),
    path(&quot;test/&quot;, sample_view, name=&quot;test&quot;),
    path(&quot;view/&quot;, my_view, name=&quot;view&quot;),
] 
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;my-template-html&quot;&gt;my_template.html&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
    &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;
    &amp;lt;title&amp;gt;Template&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    This template exists
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;   &lt;/p&gt;
&lt;p&gt;Now start the server with &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python manage.py runserver
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now when you go to &lt;code&gt;http://localhost:8000/view&lt;/code&gt; you should be able to see the following output as the file exists and there are no typos involved. &lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2700304601089646162&quot; alt=&quot;Correct&quot;&gt;&lt;/p&gt;
&lt;p&gt;But when you go to &lt;code&gt;http://localhost:8000/test&lt;/code&gt; you should be able to see the following output as the file does not exist.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14147655186650961319&quot; alt=&quot;Wrong&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-red&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;Confirm that `my_template.html` is placed in `/templates/` and that your `settings.py` correctly points to this directory as described earlier.
&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;best-practices-to-avoid-the-templatedoesnotexist-issue&quot;&gt;&lt;strong&gt;Best Practices to Avoid the &quot;TemplateDoesNotExist&quot; Issue&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;TemplateDoesNotExist&lt;/code&gt; error is a common issue in Django that can halt your development process. However, it's also one of the easiest to prevent with the right practices. You can refer various &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/257/python-debugging-techniques?show=257#q257&quot;&gt;Debugging Techniques&lt;/a&gt; in Python to know more about the type of error. Here are some tips to ensure you never run into this error again:&lt;/p&gt;
&lt;h3 id=&quot;1-verify-your-templates-configuration&quot;&gt;&lt;strong&gt;1. Verify Your TEMPLATES Configuration&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;The most common cause of this error is a &lt;strong&gt;misconfiguration&lt;/strong&gt; in the &lt;strong&gt;TEMPLATES&lt;/strong&gt; setting in your &lt;strong&gt;settings.py&lt;/strong&gt; file. Double-check that you have correctly defined the &lt;code&gt;DIRS&lt;/code&gt; list to include the paths to your templates. Use the &lt;code&gt;os.path.join(BASE_DIR, 'templates')&lt;/code&gt; pattern to ensure that your paths are correctly constructed and platform-independent.&lt;/p&gt;
&lt;h3 id=&quot;2-adhere-to-django-s-project-structure&quot;&gt;&lt;strong&gt;2. Adhere to Django's Project Structure&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Django expects your project to follow a certain structure, with a specific place for &lt;strong&gt;templates&lt;/strong&gt;. By default, Django looks for a templates directory in each app folder if &lt;strong&gt;APP_DIRS&lt;/strong&gt; is set to &lt;strong&gt;True&lt;/strong&gt; in your &lt;strong&gt;TEMPLATES&lt;/strong&gt; configuration. Ensure you place your templates in the correct directories within your apps or in the global &lt;strong&gt;templates&lt;/strong&gt; directory you specify in &lt;strong&gt;DIRS&lt;/strong&gt;. You can also use a &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/250/setting-up-virtual-environment-in-python?show=250#q250&quot;&gt;Virtual Environment&lt;/a&gt; to isolate the project.&lt;/p&gt;
&lt;h3 id=&quot;3-use-correct-template-naming-and-referencing&quot;&gt;&lt;strong&gt;3. Use Correct Template Naming and Referencing&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Always verify that the template names and paths you use in your views match exactly with your template files, including &lt;strong&gt;case sensitivity&lt;/strong&gt;, which can be an issue on some file systems. A common mistake is a &lt;strong&gt;simple typo&lt;/strong&gt; in the template path or name, leading Django to report that it cannot find the template.&lt;/p&gt;
&lt;h3 id=&quot;4-understand-template-loading-mechanism&quot;&gt;&lt;strong&gt;4. Understand Template Loading Mechanism&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Familiarize yourself with how Django loads templates, especially when using multiple apps. Django will search through the apps listed in &lt;strong&gt;INSTALLED_APPS&lt;/strong&gt; in the order they appear, looking for &lt;strong&gt;templates&lt;/strong&gt; in each app's templates directory. Knowing this order can help you troubleshoot and understand which template is being loaded when you have templates with the same name in different apps.&lt;/p&gt;
&lt;h3 id=&quot;5-regularly-check-for-deprecated-or-moved-templates&quot;&gt;&lt;strong&gt;5. Regularly Check for Deprecated or Moved Templates&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;When upgrading Django or third-party apps, templates might be &lt;strong&gt;deprecated&lt;/strong&gt; or &lt;strong&gt;moved&lt;/strong&gt;. Always check the release notes for any changes to template paths or names to ensure your project stays up-to-date and error-free.&lt;/p&gt;
&lt;h3 id=&quot;6-utilize-django-s-template-debugging-tools&quot;&gt;&lt;strong&gt;6. Utilize Django's Template Debugging Tools&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Make use of Django's built-in template debugging tools, such as setting &lt;strong&gt;DEBUG&lt;/strong&gt; to &lt;strong&gt;True&lt;/strong&gt; in your development settings to get detailed error pages that show you exactly where Django looked for your templates and where it failed to find them. This can be invaluable for quickly diagnosing and fixing path issues.&lt;/p&gt;
&lt;h3 id=&quot;7-consistent-use-of-template-extensions&quot;&gt;&lt;strong&gt;7. Consistent Use of Template Extensions&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Be consistent in your use of template file extensions. Django does not enforce a specific extension for templates &lt;strong&gt;(.html&lt;/strong&gt; is common but not required), but using different extensions inconsistently can lead to confusion and errors.&lt;/p&gt;
&lt;h3 id=&quot;8-automate-template-checks&quot;&gt;&lt;strong&gt;8. Automate Template Checks&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Consider incorporating checks into your deployment pipeline that verify the existence of templates referenced in your views. This can be as simple as a script that scans your views for &lt;strong&gt;render&lt;/strong&gt; calls and checks that the referenced templates exist in your project's template directories.&lt;/p&gt;
&lt;h2 id=&quot;conclusion-3&quot;&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;&quot;TemplateDoesNotExist&quot;&lt;/strong&gt; error in Django can be a stumbling block for developers. However, with a systematic approach to troubleshooting—verifying &lt;strong&gt;template locations&lt;/strong&gt;, ensuring correct settings in &lt;strong&gt;settings.py&lt;/strong&gt;, and checking for &lt;strong&gt;typos&lt;/strong&gt;—you can resolve this issue efficiently. Understanding &lt;strong&gt;Django's templating system&lt;/strong&gt; and how it locates templates is crucial for developing dynamic, error-free web applications.&lt;/p&gt;
&lt;p&gt;Remember, the key to avoiding such errors lies in adhering to Django's project structure conventions and thoroughly checking your configuration settings. With these practices, you'll find working with Django templates to be a smooth and error-free experience.&lt;/p&gt;
&lt;h3 id=&quot;additional-resources&quot;&gt;&lt;strong&gt;Additional Resources&lt;/strong&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Django Official Documentation: Templates (&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.djangoproject.com/en/stable/topics/templates/&quot;&gt;https://docs.djangoproject.com/en/stable/topics/templates/&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Django Official Documentation: Settings (&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.djangoproject.com/en/stable/topics/settings/&quot;&gt;https://docs.djangoproject.com/en/stable/topics/settings/&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Python</category>
<guid isPermaLink="true">https://coderlegion.com/311/django-templatedoesnotexist-solved</guid>
<pubDate>Sat, 01 Jun 2024 23:24:56 +0000</pubDate>
</item>
<item>
<title>Python Exception Handling</title>
<link>https://coderlegion.com/166/python-exception-handling</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; While working on the Python code you come across a situation where your &lt;strong&gt;program is stopped by the compiler&lt;/strong&gt; during the execution and something like an error is displayed on the terminal, &lt;strong&gt;exception handling was the solution&lt;/strong&gt; at that time. Well, that is a common problem in every developer's life. In this tutorial I will talk about Python exceptions and different types of exceptions with examples, also why exception handling is important, and how Python manages these exceptions effectively. Let's get started.&lt;/p&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Why Error Handling Matters?&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Suppose you are using a food ordering application and suddenly the app crashes. You have no idea why the app stopped working. So, exception handling is essential as it &lt;strong&gt;prevents the app from future errors&lt;/strong&gt; and handles them effectively. Exception handling helps you with the smooth execution of your programs and &lt;strong&gt;removes the risk of abnormal event occurrence&lt;/strong&gt; if it's handled during the program development phase. If some errors are left unchecked then that will cause the application to crash, data loss, and worse, so that is the reason exception handling is a significant matter.&lt;/p&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;It &lt;strong&gt;prevents&lt;/strong&gt; the software from &lt;strong&gt;crashing and stopping abruptly&lt;/strong&gt;.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Make the &lt;strong&gt;user experience better&lt;/strong&gt; by reducing the frustration and confusion with properly displaying the error message.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;It &lt;strong&gt;ensures data safety and integrity&lt;/strong&gt; and handles data reliability.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;It also helps the developer to &lt;strong&gt;safeguard&lt;/strong&gt; their application from &lt;strong&gt;hacker attacks&lt;/strong&gt;.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;It &lt;strong&gt;reduces&lt;/strong&gt; the need for future &lt;strong&gt;cost increments for technical support&lt;/strong&gt; and saves time beforehand.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; How Python Manages Errors with Exception Handling?&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; During your programming life, you may encounter many types of errors, which can be a &lt;em&gt;syntactical error, an error that comes upon run-time, or a logical error.&lt;/em&gt; We can resolve the &lt;strong&gt;syntax error&lt;/strong&gt; simply because it will show the &lt;strong&gt;error on the compilation time &lt;/strong&gt;run time error  occurs it will not halt the program compilation but &lt;strong&gt;shows unexpected behavior&lt;/strong&gt; during the execution time that &lt;em&gt;deviates from the normal flow of the program&lt;/em&gt;. &lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Remember, a syntax error is a common error that can be caught before execution but if it is not caught in some situation at compile time then there is one built-in exception as well.&lt;/span&gt;
&lt;/div&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Exception Handling Different Ways&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Python manages the errors by &lt;strong&gt;writing the program&lt;/strong&gt; that handles the exception. There are many &lt;strong&gt;ways&lt;/strong&gt; for exception handling in Python. So, let's dive into it:&lt;/p&gt; 
&lt;ul&gt;   

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;strong&gt;Try:&lt;/strong&gt; When you see that a &lt;strong&gt;specific piece of code&lt;/strong&gt; will cause the error, you &lt;strong&gt;put it inside&lt;/strong&gt; the &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/164/python-try-except-blocks&quot; target=&quot;_blank&quot;&gt;try&lt;/a&gt; block.&lt;/li&gt;   

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;strong&gt;Except:&lt;/strong&gt; If the code in the try block creates an error. Python will &lt;strong&gt;jump to the except block&lt;/strong&gt; and execute it. So, right after the try block, we must write the except block. &lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;strong&gt;Finally:&lt;/strong&gt; After using the try and except block, you can use the &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/185/python-finally-block&quot; target=&quot;_blank&quot;&gt;finally&lt;/a&gt; block which always &lt;strong&gt;executes whether the exception occurs or not&lt;/strong&gt;.&lt;/li&gt;  

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;strong&gt;Else:&lt;/strong&gt; Instead of using the finally block, you can also use the else block right after a try-and-except block. It will help you to make sure that &lt;strong&gt;no exception occurs&lt;/strong&gt; in the program, as it will only run when there is no exception.&lt;/li&gt; 

&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;strong&gt;Raise:&lt;/strong&gt; One more exception handling is done by using the &lt;strong&gt;raise keyword&lt;/strong&gt;, you can use it without using try and except block and just raise an exception that would most probably pop up.&lt;/li&gt; 
&lt;/ul&gt; 
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;It is important to use except block when you are using a try block. Many except blocks can be used with one try block&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Understanding Exceptions&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Exceptions in Python&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Exception is like a situation that halts the normal flow of the program and stops the program in between without any reason. Exceptions are not related to the syntax error in the program but a run time issue. It will help the &lt;strong&gt;program to run smoothly and improve the robustness&lt;/strong&gt; of the program. In Python, an exception is like a &lt;strong&gt;capsule that encapsulates the error events&lt;/strong&gt; related to the program's abnormal behavior. When the Python compiler encounters a situation that cannot be handled on its own, it raises the exception by &lt;strong&gt;signaling the developer to resolve it&lt;/strong&gt;.&lt;/p&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Exploring Different Types of Exceptions&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; As we know there are &lt;strong&gt;two&lt;/strong&gt; types of exceptions in Python, each has its &lt;strong&gt;use case&lt;/strong&gt; and can be used by the developer in certain situations. These are:&lt;/p&gt; 
&lt;ul&gt; 
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt; Built-in Exception: &lt;/strong&gt; A built-in exception is a type that is &lt;strong&gt;already defined&lt;/strong&gt; in Python. These exceptions normally encounter errors by many of you, so Python developed the module based on it, which is helpful and time-saving.&lt;/li&gt;  
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt; &lt;strong&gt;User-defined exception &lt;/strong&gt; Sometimes a situation occurs where you cannot handle it by the available built-in exceptions, therefore Python allows you to make the &lt;strong&gt;custom exception&lt;/strong&gt; to handle this type of problem and the programmer has to define the exception on its own with coding.&lt;/li&gt; 
&lt;/ul&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Examples of Common built-in Exceptions&lt;/h2&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Python has a &lt;strong&gt;vast range of built-in exceptions&lt;/strong&gt;. Each exception has been used for specific error occurrences. Each has its use case. So, let's explore each one of them:&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;1: Value Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception occurs when the function gets an &lt;strong&gt;argument&lt;/strong&gt; with the &lt;strong&gt;correct datatype&lt;/strong&gt;, but the value of that &lt;strong&gt;datatype is invalid&lt;/strong&gt;.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#here we pass the string to int datatype that is an invalid value 
number = int(&quot;string&quot;) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17883826825220453929&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2: Type Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception occurs when the &lt;strong&gt;operation&lt;/strong&gt; is performed on an &lt;strong&gt;incorrect type.&lt;/strong&gt;&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#here we perform an addition operation on a string with an int datatype that is inappropriate
number = 7 + &quot;7&quot; 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11768622382153601869&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3: Assert Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception occurs when the &lt;strong&gt;assert expression fails&lt;/strong&gt;. Its main purpose is to debug and check expressions.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#here assertion error occurs because the expression fails 
assert 5!=5
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9188483604105506784&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;4: Module Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception occurs when you are trying to &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/217/mastering-importing-modules-in-python&quot; target=&quot;_blank&quot;&gt;import the module&lt;/a&gt;, but Python &lt;strong&gt;cannot locate the module&lt;/strong&gt;.&lt;/p&gt;  
&lt;pre&gt;&lt;code&gt;#here import cannot locate the specified module 
import module_Name 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7206665820801744251&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;5: Index Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; This exception occurs when you try to &lt;strong&gt;access the number&lt;/strong&gt; from the list that is not added or &lt;strong&gt;out of range&lt;/strong&gt;.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#here num_add variable tries to access the number at index 6 which is out of range 
number_list = [1,2,3,4,5] 
num_add = number_list[6] 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3474679075458745563&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;6: ZeroDivision Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception normally occurs when you try to &lt;strong&gt;divide a number&lt;/strong&gt; with the second operand as &lt;strong&gt;zero&lt;/strong&gt;.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#here num variable stores the result by dividing the 10 by 0 
num  = 10/0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1039050150387168991&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;7: Name Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; This exception occurs when you try to use a &lt;strong&gt;variable&lt;/strong&gt; that is &lt;strong&gt;not defined locally and globally&lt;/strong&gt; in the program&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#here when the variable is undefined, and you are trying to use it 
num = 10 
num2 = num/num3 
print(num2) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14814752257778344785&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;8: Syntax Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception occurs when the &lt;strong&gt;incorrect syntax is not detected&lt;/strong&gt; by the parse or interpreter before the code compilation.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#here syntax is incorrect 
num  10; 
num2 50; 
result 10 + 50
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4449602819913702930&quot; alt=&quot;&quot;&gt; &lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;9: FileNotFound Error&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception occurs when you &lt;strong&gt;try to open the file but it fails&lt;/strong&gt; because the compiler cannot find the specific file in your program folder. This exception is the &lt;strong&gt;subclass of the OSError exception.&lt;/strong&gt;&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;#Try to manipulate the file that is not available and cannot be found at the provided path 
def read_content_from_file(file_path):
    with open(file_path, 'r') as file:
        content =  file.readlines()
    
file_path = &quot;file.txt&quot;
read_content_from_file(file_path)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5856662375552249816&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;10: Indentation Error&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;This exception usually occurs when you &lt;strong&gt;use incorrect indentation&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#IndentationError: incorrect indent/space is used at the return line 
def add(): 
    num1 = 7 
    num2 = 25 
    result = num1 + num2 
        return result
    
cal = add()
print(&quot;Sum of two numbers&quot;, cal)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; &lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1198014179764549574&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;All exception types are objects because they are inherited from the exception base class.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-faq&quot; style=&quot;margin-bottom: 15px; margin-top: 3px;&quot;&gt; 
&lt;span class=&quot;faq-header&quot; style=&quot;font-weight: bold; color: dark-gray;&quot;&gt;FAQs&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt; Q: Can I create my exception? &lt;br&gt;A: Yes, you can define your custom-built exception class by inheriting it from the Exception base class.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt;Q: Is error or exception handling different? &lt;br&gt; A: Yes, there are many types of error that you can catch before compiling the code but sometimes the error occurs where only exception handling is required.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px;&quot;&gt; Q: Is it possible to execute the code regardless of checking error occurrence? &lt;br&gt; A: Yes, by using the finally block with the try and catch block you can execute the code that is written in the finally block because the finally block will execute whether the exception occurs or not.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; In conclusion, we discussed the need for exception handling in the software development process before the &lt;strong&gt;program is released&lt;/strong&gt; in the market or available for the user. As you know, exception handling is a &lt;strong&gt;powerful concept of programming&lt;/strong&gt; language. It helps you as well as &lt;strong&gt;prepares you beforehand for future errors&lt;/strong&gt;. Many &lt;strong&gt;built-in exceptions&lt;/strong&gt; provided by Python cover most of your errors during the program development but you can also use the &lt;strong&gt;custom-based exception&lt;/strong&gt; if you encounter a situation where no built-in exception is helpful, this problem is also resolved by the Python programming language. Now, I hope you will easily handle the exception in your code. Thank you for reading the guide. Happy Coding!&lt;/p&gt;
&lt;hr&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt; 
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/tutorial/errors.html&quot; title=&quot;Exceptions&quot;&gt; Errors and Exceptions Handling&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://python101.pythonlibrary.org/chapter7_exception_handling.html&quot; title=&quot;Exception handling&quot;&gt;Exception Handling in Python&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Error Handling</category>
<guid isPermaLink="true">https://coderlegion.com/166/python-exception-handling</guid>
<pubDate>Mon, 04 Mar 2024 22:54:04 +0000</pubDate>
</item>
</channel>
</rss>