<?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>Abhigyan Ojha &#8211; Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/abhigyan/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com</link>
	<description></description>
	<lastBuildDate>Sun, 02 Jan 2022 09:46:34 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Abhigyan Ojha &#8211; Be on the Right Side of Change</title>
	<link>https://blog.finxter.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>What Does &#8220;if __name__ == &#8216;__main__&#039;&#8221; Do in Python?</title>
		<link>https://blog.finxter.com/what-does-if-__name__-__main__-do-in-python/</link>
		
		<dc:creator><![CDATA[Abhigyan Ojha]]></dc:creator>
		<pubDate>Tue, 30 Jun 2020 15:05:38 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Object Orientation]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=10260</guid>

					<description><![CDATA[Today, let&#8217;s discuss something that&#8217;s all over the place in many code bases: what does&#160;if __name__ == '__main__'&#160;do in Python? The statement if __name__ == '__main__': checks if variable __name__ is set to the string value '__main__' which holds only within the main source file from which you initially execute your code. In all other ... <a title="What Does &#8220;if __name__ == &#8216;__main__&#039;&#8221; Do in Python?" class="read-more" href="https://blog.finxter.com/what-does-if-__name__-__main__-do-in-python/" aria-label="Read more about What Does &#8220;if __name__ == &#8216;__main__&#039;&#8221; Do in Python?">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Today, let&#8217;s discuss something that&#8217;s all over the place in many code bases: what does&nbsp;<strong><em><code>if __name__ == '__main__'</code></em></strong>&nbsp;do in Python?</p>



<p class="has-luminous-vivid-amber-background-color has-background wp-block-paragraph">The statement <code>if __name__ == '__main__':</code> checks if variable <code>__name__</code> is set to the string value <code>'__main__'</code> which holds only within the main source file from which you initially execute your code. In all other contexts&#8212;such as in imported code files&#8212;the variable <code>__name__</code> is set to a different value. </p>



<p class="has-luminous-vivid-amber-background-color has-background wp-block-paragraph">Thus, <code>if __name__ == '__main__':</code> evaluates to <code>True</code> if you use it in your main file (the one you run with <code>python main.py</code>). If you import it indirectly, it evaluates to <code>False</code>. </p>



<p class="has-luminous-vivid-amber-background-color has-background wp-block-paragraph">This is useful because you usually don&#8217;t want to run code with side effects when importing modules. </p>



<p class="wp-block-paragraph">You can play with the code in this minimal example:</p>



<iframe src="https://repl.it/@finxter/main?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="500px" frameborder="no"></iframe>



<p class="wp-block-paragraph"><em><strong>Exercise</strong>: Run the code shell. What&#8217;s the output? Now, create a new file and <code>import main</code>. What&#8217;s the output now?</em></p>



<hr class="wp-block-separator"/>



<p class="wp-block-paragraph"><em>If you are learning Python programming step by step, you would have bumped into the above piece of code snippet somewhere. Even if you have not, I am sure you will soon come across it, and this might feel like a jerk in your so far smooth journey of learning Python programming. I have been there. I was going through a book on Python programming when I first saw this piece of code, and I thought&#8212;wait a minute, did I miss anything on my way up to here? Then I went back, revising the last few pages to figure out what I missed, and this loop went on for a while before I finally sat down to face the demon, and honestly, I smiled when I figured it out, it is that simple. Maybe, we learn this way. We go back and forth, keep jumping, and then one day, the magic happens. The only thing that works is not giving up.&nbsp;</em></p>



<p class="wp-block-paragraph">Today I will try to make this understanding simple for you in a way that will hopefully bring a smile to your face if you have been in the loop of getting a hint of what it is and then keep forgetting.</p>



<p class="wp-block-paragraph">To understand what is&nbsp;<em><code>if __name__ == __main__</code></em>&nbsp;used for we will dive into some code examples first to understand what&nbsp;<em><code>__name__</code></em>&nbsp;and&nbsp;<em><code>__main__</code></em>&nbsp;are. Then we will cement the learning through another example. So be patient and go through the article carefully. The code snippets may look a little confusing but wait until we explain and see what is happening exactly.</p>



<h2 class="wp-block-heading">What are <code>__name__</code> and <code>__main__</code>?</h2>



<p class="wp-block-paragraph">Let us start with&nbsp;<em><code>__name__</code></em>. Simply put,&nbsp;<em><code>__name__</code></em>&nbsp;is a special variable that is built-in in Python.&nbsp;</p>



<p class="wp-block-paragraph">In Python, we can run code as a source file or, in other words, a python code that runs on its own (read &#8211; not imported from some separate Python source file). This sentence may be confusing at the moment, but let us explore this further.</p>



<p class="wp-block-paragraph">Look at the code snippet below. It is a simple python file with just one line:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(f" First Module's Name : {__name__}")</pre>



<p class="wp-block-paragraph">Simply put, we are asking Python to print the value that&nbsp;<em><code>__name__</code></em>&nbsp;variable has at this moment. Notice there is no import statement or even any other line of code above it.&nbsp;</p>



<p class="wp-block-paragraph"><img fetchpriority="high" decoding="async" src="https://lh6.googleusercontent.com/ixWY9y_OT8yQeaZlsf4iF5W_aX1v7XYOyDE9T3Qiaqc9EaTMdVPJO6X1GTh9a8KtRiYUil4_hWc8tQnlDPYHkyJe-QXiq9JK5IO1_llF3oV34H1UJbKOZEjIetlp3D4CBQFdekR3" width="500" height="175"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 1</strong></p>



<p class="wp-block-paragraph">Check the output in Figure 2 below. We run the above lines of code and find the output&nbsp;</p>



<p class="wp-block-paragraph"><strong><em>First Module&#8217;s Name : <code>__main__</code></em></strong></p>



<p class="wp-block-paragraph"><img decoding="async" src="https://lh4.googleusercontent.com/lN0eXeqZ_4mqr7x32m2fn09S0K3Hqz6tZ7TMZVVp0kT0LoKGWuU5xKcof002DXSA1_VlC1frmYhHB65n2VHV4XJTO5MBH51zIBS2jV7ULi_KgO19bXGx9AA30t-53r1dGJnZxD_b" width="624" height="136"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Figure 2</strong></p>



<p class="wp-block-paragraph">We import <code>module1.py</code> into <code>module2.py</code> and ask Python to return the second module&#8217;s name (second because this is the second python code we are running) stored in<code>&nbsp;<em>__name__</em></code><em>&nbsp;</em>variable again.</p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh6.googleusercontent.com/FDrm4f07_lWBC3GBgUhZhQFSqPzYKBzDs_V3TI5X1OrpEj0ZdZ49rZRGsmslIbmDkX4Lq5H4fj-5Xrpk2_3x7yaRHAkSqAWkjbjSZo-BaxX0UBlaek3qCHazEENu2ugbbzlsFOy5" width="542" height="144"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Figure 3</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># File: module2.py
import module1

print(f"Second Module's Name : {__name__}")</pre>



<p class="wp-block-paragraph">Interestingly, in Figure 5 below, we have the output&nbsp;</p>



<p class="wp-block-paragraph"><strong><em>First Module&#8217;s Name : module1</em></strong></p>



<p class="wp-block-paragraph"><strong><em>Second Module’s Name : __main__</em></strong></p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh4.googleusercontent.com/UOVArPdiVS-NiiG_biktjplo2fzh-Ls8xP1yvmn05aDwrC8hgzAJzmhtlqdDClEkfLdjHeqrF1CxQOViCbcIQDrWRJPeUUgksh899pCe8iZqJdKOqMavmLUwxXqktm7eOKVe0xGH" width="624" height="121"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Figure 4</strong></p>



<p class="wp-block-paragraph">The above information summarised simply can be explained as follows. Python starts executing the first line of code found in a Python file, but before it runs anything to show the output, Python defines some special variables.&nbsp;<em>__name__</em>&nbsp;is one such variable. When the source file is executed on its own i.e, not being imported from some other source code, the<em>&nbsp;__name__&nbsp;</em>variable is set to value&nbsp;<em>__main__</em>, and hence the output we got in Figure 3 was&nbsp;<em>First Module&#8217;s Name : __main__</em>. If you import the file from some other module (as in the code snippet from Figure 4), the value of&nbsp;<em>__name__</em>&nbsp;variable is set to the name of the module it is imported from. Hence the output in Figure 5.</p>



<p class="wp-block-paragraph">Now let us look at the sequence of execution.</p>



<ol class="wp-block-list"><li>module1.py in Figure 1 is executed,</li><li>Variable&nbsp;<em>__name__</em>&nbsp;is set to the value<em>&nbsp;__main__</em></li><li><em>__main__</em>&nbsp;module is executed, and the output is&nbsp;<em>First Module&#8217;s Name : __main__</em>&nbsp;</li><li>Module2.py in Figure 4 is executed,</li><li>Variable<em>&nbsp;__name__</em>&nbsp;is set to the value&nbsp;<em>module1</em></li><li><em>module1</em>&nbsp;is the block of code in module1.py which is executed, and the output is&nbsp;<em>First Module&#8217;s Name : module1&nbsp;</em></li><li>Next, we move on to line 3 in module2.py, the name value is reset to&nbsp;<em>__main__</em>, because this is a fresh piece of code in module2.py, and the output is&nbsp;<em>Second Module&#8217;s Name : __main__</em></li></ol>



<h2 class="wp-block-heading">Using if __name__ == ‘__main__’</h2>



<p class="wp-block-paragraph">But let&#8217;s think only concerning the code in module2.py. In the real world, with module2.py I would not like to print the output from module1.py rather only import some functionality and get output for the lines of code written in module2.py i.e.&nbsp;<em>Second Module&#8217;s Name : __main__</em></p>



<p class="wp-block-paragraph">But how can we do it? There has to be a way because this seems more logical that way. Refer to the code snippet below in Figure 6.</p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh5.googleusercontent.com/x3Io0KK_w7stlPNBv-boKOk0FrjsRfPZjbRCcFy7vGR_wx8NxJS1OYTMdsZPHHPmOBz2A5wy42EO-uv9_3xp5T56w1DVsYkwtKJM7bpX_hpFEVqFNODCjnfYnCjCr46sRPzvFe8y" width="576" height="195"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 5</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># File: module1.py
'''print(f"First Module's Name : {__name__}")'''


def main():
	print(f"First Module's Name : {__name__}")

if __name__ == '__main__':
	main()</pre>



<p class="wp-block-paragraph">So, we will define a function <code>main()</code>, and put the print statement from <code>module1.py</code> inside the main function. Now we use this small trick of using the statement&nbsp;<em><code>if __name__ == '__main__'</code></em>&nbsp;and put the main function inside this if statement. Now let&#8217;s look at the execution sequence of our program.</p>



<ol class="wp-block-list"><li>We have a <code>main()</code> function where we ask to print the name of the first module stored in&nbsp;the <code>__name__</code>&nbsp;variable. From the above example, we know the value stored in the&nbsp;<em><code>__name__</code></em>&nbsp;variable is <code>__main__</code>.</li><li>In line 7, we say if the value in&nbsp;<em><code>__name__</code></em>&nbsp;variable is equal to&nbsp;<em><code>__main__</code></em>, only then go ahead and execute the&nbsp;<code>main()</code> function.</li><li>Now running the modified module1.py, we can see the output as&nbsp;<em>First Module&#8217;s Name : <code>__main__</code></em>&nbsp;as expected. Refer to the first output in Figure 7&nbsp;</li><li>Now when we run module2.py, we get the output as&nbsp;<em>Second Module&#8217;s Name : <code>__main__</code></em></li></ol>



<p class="wp-block-paragraph">Notice how the output for module2.py has changed now. Although we have imported module1 in our module2.py program, the program in module1.py doesn&#8217;t run. Why? Because the value stored in the&nbsp;<em>__name__</em>&nbsp;variable at this moment is module1 and not&nbsp;<em>__main__</em>. So, using a main() function and<em>&nbsp;if __name__ == ‘__main__’&nbsp;</em>has put restrictions on execution of lines of code in module1.py as it would only execute module1.py only if&nbsp;<em>__name__ == ‘__main__’</em></p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh4.googleusercontent.com/jTHhckxRAMrjKxsfSHO-XPtSHW2CuHxGSsa4Y5BBYzqyUKDl7wnSx8kskggeLIKnmtp0qgSjCQEwlq1zskVomDaPWytxaf7rw6qY_iDtsBt9cWreOiFQm0WnMCviBX98Pui1ujWO" width="624" height="135"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 6</strong></p>



<h2 class="wp-block-heading">Putting it all into a real-world example</h2>



<p class="wp-block-paragraph">We now take a more generic example, which would make more sense of all we have discussed above.</p>



<ul class="wp-block-list"><li>Have a look at the below code snippet from <code>cubes.py</code> in Figure 8. In line 1 and line 2, we have a function <code>cube()</code>, which takes <code>num</code> as an argument. The function <code>cubes(num)</code> returns the cube of a given number.</li><li>On line 4, we use a for loop which iterates over a list of numbers from 0 to 9.</li><li>On line 5, we use the <code>cubes(num)</code> function with i as input to display the cube, as shown in figure 9. Simple enough.</li></ul>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh4.googleusercontent.com/TJOYJs0u31mM170mt0bfpn6MgdOyk9bFggO2E9X6hu-Ldszo7ObG0AhjMQxt9TagvCkt8LMD8QRZANjTP-5OslxLF1eaPtWWPxBKeSzWxLukj2nnuLH3cK_CbI9I-_kQdLdNnSig" width="570" height="155"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 7</strong></p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh6.googleusercontent.com/Sdn17AJmX7ITEwRRGWfTr7GGLzcuGL8z2RU0XVKhrOfjj8Qk4KpUgtD0SoOSNPVuoBIuyu3mX7WJZ9ic2BmjkmQtW7ySiYv59U9Gcsnr8bNG-xlToyChxmeJAWaU3jTaeIoucUC5" width="624" height="252"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 8</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def cube(num):
	return num ** 3

for i in range(10):
	print(f"{i} cubed is {cube(i)}")</pre>



<p class="wp-block-paragraph">In the code snippet from <code>modules.py</code> below in Figure 10, we import <code>cube(num)</code> function from <code>cubes.py</code> and try to print cube of 10 in line 3. Logically, we are trying to use the function <code>cube(num)</code>, which returns a cube of any given input number.</p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh4.googleusercontent.com/1PbrMx0TTjtcbhZARySffFG_hs1JVBp3aemQ2NXC2BXYsnf3JuzZxTTTK24qX9pv8jUd6LS7VcF34pTPmJM1K9zUp55QS0hGMEeYh7Iz3BZLnDomxP5gQ3oCVynhXi2S7Fr8Dx4e" width="423" height="130"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 9</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># File modules.py
from cubes import cube

print(cube(10))</pre>



<p class="wp-block-paragraph">However, look at the output below. We have the output of both the programs <code>cubes.py</code> and <code>modules.py</code>. This is not what we intended or wanted to do.&nbsp;</p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh4.googleusercontent.com/VwFC1f6oeN348PQVV4XSk-qP5lvjj4_Z1uGTi_Gb82_RC59pceAY0dwIH_n-MLkc5T7VWuKEQZCpe4Js_JIs4iP-tJFkNA7g4u7fKR7GVh7uAYY4dLpR7mIXUaTZnmug0OKdkoqM" width="624" height="256"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 10</strong></p>



<p class="wp-block-paragraph">Remember the explanation from above where we used&nbsp;<em>if __name__ == &#8216;__main__&#8217;</em>&nbsp;to limit the execution of code from <code>modules1.py</code>. Let us try and implement the same idea and see if that works here.</p>



<p class="wp-block-paragraph">In the code snippet from <code>cubesModified.py</code> in Figure 11, we put the for loop and the print statement from cubes.py in the main() function. And again, we use the statement&nbsp;<em>if __name__ == &#8216;__main__&#8217;</em>&nbsp;to execute code from cubesModified.py only when the value of __name__ variable equals to&nbsp;<em>__main__.</em></p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh3.googleusercontent.com/cuuWr6W-MXEGx-K_YYy6B7c5FLzJ0_mMEvkGkHX5HTUD7ShPA3wXuEh_Ussr0uCjub-BdvmOn_sJI3RLhLUqh65z-BL9sUDE1Yqe26Ptysca3UjrCe8VUOVkbtokdrLwicARm5Wn" width="624" height="331"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Figure 11</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># File: cubesModified.py
def cube(num):
	return num ** 3

def main():
	for i in range(10):
		print(f"{i} cubed is {cube(i)}")

''' effectively what this line of code is trying to say 
here is if name equals main or in other words, "if I am 
currently running this particular file (cubesModified.py)"
then run the main function.'''

if __name__ == "__main__":
	main()</pre>



<p class="wp-block-paragraph">We run <code>cubesModified.py</code> and get the output as below and per our expectation.</p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh5.googleusercontent.com/LyD3_e4XeP7mz2uEAvv4pyb0S5E2ub6dAD2TqmIDbYlfkjfBBWb5K1Q0-rvcpnrPiW1PX-Y0NlKIq8xBbCpdxqxSI68VVERaruTwQwYvU9x_pEOutos7wu4vjLYBtH28Q2EpRTBN" width="624" height="253"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Figure 12</strong></p>



<p class="wp-block-paragraph">However, now when we run <code>modulesModified.py</code> where we import <code>cube(num)</code> function from <code>cubesModified.py</code>, it only executes the code from our <code>modulesModified.py</code> as shown in Figure 15, and the output is 1000 because the value stored in the&nbsp;<em>__name__</em>&nbsp;variable in cubesModified and not&nbsp;<em>__main__.</em></p>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh3.googleusercontent.com/ybVD8QsySwt8XIMvSOqE3Tnq0z1LKRIyGDAXKt16z5UFXFm1SZQi_Skwmvgy5uQAFWoYEsYlbtuNL4t037bDuSPqmJchK3-3Dx0rkypfLKS3S19OV_9ry7nn8rENK-2U2Bq6nLbV" width="458" height="130"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Figure 13</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># File: cubesModified
from cubesModified import cube

print(cube(10))</pre>



<p class="wp-block-paragraph"><img loading="lazy" decoding="async" src="https://lh3.googleusercontent.com/vOoB4MSBk8XfxAKKyszUkeIoLitG5BcKz1GJH-PnK9KSt6GzmARGBeQ3fIMSk756acAObrUYWv__YCde0Rvc5Dlk1o31m3B2TY9u7t0qFsRTZ1m-M9IEMbMWWkafYkdvnnZucvv6" width="624" height="93"></p>



<p class="wp-block-paragraph"><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Figure 14</strong></p>



<p class="wp-block-paragraph">I hope this explanation helps you with a better understanding of what does&nbsp;<em>if __name__ == &#8216;__main__&#8217;</em>. Go ahead and play around with the code in the code editor and cement your understanding. Best of Luck!!</p>



<h2 class="wp-block-heading">Author</h2>



<p class="wp-block-paragraph">This article is contributed by Finxter <strong>Abhigyan Ojha</strong>. <a href="https://www.upwork.com/o/profiles/users/~01c5bce36c9a7b65d4/" target="_blank" rel="noreferrer noopener">You can find his Upwork profile here.</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Test Multiple Variables Against a Value in Python?</title>
		<link>https://blog.finxter.com/how-to-test-multiple-variables-against-a-value-in-python/</link>
		
		<dc:creator><![CDATA[Abhigyan Ojha]]></dc:creator>
		<pubDate>Mon, 22 Jun 2020 20:09:36 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=10018</guid>

					<description><![CDATA[To test multiple variables x, y, z against a value in Python, use the expression value in {x, y, z}. Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value. Here&#8217;s the code: Exercise: Add a fourth variable and run the modified ... <a title="How to Test Multiple Variables Against a Value in Python?" class="read-more" href="https://blog.finxter.com/how-to-test-multiple-variables-against-a-value-in-python/" aria-label="Read more about How to Test Multiple Variables Against a Value in Python?">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="has-luminous-vivid-amber-background-color has-background wp-block-paragraph">To test multiple variables <code>x</code>, <code>y</code>, <code>z</code> against a <code>value</code> in Python, use the expression <code>value in {x, y, z}</code>. Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value. </p>



<p class="wp-block-paragraph">Here&#8217;s the code:</p>



<iframe loading="lazy" src="https://trinket.io/embed/python/ca2260e046" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="500" frameborder="0"></iframe>



<p class="wp-block-paragraph"><em><strong>Exercise</strong>: Add a fourth variable and run the modified code!</em></p>



<hr class="wp-block-separator"/>



<p class="wp-block-paragraph">In this article, you&#8217;ll learn about an interesting problem in programming. Interesting because a quick glance could give us a feeling of this problem being simple. However, diving into it can help us learn some fundamentals about Boolean operators and some data types in a way we might not have thought about earlier. In fact, you could find yourself in this situation if you&#8217;re a beginner. We will try and explore some solutions to this problem using Python taking into consideration three approaches.</p>



<ul class="wp-block-list"><li>The Incorrect Approach</li><li>The Correct Approach</li><li>The Best Approach</li></ul>



<p class="wp-block-paragraph">Let&#8217;s see some code walkthrough to understand it.</p>



<h2 class="wp-block-heading">Doing It The Wrong Way &#8212; The Incorrect Approach</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="468" height="402" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-23.png" alt="" class="wp-image-10019" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-23.png 468w, https://blog.finxter.com/wp-content/uploads/2020/06/image-23-300x258.png 300w" sizes="auto, (max-width: 468px) 100vw, 468px" /></figure>



<p class="wp-block-paragraph">Let&#8217;s consider the above lines of code. We have three variables, x = 0, y = 1 and z = 3 and want to <a href="https://blog.finxter.com/print-a-list-of-list-in-python/" target="_blank" rel="noreferrer noopener" title="How to Print a List of List in Python?">print a list</a>, &#8220;list1&#8221; as output which checks at line 9, 11, 13 and 15 respectively, if either of x, y or z equals to 0, 1, 2, or 3 and append to our output list &#8211; list1, the values, c, d, e, and f based on the output condition.</p>



<p class="wp-block-paragraph">Pause for a moment, and observe. What should be the output for the above lines of code? Now run the above code snippet. If you were expecting the output &#8211; [‘c&#8217;, &#8216;d&#8217;, &#8216;f&#8217;], read along carefully.</p>



<p class="wp-block-paragraph">Let&#8217;s find out what is happening with our code. To understand it clearly, we must appreciate a few things first. The logical operators in <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener" title="Python Programming Tutorial [+Cheat Sheets]">Python </a>do not work<strong>&nbsp;</strong>in a way you would expect them to work in English. For instance, let us look at line 9 of the code snippet.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="258" height="37" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-24.png" alt="" class="wp-image-10020"/></figure>



<p class="wp-block-paragraph">From Python documentation (<a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="noreferrer noopener">Boolean operations</a>), the expression &#8220;x or y&#8221; first evaluates x<strong>.</strong>&nbsp;If x is true, its value is returned. Otherwise, y is evaluated, and the resulting value is returned.</p>



<p class="wp-block-paragraph">The second point to note here is about&nbsp;<a target="_blank" href="https://docs.python.org/3/reference/expressions.html#operator-summary" rel="noreferrer noopener">operator precedence</a>. The &#8220;or&#8221; operator has lower precedence than &#8220;==&#8221; operator, and hence equality is evaluated first.</p>



<p class="wp-block-paragraph">The line number 9 returns &#8220;1&#8221; (True) as output. So line number 9 and 10 simplifies to:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="266" height="63" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-25.png" alt="" class="wp-image-10021"/></figure>



<p class="wp-block-paragraph">Similarly, line 11, 13, and 15 each return 1 as output and hence (therefore) &#8220;d&#8221;, &#8220;e&#8221; and &#8220;f&#8221; gets appended to the list. Below code snippet shows the output for all the conditions individually:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="208" height="184" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-26.png" alt="" class="wp-image-10022"/></figure>



<p class="wp-block-paragraph">Operations and built-in functions that have a Boolean result always return 0 or False for a false and 1 or True for true, unless otherwise stated. Thus our final output to code snippet in fig1 returns [&#8220;c&#8221;, &#8220;d&#8221;, &#8220;e&#8221;, &#8220;f&#8221;]</p>



<h2 class="wp-block-heading">Doing It The Right Way &#8212; The Correct Approach</h2>



<p class="wp-block-paragraph">Now we build upon our mistakes above and look at a solution that should give us the expected output. Let&#8217;s modify the above code snippet a little and see how it changes the expected output:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="478" height="411" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-27.png" alt="" class="wp-image-10023" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-27.png 478w, https://blog.finxter.com/wp-content/uploads/2020/06/image-27-300x258.png 300w" sizes="auto, (max-width: 478px) 100vw, 478px" /></figure>



<p class="wp-block-paragraph">The difference is evident here as we use the statement “x == 0 or y == 0 or z == 0” instead of “x or y or z == 0”. In this case, each variable here i.e. x, y, z are checked for equivalence one after the other and if the condition satisfies, the corresponding alphabet i.e c, d, e, f is appended to our list 1 respectively. Run the above code and check the output.</p>



<h2 class="wp-block-heading">Doing It The Better Way: A Better Approach</h2>



<p class="wp-block-paragraph">With Python, we get myriads of <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">collection</a>/sequence data types and some in-built keywords that we can work with. The original idea of different collection/sequence data types and the keywords available for our use is to simplify how we can create a collection/sequence of data and access them based on the problem statement we are dealing with. We will check two data structures &#8211; Tuples and <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Sets – with Harry Potter Examples">Sets</a>, which bring in a good use case for the scenario that we are dealing with.</p>



<p class="wp-block-paragraph">The &#8220;<a href="https://blog.finxter.com/check-if-a-list-contains-an-element/" target="_blank" rel="noreferrer noopener" title="The Most Pythonic Way to Check If a List Contains an Element">in</a>&#8221; keyword can be used along with sequences like lists, sets, and tuples. It returns True or False based on whether the operand on the left is found or not in the sequence. Let&#8217;s check out the code snippet below:</p>



<h3 class="wp-block-heading">Using Tuples to Do it Better:</h3>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="589" height="412" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-28.png" alt="" class="wp-image-10024" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-28.png 589w, https://blog.finxter.com/wp-content/uploads/2020/06/image-28-300x210.png 300w" sizes="auto, (max-width: 589px) 100vw, 589px" /></figure>



<p class="wp-block-paragraph">In this case, we define variables x, y, and z and then check for the specific value <a href="https://blog.finxter.com/how-to-test-multiple-variables-against-a-value-in-python/" target="_blank" rel="noreferrer noopener" title="How to Test Multiple Variables Against a Value in Python?">membership </a>with tuples in the above case. Hence, on line 9 we check, 0 to be in the tuple (0, 1, 3), which is a membership check, and if the condition is True, we append alphabet &#8220;c&#8221; to our list1. Then the membership check is done for values 1, 2, and 3, respectively, and based on whether the condition is True or False, the respective alphabet values of &#8220;c&#8221;, &#8220;d&#8221;, &#8220;e&#8221;, &#8220;f&#8221; are appended to our list1.</p>



<p class="wp-block-paragraph">To clarify further, on line 9 we get the output as True and hence &#8220;c&#8221; is appended to list1 whereas, on line 13, where we check for membership of 2 in the tuple (0, 1, 3), the condition is False and hence &#8220;e&#8221; is not appended to list1.</p>



<h3 class="wp-block-heading">Using Sets to Do it Better:</h3>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="569" height="396" src="https://blog.finxter.com/wp-content/uploads/2020/06/image-29.png" alt="" class="wp-image-10025" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/image-29.png 569w, https://blog.finxter.com/wp-content/uploads/2020/06/image-29-300x209.png 300w" sizes="auto, (max-width: 569px) 100vw, 569px" /></figure>



<p class="wp-block-paragraph">Here&#8217;s the code for easier copy&amp;pasting:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 0
y = 1
z = 3

list1 = []

if 0 in {x, y, z}:
    list1.append('c')
if 0 in {x, y, z}:
    list1.append('d')
if 0 in {x, y, z}:
    list1.append('e')
if 0 in {x, y, z}:
    list1.append('f')

print(list1)
# ['c', 'd', 'e', 'f']</pre>



<p class="wp-block-paragraph">This solution is the same as the above solution with Tuples. The only difference is the data structure that we use here. With this solution we perform membership checks using Sets and based on the condition being True or False, appending the respective alphabet &#8220;c&#8221;, &#8220;d&#8221;, &#8220;e&#8221;, &#8220;f&#8221; to list1.</p>



<p class="wp-block-paragraph">I hope this explanation helps. Try and get your hands dirty running the above code snippets, and you will have a better understanding by the time you are done.</p>



<h2 class="wp-block-heading">Author</h2>



<p class="wp-block-paragraph">This article is contributed by Finxter Abhigyan Ojha. <a href="https://www.upwork.com/o/profiles/users/~01c5bce36c9a7b65d4/" target="_blank" rel="noreferrer noopener" title="https://www.upwork.com/o/profiles/users/~01c5bce36c9a7b65d4/">You can find his Upwork profile here.</a></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-10-26 13:17:11 by W3 Total Cache
-->