<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sejal on Medium]]></title>
        <description><![CDATA[Stories by Sejal on Medium]]></description>
        <link>https://medium.com/@sejalhazare9405?source=rss-a9e10b4d137b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Sejal on Medium</title>
            <link>https://medium.com/@sejalhazare9405?source=rss-a9e10b4d137b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:45:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sejalhazare9405/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Python Functions: A Complete Guide for Writing Cleaner, Reusable Code]]></title>
            <link>https://medium.com/@sejalhazare9405/mastering-python-functions-a-complete-guide-for-writing-cleaner-reusable-code-fd2bdee3590d?source=rss-a9e10b4d137b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2bdee3590d</guid>
            <dc:creator><![CDATA[Sejal]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 06:06:15 GMT</pubDate>
            <atom:updated>2026-08-17T06:06:15.511Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Functions are the building blocks of every well-structured Python program. Here’s everything you need to know to use them like a pro.</em></p><h3>Introduction</h3><p>If you’ve written more than a few lines of Python, you’ve already used a function — print(), len(), range() are all functions doing work behind the scenes. But once you start writing your <em>own</em> functions, something changes. Your code stops being a long, repetitive script and starts becoming an organized, reusable, and testable program.</p><p>In this article, we’ll walk through everything you need to know about Python functions — from the basics to more advanced concepts like *args, **kwargs, default parameters, lambda functions, and best practices used by professional developers.</p><p>Let’s dive in.</p><h3>1. What Is a Function?</h3><p>A function is a named block of reusable code that performs a specific task. Instead of writing the same logic over and over, you define it once and call it whenever you need it.</p><pre>def greet(name):<br>    print(f&quot;Hello, {name}!&quot;)</pre><pre>greet(&quot;Alice&quot;)<br>greet(&quot;Bob&quot;)</pre><p><strong>Output:</strong></p><pre>Hello, Alice!<br>Hello, Bob!</pre><p>Here, greet() is defined once but used twice — that&#39;s the core idea behind functions: <strong>write once, use many times.</strong></p><h3>2. Why Use Functions?</h3><p>Before going further, it’s worth understanding <em>why</em> functions matter so much in professional code:</p><ul><li><strong>Reusability</strong> — Write logic once, use it anywhere.</li><li><strong>Readability</strong> — Breaking code into functions makes it easier to follow.</li><li><strong>Maintainability</strong> — Fixing a bug in one function fixes it everywhere it’s used.</li><li><strong>Testability</strong> — Functions can be tested in isolation.</li><li><strong>Abstraction</strong> — You can use a function without knowing its internal implementation.</li></ul><h3>3. Anatomy of a Python Function</h3><pre>def function_name(parameters):<br>    &quot;&quot;&quot;Optional docstring explaining what the function does.&quot;&quot;&quot;<br>    # function body<br>    return value</pre><ul><li>def — keyword used to define a function</li><li>function_name — a descriptive name (use snake_case)</li><li>parameters — inputs the function accepts (optional)</li><li>docstring — a short description of what the function does</li><li>return — sends a value back to the caller (optional)</li></ul><p>Example:</p><pre>def add(a, b):<br>    &quot;&quot;&quot;Returns the sum of two numbers.&quot;&quot;&quot;<br>    return a + b</pre><pre>result = add(5, 3)<br>print(result)  # 8</pre><h3>4. Parameters and Arguments</h3><h3>Default Parameters</h3><p>You can give parameters default values, making them optional when calling the function.</p><pre>def greet(name, greeting=&quot;Hello&quot;):<br>    print(f&quot;{greeting}, {name}!&quot;)</pre><pre>greet(&quot;Sam&quot;)                # Hello, Sam!<br>greet(&quot;Sam&quot;, &quot;Good morning&quot;) # Good morning, Sam!</pre><h3>Keyword Arguments</h3><p>You can pass arguments by name, in any order:</p><pre>def describe_pet(name, animal_type):<br>    print(f&quot;{name} is a {animal_type}.&quot;)</pre><pre>describe_pet(animal_type=&quot;dog&quot;, name=&quot;Rex&quot;)</pre><h3>*args – Variable Number of Positional Arguments</h3><pre>def total(*numbers):<br>    return sum(numbers)</pre><pre>print(total(1, 2, 3, 4))  # 10</pre><h3>**kwargs – Variable Number of Keyword Arguments</h3><pre>def print_profile(**info):<br>    for key, value in info.items():<br>        print(f&quot;{key}: {value}&quot;)</pre><pre>print_profile(name=&quot;Alice&quot;, age=25, city=&quot;New York&quot;)</pre><h3>5. Return Values</h3><p>A function doesn’t have to return anything, but when it does, return sends data back to wherever the function was called.</p><pre>def square(x):<br>    return x * x</pre><pre>result = square(4)<br>print(result)  # 16</pre><p>You can also return multiple values using tuples:</p><pre>def min_max(numbers):<br>    return min(numbers), max(numbers)</pre><pre>low, high = min_max([4, 7, 1, 9, 2])<br>print(low, high)  # 1 9</pre><h3>6. Scope: Local vs. Global Variables</h3><p>Variables defined inside a function are <strong>local</strong> — they don’t exist outside it.</p><pre>def my_function():<br>    x = 10  # local variable<br>    print(x)</pre><pre>my_function()<br>print(x)  # NameError: x is not defined</pre><p>To modify a global variable inside a function, use the global keyword (though this should be used sparingly):</p><pre>counter = 0</pre><pre>def increment():<br>    global counter<br>    counter += 1</pre><pre>increment()<br>print(counter)  # 1</pre><h3>7. Lambda Functions (Anonymous Functions)</h3><p>For short, throwaway functions, Python offers lambda — a one-line, unnamed function.</p><pre>square = lambda x: x * x<br>print(square(5))  # 25</pre><p>Lambdas are especially useful with functions like map(), filter(), and sorted():</p><pre>numbers = [1, 2, 3, 4, 5]<br>squared = list(map(lambda x: x ** 2, numbers))<br>print(squared)  # [1, 4, 9, 16, 25]</pre><h3>8. Docstrings and Type Hints (Professional Practices)</h3><p>Professional Python code documents its functions clearly and often uses type hints for clarity and better tooling support.</p><pre>def calculate_area(radius: float) -&gt; float:<br>    &quot;&quot;&quot;<br>    Calculate the area of a circle.</pre><pre>    Args:<br>        radius (float): The radius of the circle.</pre><pre>    Returns:<br>        float: The area of the circle.<br>    &quot;&quot;&quot;<br>    import math<br>    return math.pi * radius ** 2</pre><p>Type hints don’t enforce types at runtime, but they make your code self-documenting and help tools like linters and IDEs catch errors early.</p><h3>9. Common Mistakes to Avoid</h3><ul><li><strong>Mutable default arguments</strong> — avoid using lists or dictionaries as default values.</li><li># Bad def add_item(item, items=[]): items.append(item) return items # Good def add_item(item, items=None): if items is None: items = [] items.append(item) return items</li><li><strong>Overly long functions</strong> — if a function does too much, break it into smaller ones.</li><li><strong>Unclear naming</strong> — do_stuff() tells you nothing; calculate_tax() does.</li><li><strong>Not using </strong><strong>return</strong> — relying on print statements instead of returning values makes functions hard to reuse and test.</li></ul><h3>10. Putting It All Together</h3><p>Here’s a small, complete example that ties several concepts together:</p><pre>def calculate_total(prices: list[float], discount: float = 0.0) -&gt; float:<br>    &quot;&quot;&quot;<br>    Calculate the total price after applying a discount.</pre><pre>    Args:<br>        prices (list[float]): List of item prices.<br>        discount (float): Discount as a decimal (e.g., 0.1 for 10%).</pre><pre>    Returns:<br>        float: Final total after discount.<br>    &quot;&quot;&quot;<br>    subtotal = sum(prices)<br>    total = subtotal * (1 - discount)<br>    return round(total, 2)<br></pre><pre>cart = [19.99, 5.49, 12.00]<br>final_price = calculate_total(cart, discount=0.1)<br>print(f&quot;Total: ${final_price}&quot;)  # Total: $34.03</pre><p>This function is reusable, documented, testable, and readable — everything a good function should be.</p><h3>Conclusion</h3><p>Functions are more than just a syntax feature in Python — they’re a mindset. Once you start thinking in terms of small, focused, reusable blocks of logic, your code naturally becomes cleaner and easier to maintain.</p><p>Whether you’re building a simple script or a large-scale application, mastering functions is one of the most valuable skills you can develop as a Python programmer.</p><p><strong>Next time you find yourself copy-pasting the same code twice, stop — and turn it into a function.</strong></p><p><em>If you found this article helpful, feel free to follow for more Python tutorials, or leave a comment with topics you’d like covered next!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2bdee3590d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>