<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python &#8211; NoloWiz</title>
	<atom:link href="https://nolowiz.com/category/programming/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://nolowiz.com</link>
	<description>Technology news, tips and tutorials</description>
	<lastBuildDate>Sun, 18 May 2025 03:57:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.8.12</generator>

<image>
	<url>https://nolowiz.com/wp-content/uploads/2021/01/cropped-android-chrome-512x512-2-32x32.png</url>
	<title>Python &#8211; NoloWiz</title>
	<link>https://nolowiz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>The easiest way to use OpenCV with Python</title>
		<link>https://nolowiz.com/the-easiest-way-to-use-opencv-with-python/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Sun, 18 May 2025 03:50:33 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=6407</guid>

					<description><![CDATA[<p>This tutorial will discuss the easiest way to use OpenCV with Python. As you know, OpenCV (Open Source Computer Vision Library) is an open-source library of programming functions mainly aimed at computer vision tasks. It provides image and video processing tools, object detection, face recognition, and machine learning. Widely used in robotics, AI, and augmented ... <a title="The easiest way to use OpenCV with Python" class="read-more" href="https://nolowiz.com/the-easiest-way-to-use-opencv-with-python/" aria-label="More on The easiest way to use OpenCV with Python">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/the-easiest-way-to-use-opencv-with-python/">The easiest way to use OpenCV with Python</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This tutorial will discuss the easiest way to use OpenCV with Python. As you know, OpenCV (Open Source Computer Vision Library) is an open-source library of programming functions mainly aimed at computer vision tasks. It provides image and video processing tools, object detection, face recognition, and machine learning. Widely used in robotics, AI, and augmented reality, it supports multiple languages like C++, Python, and Java.</p>



<p>Let&#8217;s start! First of all, you need to download and install <a href="https://www.python.org/" target="_blank" rel="noreferrer noopener">Python</a>. </p>



<p>Next, we will use UV as a package manager. <a href="https://docs.astral.sh/uv/" target="_blank" rel="noreferrer noopener">UV</a> is a fast, modern Python package manager developed by Astral. Designed as a drop-in replacement for pip and virtualenv, it uses the<a href="https://www.rust-lang.org/" target="_blank" rel="noreferrer noopener"> Rust programming language</a> for performance, resolving dependencies quickly and managing virtual environments efficiently. UV improves installation speed, reliability, and reproducibility, aiming to streamline Python development workflows with minimal configuration. The UV is 10 to 100 times faster than the pip package manager.</p>



<p></p>



<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354"
     crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2735334721002354"
     data-ad-slot="8835878737"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<p> Next, we need to create a virtual environment using uv. Run the following command in the terminal. Here I&#8217;m using Python 3.11.6 for the virtual environment, you can use any version you wish to work with. The virtual environment will be created in env folder.</p>



<pre class="wp-block-code"><code>uv venv --python 3.11.6 env</code></pre>



<p>To activate the virtual environment, run the following command :</p>



<p>For Windows users :</p>



<pre class="wp-block-code"><code>env\Scripts\activate</code></pre>



<p>Linux\Mac users :</p>



<pre class="wp-block-code"><code>source venv/bin/activate</code></pre>



<p>Finally, we can install opencv using uv. Run the following command to install it :</p>



<pre class="wp-block-code"><code>uv pip install opencv-python</code></pre>



<p>Or you can install opencv-headless using the below command</p>



<pre class="wp-block-code"><code>uv pip install opencv-python-headless</code></pre>



<p></p>



<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354"
     crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2735334721002354"
     data-ad-slot="8835878737"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<p>The difference between opencv-python and opencv-python-headless lies mainly in GUI support and dependencies:</p>



<h2>OpenCV-Python</h2>



<ul><li><strong>Includes GUI functionality</strong> (e.g., <code>cv2.imshow()</code>, <code>cv2.waitKey()</code>)</li><li>Requires GUI-related system libraries like GTK or Qt.</li><li>Suitable for <strong>local development</strong> or environments with a display.</li></ul>



<h2>Opencv-python-headless</h2>



<ul><li><strong>Excludes GUI features</strong>, so no <code>imshow()</code> window handling.</li><li>Smaller in size and fewer dependencies.</li><li>Ideal for <strong>server-side, Docker, CI/CD</strong>, or <strong>headless environments</strong>.</li></ul>



<p>After installation, you can run the following OpenCV test code :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
import cv2
import numpy as np

print(&quot;OpenCV version:&quot;, cv2.__version__)

image = cv2.imread(&quot;test.jpg&quot;)
if image is None:
    print(&quot;Image not found,creating a dummy image&quot;)
    image = 255 * np.ones((200, 200, 3), dtype=np.uint8)

# Display the image (only works with opencv-python, not headless)
cv2.imshow(&quot;Test Image&quot;, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</pre></div>


<p>The output of the app :</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="649" height="384" src="https://nolowiz.com/wp-content/uploads/2025/05/opencv-python-demo.png" alt="OpenCV Python demo" class="wp-image-6415" srcset="https://nolowiz.com/wp-content/uploads/2025/05/opencv-python-demo.png 649w, https://nolowiz.com/wp-content/uploads/2025/05/opencv-python-demo-300x178.png 300w, https://nolowiz.com/wp-content/uploads/2025/05/opencv-python-demo-150x89.png 150w" sizes="(max-width: 649px) 100vw, 649px" /></figure>



<h2>Conclusion</h2>



<p>In conclusion, it is easy to install and and use OpenCV with Python using uv package manager.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fthe-easiest-way-to-use-opencv-with-python%2F&amp;linkname=The%20easiest%20way%20to%20use%20OpenCV%20with%20Python" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fthe-easiest-way-to-use-opencv-with-python%2F&amp;linkname=The%20easiest%20way%20to%20use%20OpenCV%20with%20Python" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fthe-easiest-way-to-use-opencv-with-python%2F&amp;linkname=The%20easiest%20way%20to%20use%20OpenCV%20with%20Python" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fthe-easiest-way-to-use-opencv-with-python%2F&amp;linkname=The%20easiest%20way%20to%20use%20OpenCV%20with%20Python" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fthe-easiest-way-to-use-opencv-with-python%2F&#038;title=The%20easiest%20way%20to%20use%20OpenCV%20with%20Python" data-a2a-url="https://nolowiz.com/the-easiest-way-to-use-opencv-with-python/" data-a2a-title="The easiest way to use OpenCV with Python"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/the-easiest-way-to-use-opencv-with-python/">The easiest way to use OpenCV with Python</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Multi-Threading in Python and Free threaded Python 3.13</title>
		<link>https://nolowiz.com/multi-threading-in-python-and-free-threaded-python-3-13/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Sun, 24 Nov 2024 02:12:07 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=6233</guid>

					<description><![CDATA[<p>In this article, we will discuss how to achieve multi-threading in Python(Python 3.12 and lower) and test the latest free-threaded experimental feature available in Python 3.13. Python and GIL (Global Interpreter Lock) The Global Interpreter Lock (GIL) in Python is a mutex that ensures only one thread executes Python bytecode at a time.&#160;Because of GIL, ... <a title="Multi-Threading in Python and Free threaded Python 3.13" class="read-more" href="https://nolowiz.com/multi-threading-in-python-and-free-threaded-python-3-13/" aria-label="More on Multi-Threading in Python and Free threaded Python 3.13">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/multi-threading-in-python-and-free-threaded-python-3-13/">Multi-Threading in Python and Free threaded Python 3.13</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we will discuss how to achieve multi-threading in Python(Python 3.12 and lower) and test the latest free-threaded experimental feature available in Python 3.13.</p>



<h2>Python and GIL (Global Interpreter Lock)</h2>



<p>The Global Interpreter Lock (GIL) in Python is a mutex that ensures only one thread executes Python bytecode at a time.&nbsp;Because of GIL, we cannot run more than one thread at a time in Python Code. Let&#8217;s understand different Python implementations and GIL.</p>



<p>Python has several implementations :</p>



<ul><li><a href="https://www.python.org/" target="_blank" rel="noreferrer noopener">CPython </a>&#8211; The default and most widely used implementation of Python written in C</li><li><a href="https://www.jython.org/" target="_blank" rel="noreferrer noopener">Jython </a>&#8211; Python implementation written in Java</li><li><a href="https://ironpython.net/" target="_blank" rel="noreferrer noopener">IronPython </a>&#8211; A version of Python that is integrated with the .NET framework.</li><li><a href="https://pypy.org/" target="_blank" rel="noreferrer noopener">PyPy </a>&#8211; A Python implementation written in Python itself (Just-in-time (JIT) compiler to improve the execution speed) </li></ul>



<p>Out of these implementations, the following Python implementations have GIL:</p>



<ul><li>CPython</li><li> PyPy</li></ul>



<p>Since Jython and IronPython have no GIL, there is no issue with multithreading. Here we only discuss the default CPython implementation and multi-threading.</p>



<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>Types of tasks</h2>



<p>Let&#8217;s understand the types of tasks Python code needs to execute:</p>



<ol><li>CPU bound tasks</li><li>IO bound tasks</li><li>Asynchronous tasks</li></ol>



<h3>1. CPU-bo<span style="font-size: inherit;">und tasks</span> </h3>



<p>CPU-bound tasks require significant computing power. It depends on the processing speed of the CPU, for example :</p>



<ul><li>Mathematical computations  </li><li>Data processing &#8211; sorting data or image processing</li></ul>



<h3>2. <span style="font-size: inherit;">IO-bound tasks</span> </h3>



<p>I/O-bound tasks are operations where the execution time is primarily determined by input/output operations rather than CPU processing speed, for example :</p>



<ul><li>Network requests &#8211; Making HTTP requests</li><li>File operations &#8211; Reading or writing to a file</li><li>Database queries &#8211; fetching data from the database</li></ul>



<h3>3. Asynchronous Tasks</h3>



<p>Python also supports asynchronous programming. It is particularly suited for I/O-bound tasks. Using libraries like asyncio, developers can write non-blocking code that allows other tasks to run while waiting for I/O operations to complete.</p>



<h2>Multithreading in Python</h2>



<p>Let&#8217;s write some code to test multithreading in Python. The following Python codes were tested on the below environment :</p>



<ul><li>Processor: Intel Core i7-12700</li><li>Operating system: Windows 11, 64-bit</li></ul>



<p>We are going to use Python 3.13 for this code execution. Let&#8217;s write a CPU-bound task to calculate the n<sup>th</sup> Fibonacci number. Let&#8217;s calculate 38th Fibonacci number:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
import time

def fibonacci(n):
    if n &lt;= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

start = time.time()
fibonacci(38)
elapsed = time.time() - start
print(f&quot;Elapsed time : {elapsed:.2f}s&quot;)
</pre></div>


<p></p>



<pre class="wp-block-code"><code>Elapsed time : 3.24s</code></pre>



<p>We can see that the elapsed time is 3.24 seconds for Fibonacci calculation. Next, we do the same calculation on two parallel threads using <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" target="_blank" rel="noreferrer noopener">ThreadPoolExecutor</a>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
from concurrent.futures import ThreadPoolExecutor
import time


def fibonacci(n):
    if n &lt;= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)


def compute_fibonacci(num):
    start = time.time()
    fibonacci(num)
    elapsed = time.time() - start
    print(f&quot;Elapsed time : {elapsed:.2f}s&quot;)


if __name__ == &quot;__main__&quot;:
    numbers = &#91;38, 38]
    with ThreadPoolExecutor() as executor:
        for num in numbers:
            executor.submit(
                compute_fibonacci,
                num,
            )

</pre></div>


<p>The output of the above code :</p>



<pre class="wp-block-code"><code>Elapsed time : 6.20s
Elapsed time : 6.23s</code></pre>



<p>We can see that each thread took 6.2 seconds for the calculation. Due to GIL, we are not getting any parallel execution, and we need to wait for 6.2 seconds for both results.</p>



<h2>Process-based Parallelism</h2>



<p>In Python, process-based parallelism does not directly achieve multithreading; rather, it is an alternative approach to achieve parallel execution by creating multiple processes. Let&#8217;s do the same compuation using <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" target="_blank" rel="noreferrer noopener">ProcessPoolExecutor</a>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
from concurrent.futures import ProcessPoolExecutor
import time


def fibonacci(n):
    if n &lt;= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)


def compute_fibonacci(num):
    start = time.time()
    fibonacci(num)
    elapsed = time.time() - start
    print(f&quot;Elapsed time : {elapsed:.2f}s&quot;)


if __name__ == &quot;__main__&quot;:
    numbers = &#91;38, 38]
    with ProcessPoolExecutor() as executor:
        for num in numbers:
            executor.submit(
                compute_fibonacci,
                num,
            )

</pre></div>


<p>The output of the above script is :</p>



<pre class="wp-block-code"><code>Elapsed time : 3.24s
Elapsed time : 3.24s</code></pre>



<p>Now the Fibonacci calculation happens in parallel through Process-based parallelism.</p>



<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>Free threaded Python3.13</h2>



<p>I&#8217;ve tried the latest experimental free-threaded Python 3.13 which removes GIL limitation. Here is the result using ThreadPoolExecutor using the above Fibonacci code in free-threaded Python.</p>



<pre class="wp-block-code"><code>Elapsed time : 5.49s
Elapsed time : 5.50s</code></pre>



<p>We can see that we got speed improvement. However, this free threading has been observed to significantly slow down single-threaded performance(3.2 to 5.4 seconds), while potentially improving multi-threaded execution(6.2 to 5.4 seconds).</p>



<h2>Conclusion</h2>



<p>Due to GIL limitation, process-based parallelism can be used for the CPU-bound tasks to execute parallelly. At the time of this writing, the Python 3.13 freethreaded feature is experimental and is not ready for production use. In the future, we can expect full multithreading support in Python.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fmulti-threading-in-python-and-free-threaded-python-3-13%2F&amp;linkname=Multi-Threading%20in%20Python%20and%20Free%20threaded%20Python%203.13" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fmulti-threading-in-python-and-free-threaded-python-3-13%2F&amp;linkname=Multi-Threading%20in%20Python%20and%20Free%20threaded%20Python%203.13" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fmulti-threading-in-python-and-free-threaded-python-3-13%2F&amp;linkname=Multi-Threading%20in%20Python%20and%20Free%20threaded%20Python%203.13" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fmulti-threading-in-python-and-free-threaded-python-3-13%2F&amp;linkname=Multi-Threading%20in%20Python%20and%20Free%20threaded%20Python%203.13" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fmulti-threading-in-python-and-free-threaded-python-3-13%2F&#038;title=Multi-Threading%20in%20Python%20and%20Free%20threaded%20Python%203.13" data-a2a-url="https://nolowiz.com/multi-threading-in-python-and-free-threaded-python-3-13/" data-a2a-title="Multi-Threading in Python and Free threaded Python 3.13"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/multi-threading-in-python-and-free-threaded-python-3-13/">Multi-Threading in Python and Free threaded Python 3.13</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Monkey Patching in Python With Examples</title>
		<link>https://nolowiz.com/monkey-patching-in-python-with-examples/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Wed, 11 Oct 2023 16:44:14 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5705</guid>

					<description><![CDATA[<p>Monkey patching allows modifying existing code at runtime. In this tutorial, we will learn monkey patching in Python with examples. Monkey Patching Monkey patching is a technique in programming where you modify or extend existing code at runtime. It allows you to add, modify, or replace functionality in a class or module without directly modifying ... <a title="Monkey Patching in Python With Examples" class="read-more" href="https://nolowiz.com/monkey-patching-in-python-with-examples/" aria-label="More on Monkey Patching in Python With Examples">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/monkey-patching-in-python-with-examples/">Monkey Patching in Python With Examples</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Monkey patching allows modifying existing code at runtime. In this tutorial, we will learn monkey patching in Python with examples.</p>



<h2>Monkey Patching</h2>



<p>Monkey patching is a technique in programming where you modify or extend existing code at runtime. It allows you to add, modify, or replace functionality in a class or module without directly modifying its source code. It&#8217;s often used to fix bugs, add functionality, or customize third-party libraries without modifying their source code.</p>



<p>The term &#8220;monkey&#8221; in this context implies that these changes are being made in a playful, somewhat experimental, and potentially risky manner, similar to how a monkey might tamper with things.</p>



<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<p>Let&#8217;s understand it with some examples.</p>



<h3>Example 1</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
import math

math.pi = 3.2 #Monkey patching pi value

print(math.pi)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>3.2</code></pre>



<p>Here we are monkey patching the value of pi in the maths module. The value of pi is approximated to  3.2.</p>



<h3>Example 2</h3>



<p>Let&#8217;s understand how monkey patching can be used to extend a Python class. Suppose we have a MathOperations class with &#8220;add&#8221; member function.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
class MathOperations:
    def add(self, a, b):
        return a + b
</pre></div>


<p>Suppose we want to add the &#8220;subtract&#8221; method to the MathOperations class we can monkey-patch it.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
MathOperations.subtract = subtract
</pre></div>


<p>Now we have added subtract method to MathOperations class and we can use the subtract method  :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
math = MathOperations()
result = math.subtract(5, 3)  
print(result)
</pre></div>


<p><strong>Output </strong></p>



<pre class="wp-block-code"><code>2</code></pre>



<h3>Example 3</h3>



<p>Let&#8217;s understand dynamic behavior with one more example. Suppose we have a Greeting class defined in greetings.py file.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# greetings.py

class Greeting:
  def greet(self):
    print(&quot;Hello!&quot;)
</pre></div>


<p>We will create a new module it will change the behaviour of greet function at run time.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
from greetings import Greeting

def display(self):
    print(&quot;Hello NoloWiz&quot;)

Greeting.greet = display #monkey patching

greeting = Greeting()
greeting.greet()
</pre></div>


<p>Here greet function is replaced with newly defined display function. </p>



<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Hello NoloWiz</code></pre>



<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>When to Use Monkey Patching</h2>



<p>In the following situations we can use Monkey patching:</p>



<ul><li><strong>Third-party Libraries</strong>: When you need to add or modify functionality in a third-party library that you can&#8217;t modify directly, monkey patching can be used.</li></ul>



<ul><li><strong>Bug Fixes</strong>: If you encounter a bug in a library or framework and can&#8217;t wait for an official fix, you can patch it temporarily using monkey patching.</li></ul>



<ul><li><strong>Legacy Code</strong>: When working with legacy code that can&#8217;t be easily refactored, monkey patching can help you make necessary changes without rewriting the entire codebase.</li></ul>



<ul><li><strong>Experimental Code</strong>: In some cases, you might use monkey patching to experiment with new features or concepts before committing to a more permanent solution.</li></ul>



<p></p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fmonkey-patching-in-python-with-examples%2F&amp;linkname=Monkey%20Patching%20in%20Python%20With%20Examples" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fmonkey-patching-in-python-with-examples%2F&amp;linkname=Monkey%20Patching%20in%20Python%20With%20Examples" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fmonkey-patching-in-python-with-examples%2F&amp;linkname=Monkey%20Patching%20in%20Python%20With%20Examples" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fmonkey-patching-in-python-with-examples%2F&amp;linkname=Monkey%20Patching%20in%20Python%20With%20Examples" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fmonkey-patching-in-python-with-examples%2F&#038;title=Monkey%20Patching%20in%20Python%20With%20Examples" data-a2a-url="https://nolowiz.com/monkey-patching-in-python-with-examples/" data-a2a-title="Monkey Patching in Python With Examples"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/monkey-patching-in-python-with-examples/">Monkey Patching in Python With Examples</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Partial Functions in Python</title>
		<link>https://nolowiz.com/partial-functions-in-python/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Sun, 08 Oct 2023 13:21:03 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5686</guid>

					<description><![CDATA[<p>In this tutorial, we will learn partial functions and their usage in Python. What is Partial function? A partial function in programming is a function that is defined for only a subset of possible inputs. It allows you to specify a fixed number of arguments in advance, leaving some arguments to be provided later. This ... <a title="Partial Functions in Python" class="read-more" href="https://nolowiz.com/partial-functions-in-python/" aria-label="More on Partial Functions in Python">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/partial-functions-in-python/">Partial Functions in Python</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, we will learn partial functions and their usage in Python.</p>



<h2>What is Partial function?</h2>



<p>A partial function in programming is a function that is defined for only a subset of possible inputs. It allows you to specify a fixed number of arguments in advance, leaving some arguments to be provided later. This can be useful for creating reusable and flexible code.  </p>



<p>In Python, we can use the functools&#8217; <a href="https://docs.python.org/3/library/functools.html#functools.partial" target="_blank" rel="noreferrer noopener">partial function</a> to implement the partial function.The  functools is a module in Python&#8217;s standard library that provides higher-order functions and operations on callable objects.</p>



<h3>Example 1: </h3>



<p>Let&#8217;s understand with an example, suppose we have a function to multiply two numbers.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
def multiply(first_num, second_num):
  '''Multiply two numbers'''
  return first_num * second_num
</pre></div>


<p>We can convert the multiply function to calculate the double of a number using partial function.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
from functools import partial

double = partial(multiply,second_num=2)
</pre></div>


<p>Here one argument to multiply function is fixed(2), the partial function double can accept one number. Now we can call the function double :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
print(double(52))
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>104</code></pre>



<p>We can also add <a href="https://nolowiz.com/python-docstrings-format-and-examples/" target="_blank" rel="noreferrer noopener">docstring</a> to the partial function using the __doc__ dunder function.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
from functools import partial

double = partial(multiply,second_num=2)
double.__doc__ = &quot;Calcualte double of the number&quot;
</pre></div>


<h3>Example 2:</h3>



<p>Suppose we have a function to calculate the power of a number.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
def power(number,exponent):
  return number ** exponent
</pre></div>


<p>We can define a square and cube partial functions as shown below :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
square = partial(power,exponent=2)
cube = partial(power,exponent=3)
</pre></div>


<p>We can call cube partial function :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
print(cube(5))
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>125</code></pre>



<h2>When to use Partial functions</h2>



<p>Partial functions are usable in the following contexts :</p>



<ul><li>When you need to fix one or more arguments of a function and create a new function with reduced arity(The term &#8220;arity&#8221; refers to the number of arguments or parameters that a function or operation can accept).</li><li>We want to create a function with default arguments.</li><li>When you need to pass a function as an argument to another function with specific arguments already set.</li><li>When we want reusable code</li></ul>



<p></p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fpartial-functions-in-python%2F&amp;linkname=Partial%20Functions%20in%20Python" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fpartial-functions-in-python%2F&amp;linkname=Partial%20Functions%20in%20Python" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fpartial-functions-in-python%2F&amp;linkname=Partial%20Functions%20in%20Python" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fpartial-functions-in-python%2F&amp;linkname=Partial%20Functions%20in%20Python" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fpartial-functions-in-python%2F&#038;title=Partial%20Functions%20in%20Python" data-a2a-url="https://nolowiz.com/partial-functions-in-python/" data-a2a-title="Partial Functions in Python"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/partial-functions-in-python/">Partial Functions in Python</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python 3.12: Important New Features That You Should Know</title>
		<link>https://nolowiz.com/python-3-12-important-new-features-that-you-should-know/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Tue, 03 Oct 2023 17:38:15 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5625</guid>

					<description><![CDATA[<p>Python 3.12 has been released with some new features. In this article, we will discuss some important features of Python 3.12. 1. Improved Error Messages Python 3.12 introduced some new improved error messages, for example, &#8220;Did you&#8221; type error messages. More informative easy to easy-to-understand error messages. Another example considers the following Person class, the ... <a title="Python 3.12: Important New Features That You Should Know" class="read-more" href="https://nolowiz.com/python-3-12-important-new-features-that-you-should-know/" aria-label="More on Python 3.12: Important New Features That You Should Know">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/python-3-12-important-new-features-that-you-should-know/">Python 3.12: Important New Features That You Should Know</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python 3.12 has been released with some new features. In this article, we will discuss some important features of Python 3.12.</p>



<p></p>



<h2>1. Improved Error Messages</h2>



<p>Python 3.12 introduced some new improved error messages, for example, &#8220;Did you&#8221; type error messages. More informative easy to easy-to-understand error messages.</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="642" height="106" src="https://nolowiz.com/wp-content/uploads/2023/10/python-improved-errormessage.png" alt="Improved error message" class="wp-image-5626" srcset="https://nolowiz.com/wp-content/uploads/2023/10/python-improved-errormessage.png 642w, https://nolowiz.com/wp-content/uploads/2023/10/python-improved-errormessage-300x50.png 300w, https://nolowiz.com/wp-content/uploads/2023/10/python-improved-errormessage-640x106.png 640w, https://nolowiz.com/wp-content/uploads/2023/10/python-improved-errormessage-150x25.png 150w" sizes="(max-width: 642px) 100vw, 642px" /></figure>



<p>Another example considers the following Person class, the calculate method has an &#8220;age&#8221; variable :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
class Person:
   def __init__(self):
       self.age = 30

   def calculate(self):
       temp = age

Person().calculate() # Calling the calculate method 

</pre></div>


<p>When we execute the above it will generate a nicely formatted &#8220;Did you &#8221; error message as shown below.</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="585" height="172" src="https://nolowiz.com/wp-content/uploads/2023/10/python-error-message-variable.png" alt="Improved import error message" class="wp-image-5630" srcset="https://nolowiz.com/wp-content/uploads/2023/10/python-error-message-variable.png 585w, https://nolowiz.com/wp-content/uploads/2023/10/python-error-message-variable-300x88.png 300w, https://nolowiz.com/wp-content/uploads/2023/10/python-error-message-variable-150x44.png 150w" sizes="(max-width: 585px) 100vw, 585px" /></figure>



<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>2. Improved syntax error messages when importing modules</h2>



<p>Sometimes it is common to write &#8220;<span class="has-inline-color has-vivid-red-color">import x from y</span>&#8221; (the correct would be &#8220;<span class="has-inline-color has-vivid-red-color">from y import x</span>&#8220;), but this incorrect import will raise a nice syntax error as shown below.</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="586" height="98" src="https://nolowiz.com/wp-content/uploads/2023/10/import-error-enhanced-python.png" alt="Improved syntax error message" class="wp-image-5633" srcset="https://nolowiz.com/wp-content/uploads/2023/10/import-error-enhanced-python.png 586w, https://nolowiz.com/wp-content/uploads/2023/10/import-error-enhanced-python-300x50.png 300w, https://nolowiz.com/wp-content/uploads/2023/10/import-error-enhanced-python-150x25.png 150w" sizes="(max-width: 586px) 100vw, 586px" /></figure>



<h2>3. Improved import errors</h2>



<p>If we are importing a function/class from a module if the imported function/class name is not correct it will suggest a similar function/class name exists in the module. See the below example, we are importing &#8220;listdir&#8221; from the os module but the import statement has a typo &#8220;<span class="has-inline-color has-vivid-red-color">from os import lstdir</span>&#8220;. The import error shows &#8220;Did you&#8221; error.</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="469" height="100" src="https://nolowiz.com/wp-content/uploads/2023/10/importerror-typo.png" alt="Improved import error message" class="wp-image-5638" srcset="https://nolowiz.com/wp-content/uploads/2023/10/importerror-typo.png 469w, https://nolowiz.com/wp-content/uploads/2023/10/importerror-typo-300x64.png 300w, https://nolowiz.com/wp-content/uploads/2023/10/importerror-typo-150x32.png 150w" sizes="(max-width: 469px) 100vw, 469px" /></figure>



<h2>4. The f-string improvements</h2>



<p>Python 3.12 removes some of the old restrictions in the f-string. One interesting thing is &#8220;quote reuse&#8221;.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
fruits = &#91;&quot;apple&quot;,&quot;orange&quot;,&quot;grapes&quot;]
f&quot;Fruits are {&quot;,&quot;.join(fruits)}&quot;
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Fruits are apple,orange,grapes</code></pre>



<p>Here the &#8220;<span class="has-inline-color has-vivid-red-color">Fruits are {&#8220;,&#8221;.join(fruits)}</span>&#8221; quotes are reused older version of Python does not support this.</p>



<h2>5. New override decorator</h2>



<p>The <a href="https://docs.python.org/3.12/library/typing.html" target="_blank" rel="noreferrer noopener">typing </a>module introduced a new override decorator. It can used to indicate overridden methods in derived classes.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
from typing import override

class Base:
    def display(self) -&gt; None:
        print(&quot;hello&quot;)

class Sub(Base):
    @override
    def display(self) -&gt; None:  # Okay: overrides Base.display
        print(&quot;fine&quot;)

    @override
    def done(self) -&gt; None:  # Error reported by type checker
        print(&quot;bad&quot;)   
</pre></div>


<h2>6. Buffer protocol accessible in Python</h2>



<p>The <a href="https://docs.python.org/3.12/c-api/buffer.html#bufferobjects" target="_blank" rel="noreferrer noopener">buffer protocol</a> in Python allows direct access to the memory of an object. It provides a way to access data more efficiently by avoiding unnecessary copying. Classes that implement the __buffer__() method are now usable as buffer types.</p>



<p>The buffer objects can be represented by <a href="https://docs.python.org/3.12/library/collections.abc.html#collections.abc.Buffer" target="_blank" rel="noreferrer noopener">collections.abc.Buffer</a> ABC.</p>



<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>7. Standard library deprecations</h2>



<p>The distutils standard library is removed instead we can use the <a href="https://packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/" target="_blank" rel="noreferrer noopener">setuptools</a>. The distutils is a module that provides support for building and distributing Python packages. It is recommended to use setuptools for packaging and distribution tasks.</p>



<h2>8. Type Parameter Syntax</h2>



<p>Python 3.12 introduces a new compact way to create generic classes/functions. Earlier it was more verbose(<a href="https://peps.python.org/pep-0484/" target="_blank" rel="noreferrer noopener">PEP 484</a>).</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
def max&#91;T](args: Iterable&#91;T]) -&gt; T:
     # logic
</pre></div>


<p>As we can see it is using the more compact declaration of generic function.</p>



<h2>9. The&nbsp;type statement</h2>



<p>Python 3.12 introduces a new &#8220;type&#8221; statement to declare <a href="https://docs.python.org/3.12/library/typing.html#type-aliases" target="_blank" rel="noreferrer noopener">type aliases</a>. For example, a Point type can be declared using the type statement as shown below.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
type Point = tuple&#91;float, float]
</pre></div>


<p>We can also write type alias using generic type alias.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
type Point&#91;T] = tuple&#91;T, T]
</pre></div>


<h2>Conclusion</h2>



<p>There you have it, these are some important new features of Python 3.12.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-3-12-important-new-features-that-you-should-know%2F&amp;linkname=Python%203.12%3A%20Important%20New%20Features%20That%20You%20Should%20Know" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-3-12-important-new-features-that-you-should-know%2F&amp;linkname=Python%203.12%3A%20Important%20New%20Features%20That%20You%20Should%20Know" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-3-12-important-new-features-that-you-should-know%2F&amp;linkname=Python%203.12%3A%20Important%20New%20Features%20That%20You%20Should%20Know" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-3-12-important-new-features-that-you-should-know%2F&amp;linkname=Python%203.12%3A%20Important%20New%20Features%20That%20You%20Should%20Know" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fpython-3-12-important-new-features-that-you-should-know%2F&#038;title=Python%203.12%3A%20Important%20New%20Features%20That%20You%20Should%20Know" data-a2a-url="https://nolowiz.com/python-3-12-important-new-features-that-you-should-know/" data-a2a-title="Python 3.12: Important New Features That You Should Know"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/python-3-12-important-new-features-that-you-should-know/">Python 3.12: Important New Features That You Should Know</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python String Methods</title>
		<link>https://nolowiz.com/python-string-methods/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Fri, 08 Sep 2023 15:03:54 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5571</guid>

					<description><![CDATA[<p>Python provides a variety of built-in string methods that allow you to manipulate and work with strings. These methods help you perform tasks like finding substrings, replacing text, converting cases, and more. By learning these methods, you can efficiently handle string operations in your Python programs. Let&#8217;s dive into some of the most commonly used ... <a title="Python String Methods" class="read-more" href="https://nolowiz.com/python-string-methods/" aria-label="More on Python String Methods">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/python-string-methods/">Python String Methods</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python provides a variety of built-in string methods that allow you to manipulate and work with strings. These methods help you perform tasks like finding substrings, replacing text, converting cases, and more. By learning these methods, you can efficiently handle string operations in your <a href="https://www.python.org/" target="_blank" rel="noreferrer noopener">Python </a>programs.</p>



<p>Let&#8217;s dive into some of the most commonly used Python string methods:</p>



<h2>1. str.upper() and str.lower()</h2>



<p>The <code>str.upper()</code> the method used to convert a string to uppercase and  <code>str.lower()</code> method used to convert string to lowercase.</p>



<p>For example : </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;Hello, World!&quot;
uppercase_text = text.upper()
lowercase_text = text.lower()

print(uppercase_text)  
print(lowercase_text)  
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>HELLO, WORLD!
hello, world!
</code></pre>



<h2>2. str.strip()</h2>



<p>The <code>strip()</code> method removes leading and trailing whitespace characters (spaces, tabs, newlines) from a string. It&#8217;s particularly handy when you&#8217;re processing user input or cleaning up data.</p>



<p> For example : </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;   Python String Methods   &quot;
cleaned_text = text.strip()

print(cleaned_text) 

</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Python String Methods</code></pre>



<p>We can see that it removed leading and trailing spaces.</p>



<h2>3. str.split()</h2>



<p>This method splits a string into a list of substrings based on a specified delimiter. It&#8217;s frequently used for parsing text and working with CSV or TSV files.</p>



<p>For example :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
csv_data = &quot;John,Doe,30&quot;
data_list = csv_data.split(',')

print(data_list)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>&#91;'John', 'Doe', '30']</code></pre>



<h2>4. str.join()</h2>



<p>The join() method is the opposite of split(). The str.join() method is used to concatenate elements of a string iterable into a new string, using the string as a separator.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
words = &#91;&quot;Python&quot;, &quot;is&quot;, &quot;awesome&quot;]
sentence = &quot; &quot;.join(words)

print(sentence) 
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Python is awesome</code></pre>



<h2>5. str.replace()</h2>



<p>The str.replace() method is used to replace occurrences of a substring within a string with a new substring. It takes two arguments: the substring to be replaced and the new substring.</p>



<p>For example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
text = &quot;I love programming in JavaScript.&quot;
modified_text = text.replace(&quot;JavaScript&quot;, &quot;Python&quot;)

print(modified_text)  

</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>I love programming in Python.</code></pre>



<h2>6. str.find() and str.index()</h2>



<p>Both methods are used to search for a substring within a string.</p>



<p>The str.find method returns the index of the first occurrence of a substring within a string. If the substring is not found, it returns -1. It takes an optional start and end index to search within.</p>



<p>The str.index() method is used to find the index of the first occurrence of a substring in a string. It raises a ValueError if the substring is not found.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
text = &quot;Python is a powerful language.&quot;
position1 = text.find(&quot;is&quot;)  
position2 = text.index(&quot;Java&quot;)  # Raises ValueError
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>7</code></pre>



<h2>7. str.startswith() and str.endswith()</h2>



<p>The str.startswith() method checks if a string starts with a specified substring. It returns True if the string starts with the substring, and False otherwise. The method takes the substring as an argument and is case-sensitive.</p>



<p>For example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;www.example.com&quot;
starts_with_www = text.startswith(&quot;www&quot;)
</pre></div>


<p>Here &#8220;starts_with_www &#8221; variable holds the <span class="has-inline-color has-vivid-red-color">True</span> value.</p>



<p>The str.endswith() method checks if a string ends with a specified suffix. It returns True if the string ends with the suffix, and False otherwise. </p>



<p>For example :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;www.example.com&quot;
ends_with_net = text.endswith(&quot;net&quot;) 
</pre></div>


<p> Here &#8220;ends_with_net&#8221; variable holds the <span class="has-inline-color has-vivid-red-color">False </span>value. </p>



<h2>Conclusion</h2>



<p>There you have it different string methods used in Python Programming. <a href="https://nolowiz.com/python-string-find-substring-check-string-contains-substring/" target="_blank" rel="noreferrer noopener">Python String Find Substring – Check String Contains Substring</a>.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-string-methods%2F&amp;linkname=Python%20String%20Methods" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-string-methods%2F&amp;linkname=Python%20String%20Methods" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-string-methods%2F&amp;linkname=Python%20String%20Methods" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-string-methods%2F&amp;linkname=Python%20String%20Methods" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fpython-string-methods%2F&#038;title=Python%20String%20Methods" data-a2a-url="https://nolowiz.com/python-string-methods/" data-a2a-title="Python String Methods"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/python-string-methods/">Python String Methods</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Strings: A Comprehensive Guide</title>
		<link>https://nolowiz.com/python-strings-a-comprehensive-guide/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Fri, 08 Sep 2023 12:55:37 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5540</guid>

					<description><![CDATA[<p>Python Strings are a fundamental data type, and understanding how to manipulate them effectively is critical to becoming a proficient Python programmer. This comprehensive guide will explore Python strings in-depth, covering everything from basic operations to advanced techniques. Python String In Python, a string is a sequence of characters enclosed within single (&#8216; &#8216;), double ... <a title="Python Strings: A Comprehensive Guide" class="read-more" href="https://nolowiz.com/python-strings-a-comprehensive-guide/" aria-label="More on Python Strings: A Comprehensive Guide">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/python-strings-a-comprehensive-guide/">Python Strings: A Comprehensive Guide</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python Strings are a fundamental data type, and understanding how to manipulate them effectively is critical to becoming a proficient Python programmer. This comprehensive guide will explore Python strings in-depth, covering everything from basic operations to advanced techniques.</p>



<h2>Python String</h2>



<p>In Python, a string is a sequence of characters enclosed within single (<span class="has-inline-color has-vivid-red-color">&#8216; &#8216;</span>), double (<span class="has-inline-color has-vivid-red-color">&#8221; &#8220;</span>), or triple (<span class="has-inline-color has-vivid-red-color">&#8221;&#8217; &#8221;&#8217;</span> or <span class="has-inline-color has-vivid-red-color">&#8220;&#8221;&#8221; &#8220;&#8221;&#8221;</span>) quotes. These characters can include letters, numbers, symbols, and whitespace. Here&#8217;s a brief overview of declaring strings:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
single_quoted = 'This is a single-quoted string.'
double_quoted = &quot;This is a double-quoted string.&quot;
triple_quoted = '''This is a triple-quoted string.'''
</pre></div>


<p>Python treats single and double quotes equally, giving you flexibility in coding style.</p>



<h2>Multiline strings</h2>



<p>To create multiline strings, you can use triple quotes (<span class="has-inline-color has-vivid-red-color">&#8221;&#8217;</span> or <span class="has-inline-color has-vivid-red-color">&#8220;&#8221;&#8221;</span>) at the beginning and end of the string. This allows you to write the string on multiple lines without the need for escape characters.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
multiline_str = &quot;&quot;&quot;This is a multiline string.
It can span across multiple lines.
It is enclosed in triple quotes.&quot;&quot;&quot;

print(multiline_str)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>This is a multiline string.
It can span across multiple lines.
It is enclosed in triple quotes.</code></pre>



<h2>Raw strings</h2>



<p>Raw strings are string literals that treat backslashes(\) as literal characters, rather than escape characters. They are useful when dealing with regular expressions, file paths, and other situations where backslashes are commonly used. Raw strings are defined by prefixing the string with the letter <span class="has-inline-color has-vivid-red-color">&#8216;r&#8217;</span>.</p>



<p>Here are some examples :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
message = r'The output saved at &quot;D:\media files\&quot;'

print(message)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>The output saved at "D:\media files\"</code></pre>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
path = r&quot;C:\Program Files&quot;

print(path)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>C:\Program Files</code></pre>



<h2>Basic String Operations</h2>



<p>Let&#8217;s start with some fundamental operations for working with strings:</p>



<h3>1. Concatenation</h3>



<p>You can combine two or more strings using the <span class="has-inline-color has-vivid-red-color"><code>+</code> operator</span> or the &#8220;join&#8221; method.:</p>



<p>Here is an example using the + operator :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
first_name = &quot;Super&quot;
last_name = &quot;Mario&quot;
full_name = first_name + &quot; &quot; + last_name

print(full_name) 
</pre></div>


<p> <strong>Output</strong> </p>



<pre class="wp-block-code"><code>Super Mario</code></pre>



<p>Example using the join method : </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
strings = &#91;&quot;Hello&quot;, &quot;World&quot;]
greeting = &quot; &quot;.join(strings)

print(greeting)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Hello World</code></pre>



<h3>2. Repetition</h3>



<p>You can replicate a string using the &#8220;<code><span class="has-inline-color has-vivid-red-color">*</span></code>&#8221; operator:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
greeting = &quot;Hello, &quot;
repeat_greeting = greeting * 3

print(repeat_greeting) 

</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Hello, Hello, Hello,</code></pre>



<h3>3. Length</h3>



<p>To find the length of a string, you can use the <a href="https://nolowiz.com/what-is-len-in-python/" target="_blank" rel="noreferrer noopener">len()</a> function:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
message = &quot;Hello Nolowiz&quot;
length = len(message)

print(length)  
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>13</code></pre>



<h3>4. Indexing </h3>



<p>Strings are sequences, allowing you to access individual characters using indices.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;Python is amazing!&quot;

print(text&#91;0])      # Output: 'P' , indexing 

</pre></div>


<h2>Advanced String Manipulations</h2>



<p>Python&#8217;s string manipulation capabilities go well beyond the basics. You can use regular expressions, format strings, and more to handle complex tasks like parsing validation, and data transformation.</p>



<h3>1. Regular Expressions</h3>



<p>Python&#8217;s <a href="https://docs.python.org/3/library/re.html" target="_blank" rel="noreferrer noopener">re</a> module enables powerful string pattern matching using regular expressions. This is especially useful for tasks like email validation, text extraction, and complex string manipulation.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
import re

string = &quot;Hello, world!&quot;
pattern = &quot;hello&quot;

match = re.search(pattern, string, re.IGNORECASE)
if match:
    print(&quot;Match found!&quot;)
else:
    print(&quot;Match not found.&quot;)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Match found!</code></pre>



<h3>2. String Slicing</h3>



<p>Extract specific parts of a string using slicing syntax like <span class="has-inline-color has-vivid-red-color">string[start:end:step]</span>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;Python is amazing!&quot;

print(text&#91;10:14]) 
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>amaz</code></pre>



<p></p>



<h3>3. f-Strings</h3>



<p>Introduced in Python 3.6, f-strings allow you to embed expressions within string literals, making string formatting concise and readable:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
name = &quot;Alice&quot;
age = 30
formatted_string = f&quot;My name is {name} and I am {age} years old.&quot;

print(formatted_string) 
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>My name is Alice and I am 30 years old.</code></pre>



<h3>4. String Methods</h3>



<p>Python string has built-in methods like split(), join(), replace(), strip(), etc. for advanced string operations. You can learn Python string methods <a href="https://nolowiz.com/python-string-methods/" target="_blank" rel="noreferrer noopener">here </a>.</p>



<h2>Conclusion</h2>



<p>In this comprehensive guide, we&#8217;ve delved into the world of Python strings, covering the basics, common operations, essential string methods, and even advanced techniques like regular expressions and f-strings.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-strings-a-comprehensive-guide%2F&amp;linkname=Python%20Strings%3A%20A%20Comprehensive%20Guide" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-strings-a-comprehensive-guide%2F&amp;linkname=Python%20Strings%3A%20A%20Comprehensive%20Guide" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-strings-a-comprehensive-guide%2F&amp;linkname=Python%20Strings%3A%20A%20Comprehensive%20Guide" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fpython-strings-a-comprehensive-guide%2F&amp;linkname=Python%20Strings%3A%20A%20Comprehensive%20Guide" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fpython-strings-a-comprehensive-guide%2F&#038;title=Python%20Strings%3A%20A%20Comprehensive%20Guide" data-a2a-url="https://nolowiz.com/python-strings-a-comprehensive-guide/" data-a2a-title="Python Strings: A Comprehensive Guide"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/python-strings-a-comprehensive-guide/">Python Strings: A Comprehensive Guide</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>A Deep Dive into Python Data Types</title>
		<link>https://nolowiz.com/a-deep-dive-into-python-data-types/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Sun, 03 Sep 2023 13:07:51 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5452</guid>

					<description><![CDATA[<p>Python is one of the most beginner-friendly programming languages, it is very famous for its simplicity and readability. The robust data types of Python are the foundation of its adaptability and simplicity. In this tutorial, we will discuss Python data types. What Are Data Types? In programming, a data type defines the type of data ... <a title="A Deep Dive into Python Data Types" class="read-more" href="https://nolowiz.com/a-deep-dive-into-python-data-types/" aria-label="More on A Deep Dive into Python Data Types">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/a-deep-dive-into-python-data-types/">A Deep Dive into Python Data Types</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python is one of the most beginner-friendly programming languages, it is very famous for its simplicity and readability. The robust data types of Python are the foundation of its adaptability and simplicity. In this tutorial, we will discuss Python data types.</p>



<h2>What Are Data Types?</h2>



<p>In programming, a data type defines the type of data that a variable can hold. It specifies the range of values that the variable can take and the operations that can be performed on it.</p>



<h2>Python Data Types</h2>



<p>Python, as a dynamically typed language, provides a wide range of built-in data types that can be classified into several categories:</p>



<h3>1. Numeric Types</h3>



<p>There are 3 types of numeric data types in Python. </p>



<ul><li>int</li><li>float</li><li>complex</li></ul>



<h4><strong>int</strong>: Represents integers</h4>



<p>The <span class="has-inline-color has-vivid-red-color">int </span>data type in Python represents whole numbers without any decimal point. It can be used to perform arithmetic operations like addition, subtraction, multiplication, and division. Integers can be positive, negative, or zero. They have unlimited precision and can be created using the int() constructor or by directly assigning a value</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
count = 50
age = int(26) # using int constructor
</pre></div>


<h4><strong>float</strong>: Represents floating-point numbers</h4>



<p>The <span class="has-inline-color has-vivid-red-color">float </span>data type in Python represents decimal numbers. It is used to store real numbers, such as 3.14 or -0.5. Floating-point numbers can be manipulated using mathematical operations.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
temperature = 29.5
</pre></div>


<h4><strong>Complex</strong>: Represents complex numbers</h4>



<p>A <span class="has-inline-color has-vivid-red-color">complex </span>data type in Python represents complex numbers, which consist of a real part and an imaginary part. Complex numbers are written in the form a + bj, where a is the real part and b is the imaginary part. Example: </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
complex_num = 3 + 2j
</pre></div>


<h3>2. Boolean Type</h3>



<p>The Python boolean data type is used to represent two values: <span class="has-inline-color has-vivid-red-color">True and False</span>. It is commonly used in conditional statements and logical operations. Booleans are case-sensitive and must be written as True or False, with the first letter capitalized.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
is_recording = False
</pre></div>


<p></p>



<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354"
     crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2735334721002354"
     data-ad-slot="8835878737"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h3>3. Text Sequence Type</h3>



<p>Textual data is represented by the str data type in Python.</p>



<h4><strong>Str</strong>: Represents strings of characters</h4>



<p>The <span class="has-inline-color has-vivid-red-color">str</span> data type in Python is used to represent a sequence of characters. It is immutable, it means its value cannot be changed once created. Strings can be created using single quotes double quotes or triple quotes. Various methods are available to manipulate and operate on string objects.</p>



<p>For example, a string created using single quotes</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
blog_name = 'Nolowiz'
</pre></div>


<p> A string created using double quotes </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
blog_name = &quot;Nolowiz&quot;
</pre></div>


<p> For example, a string created using triple quotes  </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
blog_description = '''Technology tutorials,news,tips '''
</pre></div>


<h3>4.<strong> </strong>Sequence Types</h3>



<p>Sequence data types in Python are used to store multiple values in an ordered manner. The main sequence types are str, lists, tuples, and ranges. Different sequence data types  are :</p>



<ul><li>list</li><li>tuple</li><li>range</li></ul>



<h4><strong>List</strong>: Represents ordered, mutable sequences</h4>



<p>The Python <span class="has-inline-color has-vivid-red-color">list </span>data type allows you to store and manipulate a collection of items. You can add, remove, or modify elements using various methods such as append(), pop(), and insert(). Lists are mutable, meaning they can be modified after creation.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
odd_numbers = &#91;1,3,5,7]
</pre></div>


<h4><strong>Tuple</strong>: Represents ordered, immutable sequences</h4>



<p>A <span class="has-inline-color has-vivid-red-color">tuple</span> in Python is an immutable sequence data type that can store multiple elements. It is created using parentheses and elements are separated by commas. Tuples are commonly used to group related data together and can be accessed using indexing or unpacking.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
numbers = (10,20,30)
</pre></div>


<h4><strong>Range</strong>: Represents ordered, mutable sequences </h4>



<p>The<a href="https://nolowiz.com/python-range-function/"> range</a> data type in Python is used to generate a sequence of numbers. It is commonly used in &#8220;for&#8221; loops to iterate over a specific range of values. The range function takes start, stop, and step parameters to define the sequence.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
numbers = range(5)
</pre></div>

<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
for i in range(5):
    print(i)
</pre></div>


<p>This will print the numbers 0 to 4. You can read more about the range function <a href="https://nolowiz.com/python-range-function/" target="_blank" rel="noreferrer noopener">here</a>. </p>



<h3>5. Mapping Type </h3>



<p>The Python <span class="has-inline-color has-vivid-red-color">dict</span> data type is a collection of key-value pairs, where each key is unique. It allows you to store and retrieve values based on their associated keys. Dicts are mutable and can be modified using various methods like adding, updating, or deleting key-value pairs.</p>



<p>To create a dictionary in Python, use curly braces <span class="has-inline-color has-vivid-red-color">{} </span>and separate key-value pairs with colons. For example: <code>my_dict = {'key1': 'value1', 'key2': 'value2'}</code>. You can also use the <a href="https://docs.python.org/3/library/functions.html#func-dict" target="_blank" rel="noreferrer noopener">dict()</a> constructor or add key-value pairs using the square brackets.</p>



<p>For example :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
person = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30}
</pre></div>


<h3>6. Set Types</h3>



<p>Different types of set data types are :</p>



<ul><li>set</li><li>frozen set</li></ul>



<h4><strong>Set</strong>: Represents an unordered collection of unique elements</h4>



<p>The Python <span class="has-inline-color has-vivid-red-color">set </span>data type allows you to store a collection of unique elements. It is mutable and unordered. You can add, remove, and perform operations like union, intersection, and difference on sets.</p>



<p>To create a set in Python, you can use the <a href="https://docs.python.org/3/library/functions.html#func-set" target="_blank" rel="noreferrer noopener">set() </a>function or place items inside curly braces {}. For example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
my_set = {1, 2, 3} 

another_set = set(&#91;1,2,3])
</pre></div>


<h4><strong>Frozenset</strong>: Represents an immutable set</h4>



<p>The frozenset data type in Python is an immutable version of the set data type. It is created using the f<a href="https://docs.python.org/3/library/stdtypes.html#frozenset" target="_blank" rel="noreferrer noopener">rozenset()</a> function and cannot be modified once created. It is useful for storing and manipulating unique elements, just like the set data type.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
my_set = {1, 2, 3}
my_frozenset = frozen
set(my_set)print(my_frozenset)
</pre></div>


<p></p>



<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354"
     crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2735334721002354"
     data-ad-slot="8835878737"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h3>7. Binary Sequence Types</h3>



<p>Python supports different binary sequence types.</p>



<ul><li>bytes</li><li>bytearray</li><li>memoryview</li></ul>



<h4><strong>Bytes</strong>: Represents a sequence of bytes</h4>



<p>The <span class="has-inline-color has-vivid-red-color">bytes </span>data type in Python represents a sequence of byte values. It is immutable and used to store binary data like images or network packets. </p>



<p>To create a <a href="https://docs.python.org/3/library/stdtypes.html#bytes" target="_blank" rel="noreferrer noopener">bytes </a>data type in Python, you can use the bytes() constructor or by prefixing a string with b. Here&#8217;s an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
b_data = bytes(&#91;65, 66, 67])
print(b_data)
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>b'ABC'</code></pre>



<p>In the above example, the value of numbers([65,66,67)] must be between in range  (0 to 255). So  b_data = bytes([65, 66, 712]) is invalid because 712 is outside the specified range.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
b_data = b'Hello'
print(b_data) 
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>b'Hello'</code></pre>



<h4><strong>Bytearray</strong>: Represents a mutable sequence of bytes</h4>



<p>The <span class="has-inline-color has-vivid-red-color">bytearray </span>data type in Python is a mutable sequence that represents a collection of integers ranging from 0 to 255. It allows for efficient manipulation of binary data, such as encoding and decoding.</p>



<p>To create a bytearray in Python, use the <a href="https://docs.python.org/3/library/functions.html#func-bytearray" target="_blank" rel="noreferrer noopener">bytearray()</a> constructor and pass in the desired length or an iterable object containing integers. Here&#8217;s an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# Creating a bytearray with length 5
my_bytearray = bytearray(5)
</pre></div>

<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# Creating a bytearray from a list of integers
my_bytearray = bytearray(&#91;1, 2, 3, 4, 5])
</pre></div>


<h4><strong>Memoryview</strong>: Allows you to access the underlying memory of an object</h4>



<p>The <span class="has-inline-color has-vivid-red-color">memoryview </span>data type in Python allows direct access to the internal memory of an object, such as a bytearray. It provides a way to view and manipulate the data without creating a new copy.</p>



<p>To create a memoryview object in Python, you can use the <a href="https://docs.python.org/3/library/functions.html#func-memoryview" target="_blank" rel="noreferrer noopener">memoryview()</a> function. It takes an object that supports the buffer protocol as an argument. Here&#8217;s an example of using memoryview with a bytearray:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
data = bytearray(b'Hello, world!')
view = memoryview(data)
print(view&#91;7:12])
</pre></div>


<p>Please note that memoryview requires objects that support the buffer protocol.</p>



<h3>8. None Type</h3>



<p>The Python <span class="has-inline-color has-vivid-red-color">None </span>data type represents the absence of a value. It is often used to indicate that a variable or function does not have a specific value. For example, x = None assigns the variable x to the value None.</p>



<h2>Type Conversion</h2>



<p>Python allows you to convert between different data types, either implicitly or explicitly. Implicit conversion occurs automatically when Python converts one type to another to perform an operation, while explicit conversion is done explicitly by the programmer using functions like<span class="has-inline-color has-vivid-red-color"> <code>int()</code>, <code>str()</code>, or <code>float()</code></span>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# Implicit conversion
result = 5 + 2.0  # int + float = float
print(result)     # Output: 7.0

# Explicit conversion
number = &quot;42&quot;
number = int(number)  # Convert string to int
print(number)         # Output: 42
</pre></div>


<p>Python data types can be listed as a table :</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="1024" height="768" src="https://nolowiz.com/wp-content/uploads/2023/09/python-datatypes-table.png" alt="Python datatypes infographics" class="wp-image-5525" srcset="https://nolowiz.com/wp-content/uploads/2023/09/python-datatypes-table.png 1024w, https://nolowiz.com/wp-content/uploads/2023/09/python-datatypes-table-300x225.png 300w, https://nolowiz.com/wp-content/uploads/2023/09/python-datatypes-table-768x576.png 768w, https://nolowiz.com/wp-content/uploads/2023/09/python-datatypes-table-150x113.png 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2>Conclusion</h2>



<p>Data types are the foundation of Python programming, enabling you to work with various kinds of data effectively.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fa-deep-dive-into-python-data-types%2F&amp;linkname=A%20Deep%20Dive%20into%20Python%20Data%20Types" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fa-deep-dive-into-python-data-types%2F&amp;linkname=A%20Deep%20Dive%20into%20Python%20Data%20Types" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fa-deep-dive-into-python-data-types%2F&amp;linkname=A%20Deep%20Dive%20into%20Python%20Data%20Types" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fa-deep-dive-into-python-data-types%2F&amp;linkname=A%20Deep%20Dive%20into%20Python%20Data%20Types" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fa-deep-dive-into-python-data-types%2F&#038;title=A%20Deep%20Dive%20into%20Python%20Data%20Types" data-a2a-url="https://nolowiz.com/a-deep-dive-into-python-data-types/" data-a2a-title="A Deep Dive into Python Data Types"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/a-deep-dive-into-python-data-types/">A Deep Dive into Python Data Types</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Comments in Python Code</title>
		<link>https://nolowiz.com/comments-in-python-code/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Fri, 01 Sep 2023 14:02:20 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5427</guid>

					<description><![CDATA[<p>When it comes to writing clean, maintainable, and understandable code, Python is a language that excels. We know that comments are an essential part of a good code base. In this tutorial, we&#8217;ll learn how to write comments in Python Code. Why are Comments Important? Comments are lines of text in your code that the ... <a title="Comments in Python Code" class="read-more" href="https://nolowiz.com/comments-in-python-code/" aria-label="More on Comments in Python Code">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/comments-in-python-code/">Comments in Python Code</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>When it comes to writing clean, maintainable, and understandable code, Python is a language that excels. We know that comments are an essential part of a good code base. In this tutorial, we&#8217;ll learn how to write comments in Python Code.</p>



<h2>Why are Comments Important?</h2>



<p>Comments are lines of text in your code that the <a href="https://www.python.org/" target="_blank" rel="noreferrer noopener">Python </a>interpreter ignores. They exist solely to provide human-readable explanations of the code&#8217;s functionality, logic, or any other relevant information. They act as a form of documentation, helping developers grasp the intent behind the code without having to decipher every line.</p>



<h2>Types of Comments</h2>



<p>There are two types of comments in Python :</p>



<ol><li>Single-line comment </li><li>Multi-line comment</li></ol>



<h3>1. Single-line comments</h3>



<p>These are comments that appear on a single line and are used to annotate a specific line of code. They begin with the<span class="has-inline-color has-vivid-red-color"> <code>#</code></span> symbol and continue until the end of the line.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# This is a single-line comment
</pre></div>


<p>However, the below code is not a comment even though it has a <span class="has-inline-color has-vivid-red-color"># </span>symbol.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
text = &quot;# This is not a comment because it's inside quotes.&quot;
</pre></div>


<h3> 2. Multi-line comments </h3>



<p>Multi-line comments in Python can be written using triple quotes (&#8221;&#8217; &#8221;&#8217;) or triple double quotes (&#8220;&#8221;&#8221; &#8220;&#8221;&#8221;). This allows you to write multiple lines of comments without using the # symbol at the beginning of each line.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
&quot;&quot;&quot;
This is a 
multi-line comment in 
Python programming
&quot;&quot;&quot;
</pre></div>


<p>Multi-line comment with triple quotes example :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
'''
This is a another
multi-line comment in 
Python programming using the triple quotes 
'''
</pre></div>


<h2>When to Use Comments</h2>



<ol><li><strong>Complex algorithms:</strong> If you&#8217;re implementing a complex algorithm or logic, comments can help break down the steps and provide insights into the thought process.</li><li><strong>Workarounds or hacks</strong>: If you&#8217;re using a workaround or a less-than-ideal solution due to constraints, explain the reason in a comment.</li><li><strong>Important decisions</strong>: Comments are valuable for explaining design decisions, especially when multiple options are considered before settling on a particular approach.</li><li><strong>Potential pitfalls:</strong> If a piece of code has potential pitfalls or edge cases, use comments to highlight these areas.</li></ol>



<h2>Conclusion</h2>



<p>In conclusion, Python comments are a very effective tool for writing clean and comprehensible code. <a href="https://nolowiz.com/python-docstrings-format-and-examples/" target="_blank" rel="noreferrer noopener">You can read about Python docstrings, format, and examples</a>.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Fcomments-in-python-code%2F&amp;linkname=Comments%20in%20Python%20Code" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Fcomments-in-python-code%2F&amp;linkname=Comments%20in%20Python%20Code" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Fcomments-in-python-code%2F&amp;linkname=Comments%20in%20Python%20Code" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Fcomments-in-python-code%2F&amp;linkname=Comments%20in%20Python%20Code" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Fcomments-in-python-code%2F&#038;title=Comments%20in%20Python%20Code" data-a2a-url="https://nolowiz.com/comments-in-python-code/" data-a2a-title="Comments in Python Code"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/comments-in-python-code/">Comments in Python Code</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Understanding Python Variables: A Comprehensive Guide</title>
		<link>https://nolowiz.com/understanding-python-variables-a-comprehensive-guide/</link>
		
		<dc:creator><![CDATA[Rupesh Sreeraman]]></dc:creator>
		<pubDate>Thu, 31 Aug 2023 14:02:40 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://nolowiz.com/?p=5388</guid>

					<description><![CDATA[<p>Variables are used to store and manipulate data in programming. In this tutorial, we&#8217;ll delve into the concept of variables in Python, exploring their definition, naming conventions, data types, and best practices. Python variables declaration In Python, a variable is essentially a name that refers to a value stored in memory. Unlike some other programming ... <a title="Understanding Python Variables: A Comprehensive Guide" class="read-more" href="https://nolowiz.com/understanding-python-variables-a-comprehensive-guide/" aria-label="More on Understanding Python Variables: A Comprehensive Guide">Read more</a></p>
<p>The post <a rel="nofollow" href="https://nolowiz.com/understanding-python-variables-a-comprehensive-guide/">Understanding Python Variables: A Comprehensive Guide</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Variables are used to store and manipulate data in programming. In this tutorial, we&#8217;ll delve into the concept of variables in Python, exploring their definition, naming conventions, data types, and best practices.</p>



<h2>Python variables declaration</h2>



<p>In Python, a variable is essentially a name that refers to a value stored in memory. Unlike some other programming languages, you don&#8217;t need to declare the type of a variable explicitly; Python does this for you. </p>



<p>To declare a variable in Python, use the assignment operator (=) followed by the variable name. For example, age = 25 declares a variable named &#8220;age&#8221; and assigns it the value 25.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
age = 25
</pre></div>


<p>In Python, variables are dynamically typed, which means you don&#8217;t need to explicitly declare their type. You simply assign a value to a variable, and Python will automatically determine its type based on the value you provide. Here&#8217;s how you declare and assign values to variables in Python:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
# Assigning values to variables
name = &quot;Alice&quot;           # String
age = 25                 # Integer
height = 5.8             # Float
is_student = True         # Boolean
grades = &#91;85, 90, 78]    # List
coordinates = (10, 20)   # Tuple
person = {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}  # Dictionary
unique_numbers = {1, 2, 3}  # Set

</pre></div>


<p></p>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354" crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2735334721002354" data-ad-slot="8835878737" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>Naming Conventions</h2>



<p>Python has some rules and guidelines for naming variables:</p>



<ol><li>Use lowercase letters for Python variables.</li><li>Python variable names cannot start with a number.</li><li>A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _).</li><li>Separate words with underscores (snake_case).</li><li>Avoid using reserved words (e.g., &#8220;print&#8221;, &#8220;if&#8221;, &#8220;for&#8221;).</li><li>Use descriptive names that indicate the variable&#8217;s purpose.</li><li>Constants are typically written in uppercase (e.g., &#8220;MAX_VALUE&#8221;).</li><li>Don&#8217;t use abbreviations.</li></ol>



<h2>Data Types</h2>



<p>Python variables can hold various types of data, including:</p>



<ol><li><strong>Integers:</strong> Whole numbers without decimal points, e.g., <code>age = 25</code>.</li><li><strong>Floats:</strong> Numbers with decimal points, e.g., <code>pi = 3.14</code>.</li><li><strong>Strings:</strong> Sequences of characters, e.g., <code>name = "Alice"</code>.</li><li><strong>Booleans:</strong> Represents either <code>True</code> or <code>False</code> values, e.g., <code>is_valid = True</code>.</li><li><strong>Lists:</strong> Ordered collections of items, e.g., <code>numbers = [1, 2, 3, 4, 5]</code>.</li><li><strong>Tuples:</strong> Similar to lists, but immutable, e.g., <code>coordinates = (10, 20)</code>.</li><li><strong>Dictionaries:</strong> Key-value pairs, e.g., <code>person = {"name": "Bob", "age": 30}</code>.</li><li><strong>Sets:</strong> Unordered collections of unique items, e.g., <code>unique_numbers = {1, 2, 3}</code>.</li></ol>



<h2>Best Practices</h2>



<p>To write clean and maintainable code, it&#8217;s important to follow some best practices when working with variables in Python:</p>



<ol><li><strong>Descriptive Names:</strong> Choose meaningful variable names that reflect the purpose of the variable. For example, use <code>total_students</code> instead of just <code>count</code>.</li><li><strong>Consistent Casing:</strong> Stick to a consistent naming convention. Many Python developers prefer using lowercase letters and underscores (<code>snake_case</code>) for variable names.</li><li><strong>Initialize Variables:</strong> Always initialize variables before using them to avoid unexpected behavior.</li><li><strong>Avoid Magic Numbers:</strong> Instead of using raw numbers in your code, assign them to variables with descriptive names. This improves code readability and makes maintenance easier (e.g.: MAX_VALUE = 100).</li><li><strong>Use Comments:</strong> If a variable&#8217;s purpose might not be immediately obvious, provide comments to explain its significance and usage.</li></ol>



<p></p>



<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2735334721002354"
     crossorigin="anonymous"></script>
<!-- article-horizontal -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2735334721002354"
     data-ad-slot="8835878737"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<p></p>



<h2>Python Global variables</h2>



<p>A Python global variable is a variable that can be accessed and modified from any part of a program. It is defined outside of any function and can be used throughout the entire program. Global variables can be useful for storing data that is needed across different functions or modules. Here is an example :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
greeting = &quot;Hello&quot;

def display_message():
  print( greeting + &quot; nolowiz&quot; )

display_message()
</pre></div>


<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>Hello nolowiz</code></pre>



<p>In the above code, the variable &#8220;greeting&#8221; is a global variable. </p>



<p><strong>What happens if the same variable name is inside the function?</strong></p>



<p>In the below example, the global variable name(Line number: 1) and variable( Line number: 4)  inside the display_message function have the same name.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
greeting = &quot;Hello&quot;

def display_message():
  greeting = &quot;Hi&quot;
  print( greeting + &quot; nolowiz&quot; )

display_message()

print(greeting + &quot; nolowiz&quot;)

</pre></div>


<p><strong>Output</strong></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
Hi nolowiz
Hello nolowiz
</pre></div>


<p>So the &#8220;greeting&#8221; variable inside the display_message function is a local variable. However the global variable ( Line number: 1) value remains the same.</p>



<h3>The global Keyword</h3>



<p>The <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-python-grammar-global_stmt" target="_blank" rel="noreferrer noopener">global keyword</a> in Python is used to declare a variable as global within a function, allowing it to be accessed and modified outside the function. It is used to differentiate between local and global variables with the same name.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: python; title: ; notranslate">
x = 10

def update_value():
    global x
    x = 20
    
print(x)  # Output: 10

update_value()

print(x)  # Output: 20
</pre></div>


<p>Here global variable x is modified inside the update_value function using the global keyword.</p>



<p><strong>Output</strong></p>



<pre class="wp-block-code"><code>10
20</code></pre>



<h2>Conclusion</h2>



<p>In conclusion, variables are fundamental components of any programming language, and Python&#8217;s approach to variables adds a layer of simplicity and versatility to the coding experience. <a href="https://nolowiz.com/basics-of-a-python-program/" target="_blank" rel="noreferrer noopener">Read about the basics of a Python program</a>.</p>
<p><a class="a2a_button_twitter" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Fnolowiz.com%2Funderstanding-python-variables-a-comprehensive-guide%2F&amp;linkname=Understanding%20Python%20Variables%3A%20A%20Comprehensive%20Guide" title="Twitter" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_whatsapp" href="https://www.addtoany.com/add_to/whatsapp?linkurl=https%3A%2F%2Fnolowiz.com%2Funderstanding-python-variables-a-comprehensive-guide%2F&amp;linkname=Understanding%20Python%20Variables%3A%20A%20Comprehensive%20Guide" title="WhatsApp" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fnolowiz.com%2Funderstanding-python-variables-a-comprehensive-guide%2F&amp;linkname=Understanding%20Python%20Variables%3A%20A%20Comprehensive%20Guide" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_copy_link" href="https://www.addtoany.com/add_to/copy_link?linkurl=https%3A%2F%2Fnolowiz.com%2Funderstanding-python-variables-a-comprehensive-guide%2F&amp;linkname=Understanding%20Python%20Variables%3A%20A%20Comprehensive%20Guide" title="Copy Link" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fnolowiz.com%2Funderstanding-python-variables-a-comprehensive-guide%2F&#038;title=Understanding%20Python%20Variables%3A%20A%20Comprehensive%20Guide" data-a2a-url="https://nolowiz.com/understanding-python-variables-a-comprehensive-guide/" data-a2a-title="Understanding Python Variables: A Comprehensive Guide"></a></p><p>The post <a rel="nofollow" href="https://nolowiz.com/understanding-python-variables-a-comprehensive-guide/">Understanding Python Variables: A Comprehensive Guide</a> appeared first on <a rel="nofollow" href="https://nolowiz.com">NoloWiz</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
