<?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>Math Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/math/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/math/</link>
	<description></description>
	<lastBuildDate>Wed, 01 May 2024 14:37:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Math Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/math/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Calculate CAGR in Google Sheets</title>
		<link>https://blog.finxter.com/how-to-calculate-cagr-in-google-sheets/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 01 May 2024 14:37:16 +0000</pubDate>
				<category><![CDATA[Excel]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Spreadsheet]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670227</guid>

					<description><![CDATA[<p>The Compound Annual Growth Rate (CAGR) is a useful measure to understand the growth of an investment over time. How do I calculate CAGR in Google Sheets? 👇 To calculate CAGR in Google Sheets, use the following formula: (Ending Value/Starting Value)˄(1/Number of Years) - 1 Step 1: Input Your Start and End Values In column ... <a title="How to Calculate CAGR in Google Sheets" class="read-more" href="https://blog.finxter.com/how-to-calculate-cagr-in-google-sheets/" aria-label="Read more about How to Calculate CAGR in Google Sheets">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-cagr-in-google-sheets/">How to Calculate CAGR in Google Sheets</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The <strong>Compound Annual Growth Rate (CAGR)</strong> is a useful measure to understand the growth of an investment over time. How do I calculate CAGR in Google Sheets? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="has-global-color-8-background-color has-background wp-block-paragraph">To calculate CAGR in Google Sheets, use the following formula: <br><code><strong>(Ending Value/Starting Value)˄(1/Number of Years) - 1</strong></code></p>



<h2 class="wp-block-heading">Step 1: Input Your Start and End Values</h2>



<p class="has-base-2-background-color has-background wp-block-paragraph">In column A, input the periods over which you want to calculate the CAGR of your investment. In column B, input your investment value at the end of each period.</p>



<p class="wp-block-paragraph">For example: </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="712" height="493" src="https://blog.finxter.com/wp-content/uploads/2024/05/image-1.png" alt="" class="wp-image-1670229" srcset="https://blog.finxter.com/wp-content/uploads/2024/05/image-1.png 712w, https://blog.finxter.com/wp-content/uploads/2024/05/image-1-300x208.png 300w" sizes="(max-width: 712px) 100vw, 712px" /></figure>
</div>


<h2 class="wp-block-heading">Step 2: Use the CAGR Formula</h2>



<p class="wp-block-paragraph">The CAGR formula <code><strong>(Ending Value/Starting Value)˄(1/Number of Years) - 1</strong></code> calculates the rate at which an investment grows over time. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="630" height="535" src="https://blog.finxter.com/wp-content/uploads/2024/05/image-2.png" alt="" class="wp-image-1670230" srcset="https://blog.finxter.com/wp-content/uploads/2024/05/image-2.png 630w, https://blog.finxter.com/wp-content/uploads/2024/05/image-2-300x255.png 300w" sizes="(max-width: 630px) 100vw, 630px" /></figure>
</div>


<p class="wp-block-paragraph">Specifically, I used this formula to calculate the compound annual growth rate over <code>3-1=2</code> years:</p>



<p class="wp-block-paragraph"><strong><code>=(B4/B2)^(1/(A4-A2))-1</code></strong></p>



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



<ul class="wp-block-list">
<li><code>B4</code> is the cell with the ending value of your investment.</li>



<li><code>B2</code> is the cell with the starting value of your investment.</li>



<li><code>A4</code> and <code>A2</code> are the cells with the end and start periods, respectively. You can also put in the number of years right away.</li>
</ul>



<h2 class="wp-block-heading">Step 3: Format as Percentage</h2>



<p class="wp-block-paragraph">After entering the formula, the result is not yet displayed as a percentage. To format it, click on the CAGR result cell and click <code>Format > Number > Percent</code>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="387" src="https://blog.finxter.com/wp-content/uploads/2024/05/image-3-1024x387.png" alt="" class="wp-image-1670231" srcset="https://blog.finxter.com/wp-content/uploads/2024/05/image-3-1024x387.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/05/image-3-300x114.png 300w, https://blog.finxter.com/wp-content/uploads/2024/05/image-3-768x291.png 768w, https://blog.finxter.com/wp-content/uploads/2024/05/image-3-1536x581.png 1536w, https://blog.finxter.com/wp-content/uploads/2024/05/image-3.png 1562w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The resulting cell looks like this:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="616" height="563" src="https://blog.finxter.com/wp-content/uploads/2024/05/image-4.png" alt="" class="wp-image-1670232" srcset="https://blog.finxter.com/wp-content/uploads/2024/05/image-4.png 616w, https://blog.finxter.com/wp-content/uploads/2024/05/image-4-300x274.png 300w" sizes="auto, (max-width: 616px) 100vw, 616px" /></figure>
</div>


<p class="wp-block-paragraph">Voilà. You&#8217;ve successfully calculated the CAGR in your Google spreadsheet and formatted it as a percentage value. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" />  </p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-cagr-in-google-sheets/">How to Calculate CAGR in Google Sheets</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Check If an Integer is in Range</title>
		<link>https://blog.finxter.com/python-check-if-an-integer-is-in-range/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 24 Apr 2024 11:30:45 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670127</guid>

					<description><![CDATA[<p>Problem Formulation You&#8217;re given a number. How do you check if the number lies between two numbers, i.e., a numeric range? When you check if a number lies between two other numbers it returns a boolean that determines if the number is greater than or equal to the minimum number and also less than or ... <a title="Python Check If an Integer is in Range" class="read-more" href="https://blog.finxter.com/python-check-if-an-integer-is-in-range/" aria-label="Read more about Python Check If an Integer is in Range">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-check-if-an-integer-is-in-range/">Python Check If an Integer is in Range</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"><strong>Problem Formulation</strong></h2>



<p class="wp-block-paragraph"><strong>You&#8217;re given a number. How do you check if the number lies between two numbers, i.e., a numeric <em>range</em>?</strong></p>



<p class="wp-block-paragraph">When you check if a number lies between two other numbers it returns a boolean that determines if the number is greater than or equal to the minimum number and also less than or equal to the maximum number. </p>



<p class="wp-block-paragraph">Here&#8217;s an example that demonstrates the problem:</p>



<pre class="wp-block-preformatted"><strong>Example 1:</strong> Is 25 between 15 and 35?<br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Output: </strong><code>True</code><br><br><strong>Example 2</strong>: Is 0.5 between 1 and 5?<br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Output: </strong><code>False</code><br><br><strong>Example 3</strong>: Is 10 between 10 and 20?<br><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Output: </strong><code>True</code></pre>



<p class="wp-block-paragraph">Let&#8217;s dive into the trivial solution next &#8212; can you figure out why this is not optimal? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Method 1: Using Python&#8217;s <a href="https://blog.finxter.com/python-membership-in-operator/" target="_blank" rel="noreferrer noopener"><code>in</code></a> Keyword with the <code>range()</code> Function</h2>



<p class="has-global-color-8-background-color has-background wp-block-paragraph">You can use the <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290">range()</a></code> function to determine the upper and lower limits/numbers by feeding in the start and stop values within it. Now, to check if the number lies between the two numbers you can simply use the <strong><code>in</code></strong> keyword to check it. So, if the number lies in the specified range then the output will be &#8220;<em><code>True</code></em>&#8221; else &#8220;<em><code>False</code></em>&#8220;.</p>



<p class="wp-block-paragraph">Here&#8217;s a simple example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(25 in range(15, 36))  # True
print(0.5 in range(0, 2))  # False
print(10 in range(10, 20))  # True</pre>



<p class="wp-block-paragraph">Note that the stop value within the <code>range()</code> function should always be one greater than the given maximum number/upper limit since the range of values taken into account by the <code>range</code> function always lies between start to stop-1. Read more about the <code>range()</code> function here:</p>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong><a href="https://blog.finxter.com/python-range-function/" target="_blank" rel="noreferrer noopener">Python <code>range()</code> Function — A Helpful Illustrated Guide</a></strong></p>



<p class="has-base-2-background-color has-background wp-block-paragraph"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Info:</strong> Python’s “<code>in</code>” operator is a reserved <a href="https://blog.finxter.com/python-cheat-sheet/" target="_blank" rel="noreferrer noopener">keyword </a>to test <a href="https://blog.finxter.com/python-membership-in-operator/" data-type="post" data-id="34005">membership</a> of the left operand in the right operand. The right operand, therefore, needs to be a collection type.<br><br>For example, the expression <code>x in my_list checks</code> if object <code>x</code> exists in the <code>my_list</code> collection, so that at least one element <code>y</code> exists in <code>my_list</code> for that <code>x == y</code> holds. <br><br>You can check membership using the “<code>in</code>” operator in collections such as <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">lists</a>, <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">sets</a>, <a href="https://blog.finxter.com/python-string-methods/" target="_blank" rel="noreferrer noopener">strings</a>, and <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank" rel="noreferrer noopener">tuples</a>.</p>



<figure class="wp-block-image size-full is-style-default"><a href="https://blog.finxter.com/python-membership-in-operator/"><img loading="lazy" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/09/image-71.png" alt="" class="wp-image-699814" srcset="https://blog.finxter.com/wp-content/uploads/2022/09/image-71.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/09/image-71-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2022/09/image-71-768x432.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="wp-block-paragraph">This is not the optimal method because you need to create a whole range of values. Its runtime complexity depends on the size of the range which is really bad when compared to the better alternative: </p>



<h2 class="wp-block-heading">Method 2: Use Comparison Operators</h2>



<p class="wp-block-paragraph">Python <a href="https://blog.finxter.com/python-comparison-operators/" data-type="post" data-id="33245">comparison operators</a> can compare numerical values such as integers and floats in Python. The operators are: </p>



<ul class="wp-block-list">
<li>equal to ( == ), </li>



<li>not equal to ( != ), </li>



<li>greater than ( > ), </li>



<li>less than ( &lt; ), </li>



<li>less than or equal to ( &lt;= ), and </li>



<li>greater than or equal to ( >= ).</li>
</ul>



<p class="has-global-color-8-background-color has-background wp-block-paragraph">You can use the &lt;= and the >= operators to check if a number lies between the upper limit (maximum number) and lower limit(minimum number).</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(15 &lt;= 25 &lt; 35)  # True
print(1 &lt;= 0.5 &lt; 5)  # False
print(10 &lt;= 10 &lt; 20)  # True</pre>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/check-if-a-number-is-between-two-numbers-in-python/">Check If a Number is Between Two Numbers in Python</a></p>



<h2 class="wp-block-heading">Method 3: Using &#8220;and&#8221; Keyword with Comparison Operators</h2>



<p class="wp-block-paragraph">An alternative way of checking whether a value lies in a range of values is quite similar to the one used above. The only difference, in this case, is to use the <code>and</code> keyword in between the two comparison operators as shown in the solution below.</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(15 &lt;= 25 and 25 &lt;= 35)  # True
print(1 &lt;= 0.5 and 0.5 &lt;= 5)  # False
print(10 &lt;= 10 and 10 &lt;= 20)  # True</pre>



<p class="wp-block-paragraph">Some of you might be thinking why use an extra keyword when the solution given before is more readable than this one! Well! That&#8217;s true. The first syntax is more readable but this solution runs faster. Let&#8217;s compare the two solutions using <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-measure-elapsed-time-in-python/#Method_4_Using_timeit_Module" target="_blank">timeit</a></strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="atomic" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">~$ python3 -m timeit "10 &lt;= 20 and 20 &lt;= 30"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "10 &lt;= 20 &lt;= 30"
10000000 loops, best of 3: 0.0396 usec per loop</pre>



<h2 class="wp-block-heading">Quick Overview</h2>



<p class="wp-block-paragraph">Here are various ways to check if a Python integer, <code>x</code>, falls within a specific range:</p>



<ul class="wp-block-list">
<li><strong>Direct Comparison</strong>: <code>if low &lt;= x &lt;= high</code> for inclusive or <code>if low &lt; x &lt; high</code> for exclusive.</li>



<li><strong>Using <code>range()</code></strong>: <code>if x in range(low, high+1)</code> for inclusive or <code>if x in range(low, high)</code> for exclusive.</li>



<li><strong>Boolean Operators</strong>: <code>if x >= low and x &lt;= high</code> for inclusive or <code>if x > low and x &lt; high</code> for exclusive.</li>



<li><strong>Custom Function</strong>: Define a function like <code>def in_range(x, low, high): return low &lt;= x &lt;= high</code> for easy reuse.</li>



<li><strong>Using <code>math</code> module</strong>: <code>import math; if math.isclose(x, low, abs_tol=1e-9) or low &lt; x &lt; high</code> for near lower bound inclusivity.</li>



<li><strong>List Comprehension</strong>: <code>if x in [i for i in range(low, high+1)]</code> offers explicit control over range elements.</li>
</ul>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/list-comprehension/">List Comprehension in Python — A Helpful Illustrated Guide</a></p>
<p>The post <a href="https://blog.finxter.com/python-check-if-an-integer-is-in-range/">Python Check If an Integer is in Range</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Fit a Curve to Power-law Distributed Data in Python</title>
		<link>https://blog.finxter.com/fitting-a-curve-to-power-law-distributed-data-a-python-tutorial/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 31 Mar 2024 07:21:01 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SciPy]]></category>
		<category><![CDATA[Statistics]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1669961</guid>

					<description><![CDATA[<p>In this tutorial, you&#8217;ll learn how to generate synthetic data that follows a power-law distribution, plot its cumulative distribution function (CDF), and fit a power-law curve to this CDF using Python. This process is useful for analyzing datasets that follow power-law distributions, which are common in natural and social phenomena. Prerequisites Ensure you have Python ... <a title="How to Fit a Curve to Power-law Distributed Data in Python" class="read-more" href="https://blog.finxter.com/fitting-a-curve-to-power-law-distributed-data-a-python-tutorial/" aria-label="Read more about How to Fit a Curve to Power-law Distributed Data in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/fitting-a-curve-to-power-law-distributed-data-a-python-tutorial/">How to Fit a Curve to Power-law Distributed Data in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this tutorial, you&#8217;ll learn how to generate synthetic data that follows a power-law distribution, plot its cumulative distribution function (CDF), and fit a power-law curve to this CDF using Python. This process is useful for analyzing datasets that follow power-law distributions, which are common in natural and social phenomena.</p>



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



<p class="wp-block-paragraph">Ensure you have Python installed, along with the <code>numpy</code>, <code>matplotlib</code>, and <code>scipy</code> libraries. If not, you can install them using pip:</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="">pip install numpy matplotlib scipy</pre>



<h2 class="wp-block-heading">Step 1: Generate Power-law Distributed Data</h2>



<p class="wp-block-paragraph">First, we&#8217;ll generate a dataset that follows a power-law distribution using <code>numpy</code>.</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="">import numpy as np

# Parameters
alpha = 3.0  # Exponent of the distribution
size = 1000  # Number of data points

# Generate power-law distributed data
data = np.random.power(a=alpha, size=size)</pre>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a></p>



<p class="wp-block-paragraph">The data looks like this:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="921" height="594" src="https://blog.finxter.com/wp-content/uploads/2024/03/image-58.png" alt="" class="wp-image-1669962" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/image-58.png 921w, https://blog.finxter.com/wp-content/uploads/2024/03/image-58-300x193.png 300w, https://blog.finxter.com/wp-content/uploads/2024/03/image-58-768x495.png 768w" sizes="auto, (max-width: 921px) 100vw, 921px" /></figure>
</div>


<p class="wp-block-paragraph">Let&#8217;s make some sense out of it and plot it in 2D space: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">Step 2: Plot the Cumulative Distribution Function (CDF)</h2>



<p class="wp-block-paragraph">Next, we&#8217;ll plot the CDF of the generated data on a log-log scale to visualize its power-law distribution.</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="">import matplotlib.pyplot as plt

# Prepare data for the CDF plot
sorted_data = np.sort(data)
yvals = np.arange(1, len(sorted_data) + 1) / float(len(sorted_data))

# Plot the CDF
plt.plot(sorted_data, yvals, marker='.', linestyle='none', color='blue')
plt.xlabel('Value')
plt.ylabel('Cumulative Frequency')
plt.title('CDF of Power-law Distributed Data')
plt.xscale('log')
plt.yscale('log')
plt.grid(True, which="both", ls="--")
plt.show()</pre>



<p class="wp-block-paragraph">The plot:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="578" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-5.png" alt="" class="wp-image-1669964" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-5.png 578w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-5-300x238.png 300w" sizes="auto, (max-width: 578px) 100vw, 578px" /></figure>
</div>


<h2 class="wp-block-heading">Step 3: Fit a Power-law Curve to the CDF</h2>



<p class="wp-block-paragraph">To understand the underlying power-law distribution better, we fit a curve to the CDF using the <code>curve_fit</code> function from <code>scipy.optimize</code>.</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="">from scipy.optimize import curve_fit

# Power-law fitting function
def power_law_fit(x, a, b):
    return a * np.power(x, b)

# Fit the power-law curve
params, covariance = curve_fit(power_law_fit, sorted_data, yvals)

# Generate fitted values
fitted_yvals = power_law_fit(sorted_data, *params)</pre>



<h2 class="wp-block-heading">Step 4: Plot the Fitted Curve with the CDF</h2>



<p class="wp-block-paragraph">Finally, we&#8217;ll overlay the fitted power-law curve on the original CDF plot to visually assess the fit.</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=""># Plot the original CDF and the fitted power-law curve
plt.plot(sorted_data, yvals, marker='.', linestyle='none', color='blue', label='Original Data')
plt.plot(sorted_data, fitted_yvals, 'r-', label='Fitted Power-law Curve')
plt.xlabel('Value')
plt.ylabel('Cumulative Frequency')
plt.title('CDF with Fitted Power-law Curve')
plt.xscale('log')
plt.yscale('log')
plt.grid(True, which="both", ls="--")
plt.legend()
plt.show()</pre>



<p class="wp-block-paragraph">Voilà! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="578" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-6.png" alt="" class="wp-image-1669965" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-6.png 578w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-6-300x238.png 300w" sizes="auto, (max-width: 578px) 100vw, 578px" /></figure>
</div>


<p class="wp-block-paragraph">This visualization helps in assessing the accuracy of the power-law model in describing the distribution of the data. </p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">Recommended article: </p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="664" src="https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1536x996-1-1024x664.png" alt="" class="wp-image-1669966" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1536x996-1-1024x664.png 1024w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1536x996-1-300x195.png 300w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1536x996-1-768x498.png 768w, https://blog.finxter.com/wp-content/uploads/2024/03/8a9b7881-bc2d-4100-80df-5da295e73602-1536x996-1.png 1536w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/visualizing-wealth-plotting-the-net-worth-of-the-worlds-richest-in-log-log-space/">Visualizing Wealth: Plotting the Net Worth of the World’s Richest in Log/Log Space</a></p>
<p>The post <a href="https://blog.finxter.com/fitting-a-curve-to-power-law-distributed-data-a-python-tutorial/">How to Fit a Curve to Power-law Distributed Data in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</title>
		<link>https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 30 Mar 2024 17:27:56 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Statistics]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1669952</guid>

					<description><![CDATA[<p>To generate random samples from a power-law distribution in Python, use the numpy library for numerical operations and matplotlib for visualization. Here&#8217;s a minimal code example to generate and visualize random samples from a power-law distribution: First, we import the necessary libraries: numpy for generating the power-law distributed samples and matplotlib.pyplot for plotting. The a ... <a title="How to Generate and Plot Random Samples from a Power-Law Distribution in Python?" class="read-more" href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/" aria-label="Read more about How to Generate and Plot Random Samples from a Power-Law Distribution in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">To generate random samples from a <a href="https://blog.finxter.com/5-best-ways-to-create-logarithmic-y-axis-bins-in-python/" data-type="post" data-id="1664973">power-law distribution</a> in Python, use the <code>numpy</code> library for numerical operations and <code>matplotlib</code> for visualization. </p>



<ul class="wp-block-list">
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4f1.png" alt="📱" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Computation</strong>: Specifically, you can use the <code>numpy.random.power</code> function, which draws samples from a power-law distribution with a specific exponent. </li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Visualization</strong>: After generating the samples, it&#8217;s beneficial to visualize them in a log-log space to observe the characteristic straight-line behavior of power-law distributions. This visualization helps in understanding the distribution&#8217;s properties and confirming its power-law nature.</li>
</ul>



<p class="wp-block-paragraph">Here&#8217;s a minimal code example to generate and visualize random samples from a power-law distribution:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt

# Parameters
a = 5  # Shape parameter
samples = 10000  # Number of samples

# Generate random samples
data = np.random.power(a, samples)

# Visualization in log-log space
counts, bins = np.histogram(data, bins=50)
bins_center = (bins[:-1] + bins[1:]) / 2
plt.loglog(bins_center, counts, marker='o', linestyle='none')

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Power-law distribution in log-log space')
plt.show()</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="570" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3.png" alt="" class="wp-image-1669956" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3.png 570w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-3-300x242.png 300w" sizes="auto, (max-width: 570px) 100vw, 570px" /></figure>
</div>


<p class="wp-block-paragraph">First, we import the necessary libraries: <code>numpy</code> for generating the power-law distributed samples and <code>matplotlib.pyplot</code> for plotting.</p>



<p class="wp-block-paragraph">The <code>a</code> parameter is the shape parameter of the power-law distribution, controlling the steepness of the distribution. The <code>samples</code> variable defines how many <a href="https://blog.finxter.com/5-secure-ways-to-generate-random-numbers-in-python/" data-type="post" data-id="1668905">random values we want to generate</a>.</p>



<p class="wp-block-paragraph"><code>np.random.power(a, samples)</code> generates an array of samples drawn from a power-law distribution with the shape parameter <code>a</code>.</p>



<p class="wp-block-paragraph">To visualize the distribution in log-log space, we first compute the histogram of the data using <code>np.histogram</code>, which returns the counts and the bin edges.</p>



<p class="wp-block-paragraph">We calculate the center of each bin for plotting purposes (<code>bins_center</code>) and then plot the histogram using <code>plt.loglog</code> to create a log-log plot. This is crucial for visualizing power-law distributions as they appear as straight lines in log-log plots.</p>



<p class="wp-block-paragraph">Finally, we label the axes and show the plot with <code>plt.show()</code>.</p>



<h2 class="wp-block-heading">Creating Power Law Distribution Without Library Such As NumPy</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="570" height="459" src="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4.png" alt="" class="wp-image-1669957" srcset="https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4.png 570w, https://blog.finxter.com/wp-content/uploads/2024/03/Untitled-4-300x242.png 300w" sizes="auto, (max-width: 570px) 100vw, 570px" /></figure>
</div>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">To create samples from a power-law distribution without a library, we use the inverse transform sampling method, where we <a href="https://blog.finxter.com/5-best-ways-to-generate-pseudo-random-numbers-in-python/" data-type="post" data-id="1669034">generate uniform random samples</a> and apply the inverse of the distribution&#8217;s cumulative distribution function (CDF) to these samples. This approach mathematically transforms uniformly distributed random numbers into numbers that follow the desired power-law distribution, based on the power-law&#8217;s specific characteristics and parameters.</p>



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



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random
import matplotlib.pyplot as plt

def generate_power_law_samples(alpha, size=1000, xmin=1):
    """Generate samples from a power-law distribution using the inverse transform sampling method."""
    samples = []
    for _ in range(size):
        u = random.random()  # Uniform random sample from 0 to 1
        x = xmin * (1 - u) ** (-1 / (alpha - 1))
        samples.append(x)
    return samples

def plot_rank_frequency(samples):
    """Plot samples in log-log space using rank-frequency."""
    # Sort samples in descending order
    sorted_samples = sorted(samples, reverse=True)
    # Generate ranks
    ranks = range(1, len(sorted_samples) + 1)
    # Plotting
    plt.loglog(ranks, sorted_samples, marker='o', linestyle='none')
    plt.xlabel('Rank')
    plt.ylabel('Sample Value')
    plt.title('Power-law distribution rank-frequency plot in log-log space')
    plt.show()

# Generate samples
alpha = 2.5  # Shape parameter of the power-law distribution
samples = generate_power_law_samples(alpha, 10000)

# Plot rank-frequency in log-log space
plot_rank_frequency(samples)
</pre>



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



<p class="wp-block-paragraph">This code generates samples from a power-law distribution using the <code>generate_power_law_samples</code> function, as before.</p>



<p class="wp-block-paragraph">The <code>plot_rank_frequency</code> function sorts the samples in descending order and then generates their ranks. In a rank-frequency plot, each point&#8217;s x-coordinate is its rank (i.e., its position in the sorted list), and its y-coordinate is the sample value itself.</p>



<p class="wp-block-paragraph">We plot these points in a log-log space using <code>plt.loglog()</code>. This type of plot is useful for observing the power-law behavior of the distribution, where a linear relationship in log-log space indicates a power-law distribution.</p>



<p class="wp-block-paragraph">The plot&#8217;s x-axis represents the ranks of the samples, and the y-axis represents the sample values, both on logarithmic scales. This visualization technique is effective for highlighting the characteristics of power-law distributions.</p>
<p>The post <a href="https://blog.finxter.com/how-to-generate-and-plot-random-samples-from-a-power-law-distribution-in-python/">How to Generate and Plot Random Samples from a Power-Law Distribution in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>CAGR Calculator</title>
		<link>https://blog.finxter.com/compound-annual-growth-rate-cagr-calculator/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 20 Mar 2024 12:41:09 +0000</pubDate>
				<category><![CDATA[Calculators]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Investment]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Tool]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1669803</guid>

					<description><![CDATA[<p>Calculate the compound annual growth rate (CAGR) right here: 👇 Calculate CAGR 📈 The compound annual growth rate of your investment is: 💡 The Compound Annual Growth Rate (CAGR) is a useful measure that provides a smoothed annual rate of return of an investment, asset, or business metric over a specified time period. Unlike simple ... <a title="CAGR Calculator" class="read-more" href="https://blog.finxter.com/compound-annual-growth-rate-cagr-calculator/" aria-label="Read more about CAGR Calculator">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/compound-annual-growth-rate-cagr-calculator/">CAGR Calculator</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Calculate the compound annual growth rate (CAGR) right here: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<div id="cagr-calculator">
  <style>
    #cagr-calculator {
      font-family: Arial, sans-serif;
    }
    #cagr-calculator input[type="number"] {
      margin: 5px 0;
      padding: 8px;
      width: calc(100% - 16px);
    }
    #cagr-result {
      font-size: 24px;
      margin-top: 10px;
    }
    .positive {
      color: green;
    }
    .negative {
      color: red;
    }
  </style>
  <input type="number" id="initialValue" placeholder="Starting Value" />
  <input type="number" id="endValue" placeholder="Ending Value" />
  <input type="number" id="years" placeholder="Years" />
  <button onclick="calculateCAGR()">Calculate CAGR</button>
  <br><br>
  <div><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The compound annual growth rate of your investment is:</div>
  <div id="cagr-result"></div>
  <br><br>

  <script>
    function calculateCAGR() {
      var initialValue = document.getElementById('initialValue').value;
      var endValue = document.getElementById('endValue').value;
      var years = document.getElementById('years').value;

      var cagr = (Math.pow(endValue / initialValue, 1 / years) - 1) * 100;

      var resultElement = document.getElementById('cagr-result');
      resultElement.innerText = `${cagr >= 0 ? '+' : '-'}${Math.abs(cagr).toFixed(2)}%`;
      resultElement.className = cagr >= 0 ? 'positive' : 'negative';
    }
  </script>
</div>



<p class="has-base-2-background-color has-background wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <strong>Compound Annual Growth Rate (CAGR)</strong> is a useful measure that provides a smoothed annual rate of return of an investment, asset, or business metric over a specified time period. Unlike simple percentage calculations, CAGR offers a geometric progression rate, effectively showing what an investment would have yielded per annum had it grown at a steady rate.</p>



<p class="wp-block-paragraph">CAGR is particularly valuable for comparing the growth rates of investments of varying sizes over different time periods. It&#8217;s widely used in the finance and investment sectors to gauge the performance of stocks, funds, assets, or even entire portfolios. Additionally, businesses often use CAGR to evaluate the growth of different segments or the company as a whole over multiple years.</p>



<p class="wp-block-paragraph">The formula used in the calculator for computing the CAGR is:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="237" height="49" src="https://blog.finxter.com/wp-content/uploads/2024/03/image-25.png" alt="" class="wp-image-1669805"/></figure>
</div>


<p class="wp-block-paragraph">In this formula:</p>



<ul class="wp-block-list">
<li><strong>End Value</strong> represents the final value of the investment or asset at the end of the period.</li>



<li><strong>Initial Value</strong> is the value of the investment or asset at the beginning of the period.</li>



<li><strong>Years</strong> is the duration of the period in years over which the investment grows from its initial to its final value.</li>
</ul>



<p class="wp-block-paragraph">The result is expressed as a percentage, indicating the average annual rate at which the investment has grown over the specified period. If the CAGR is positive, it indicates growth, while a negative CAGR indicates a decline in value over the period.</p>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://blog.finxter.com/financial-freedom-calculator/" data-type="post" data-id="1669784">Financial Freedom Calculator</a></p>
<p>The post <a href="https://blog.finxter.com/compound-annual-growth-rate-cagr-calculator/">CAGR Calculator</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>5 Best Ways to Paste Copied Text From the Keyboard in Python</title>
		<link>https://blog.finxter.com/5-best-ways-to-paste-copied-text-from-the-keyboard-in-python/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sat, 02 Mar 2024 21:06:24 +0000</pubDate>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1660728</guid>

					<description><![CDATA[<p>💡 Problem Formulation: How does one paste a string that has been copied to the clipboard into their Python program? For instance, if a user has copied &#8220;Hello, World!&#8221; to the clipboard, how can the program retrieve that text and use it within the Python script? Method 1: Using the Pyperclip Module The Pyperclip module ... <a title="5 Best Ways to Paste Copied Text From the Keyboard in Python" class="read-more" href="https://blog.finxter.com/5-best-ways-to-paste-copied-text-from-the-keyboard-in-python/" aria-label="Read more about 5 Best Ways to Paste Copied Text From the Keyboard in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-paste-copied-text-from-the-keyboard-in-python/">5 Best Ways to Paste Copied Text From the Keyboard in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p class="has-base-2-background-color has-background wp-block-paragraph"><b><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Problem Formulation:</b> How does one paste a string that has been copied to the clipboard into their Python program? For instance, if a user has copied &#8220;Hello, World!&#8221; to the clipboard, how can the program retrieve that text and use it within the Python script?</p>



<h2 class="wp-block-heading">Method 1: Using the Pyperclip Module</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The Pyperclip module is a cross-platform Python module for copying and pasting text to the clipboard. It allows Python programs to interact with the clipboard, providing simple copy() and paste() functions. Here is how you can use the <code>paste()</code> function to retrieve text from the clipboard.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pyperclip

# Assume "Hello, World!" is already copied to the clipboard
copied_text = pyperclip.paste()
print(copied_text)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello, World!</pre>


<p class="wp-block-paragraph">This code snippet uses Pyperclip&#8217;s <code>paste()</code> function to retrieve any text stored in the system&#8217;s clipboard. It then prints the retrieved text to the console.</p>



<h2 class="wp-block-heading">Method 2: Using the Clipboard Module</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The Clipboard module provides a simple way to copy and paste text to and from the clipboard on Windows. For those using Windows, the clipboard module can be a straightforward option for clipboard interactions in Python.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import clipboard

# Assume "Hello, World!" is already copied to the clipboard
copied_text = clipboard.paste()
print(copied_text)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello, World!</pre>


<p class="wp-block-paragraph">The provided example showcases how to use the <code>clipboard</code> module to paste text. The <code>paste()</code> function retrieves the content from the clipboard and the <code>print()</code> function outputs it to the terminal.</p>



<h2 class="wp-block-heading">Method 3: Using the Tkinter Module</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">Tkinter is the standard GUI (Graphical User Interface) library for Python. Though primarily designed for creating GUIs, it also offers clipboard access through its <code>clipboard_get()</code> method in the <code>Tk</code> class.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter

root = tkinter.Tk()
root.withdraw()  # Hides the Tkinter window

# Assume "Hello, World!" is already copied to the clipboard
copied_text = root.clipboard_get()
print(copied_text)

root.destroy()</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello, World!</pre>


<p class="wp-block-paragraph">This snippet begins by creating a hidden Tkinter window to access the clipboard and uses <code>clipboard_get()</code> to paste the contents. It then cleans up by destroying the Tk window after use.</p>



<h2 class="wp-block-heading">Method 4: Using xclip/xsel on Linux</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">On Linux systems, <code>xclip</code> or <code>xsel</code> commands can be used for clipboard operations. These commands can be accessed from within Python using the <code>subprocess</code> module.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import subprocess

# This example uses xclip. You can also use xsel by replacing 'xclip' with 'xsel' in the command.
copied_text = subprocess.check_output('xclip -o', shell=True).decode('utf-8')
print(copied_text)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello, World!</pre>


<p class="wp-block-paragraph">This code example leverages the <code>xclip</code> command accessed through Python&#8217;s <code>subprocess</code> module to retrieve the clipboard contents in a Linux environment.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using pandas read_clipboard()</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">Pandas provides a <code>read_clipboard()</code> function that can be used to paste tabular data directly from the clipboard into a DataFrame. This method is useful for quickly importing data copied from a spreadsheet or table.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd

# Assume a table is already copied to the clipboard
df = pd.read_clipboard()
print(df)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">       Data
0  Hello, World!</pre>


<p class="wp-block-paragraph">This one-liner code snippet shows the <code>read_clipboard()</code> function in action: reading the contents of the clipboard assumed to be tabular data and printing the resulting DataFrame.</p>



<h2 class="wp-block-heading">Summary/Discussion</h2>


<ul class="wp-block-list">
  
<li><b>Method 1: Pyperclip</b>. Simple and cross-platform. Requires third-party installation. Not suitable for pasting non-text clipboard formats.</li>

  
<li><b>Method 2: Clipboard</b>. Specifically for Windows. Requires third-party module. Straightforward with limitations to non-text formats and non-Windows systems.</li>

  
<li><b>Method 3: Tkinter</b>. Part of the Python standard library. GUI must be managed, but provides a non-third-party solution. Overkill for simple clipboard operations.</li>

  
<li><b>Method 4: xclip/xsel</b>. Linux based solution with good performance. Requires these utilities to be pre-installed. Not cross-platform.</li>

  
<li><b>Bonus Method 5: pandas read_clipboard()</b>. Great for pasting tabular data. Part of the pandas library. Requires pandas and is limited to tabular data.</li>

</ul>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-paste-copied-text-from-the-keyboard-in-python/">5 Best Ways to Paste Copied Text From the Keyboard in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>5 Best Ways to Display a Table Editor in a Tkinter Text Widget</title>
		<link>https://blog.finxter.com/5-best-ways-to-display-a-table-editor-in-a-tkinter-text-widget/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sat, 02 Mar 2024 21:06:24 +0000</pubDate>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1660729</guid>

					<description><![CDATA[<p>💡 Problem Formulation: You&#8217;re working on a Tkinter application and need to display tabular data within a text widget for editing purposes. Ideally, you want users to interact with a table as they would in a spreadsheet. The input is a dataset, perhaps a list of lists, and the desired output is a graphical table ... <a title="5 Best Ways to Display a Table Editor in a Tkinter Text Widget" class="read-more" href="https://blog.finxter.com/5-best-ways-to-display-a-table-editor-in-a-tkinter-text-widget/" aria-label="Read more about 5 Best Ways to Display a Table Editor in a Tkinter Text Widget">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-display-a-table-editor-in-a-tkinter-text-widget/">5 Best Ways to Display a Table Editor in a Tkinter Text Widget</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p class="has-base-2-background-color has-background wp-block-paragraph"><b><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Problem Formulation:</b> You&#8217;re working on a Tkinter application and need to display tabular data within a text widget for editing purposes. Ideally, you want users to interact with a table as they would in a spreadsheet. The input is a dataset, perhaps a list of lists, and the desired output is a graphical table embedded within the Tkinter Text widget, allowing data to be viewed and edited.</p>



<h2 class="wp-block-heading">Method 1: Using the <code>tkinter.Text()</code> Widget with Manual Spacing</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">One straightforward way to create a table editor in a text widget is to manually manage the spacing of <a href="https://blog.finxter.com/python-strings-made-easy/" target="_blank" rel="noopener"> strings </a> to mimic table cells. You would use string formatting to align text into columns, simulating a table structure. This method offers simplicity but lacks advanced features like cell selection or interactive editing.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

root = tk.Tk()
text_widget = tk.Text(root)
data = [['row1col1', 'row1col2'], ['row2col1', 'row2col2']]

for row in data:
    row_data = ' | '.join(row)
    text_widget.insert(tk.END, row_data + '\n')

text_widget.pack()
root.mainloop()
</pre>


<p class="wp-block-paragraph">Output: A text widget displaying two rows of data with simple column separation.</p>


<p class="wp-block-paragraph">This code snippet creates a Tkinter window with a text widget. It inserts strings into the text widget, with data formatted to appear as two columns in each row. This approach, while crude, can be adequate for displaying simple, non-interactive tables.</p>



<h2 class="wp-block-heading">Method 2: Creating Custom Table with <code>tkinter.Canvas</code> and <code>tkinter.Entry</code> Widgets</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">By combining the <code>Canvas</code> and <code>Entry</code> widgets, you can craft a custom table editor. Use the <code>Canvas</code> to position the <code>Entry</code> widgets in grid-like fashion. This approach can be customizable and creates an editable table, but it also requires more code and intricate widget management.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()

data = [['row1col1', 'row1col2'], ['row2col1', 'row2col2']]
entries = []

for i, row in enumerate(data):
    temp = []
    for j, val in enumerate(row):
        entry = tk.Entry(canvas)
        canvas.create_window(100*j, 20*i, window=entry)
        entry.insert(0, val)
        temp.append(entry)
    entries.append(temp)

root.mainloop()
</pre>


<p class="wp-block-paragraph">Output: A canvas with entry widgets arranged to represent a table where each cell is editable.</p>


<p class="wp-block-paragraph">This snippet constructs a table where each cell is a Tkinter Entry widget positioned on a Canvas. Users can directly edit the content of each cell, and you can retrieve the data programmatically from the Entry widgets.</p>



<h2 class="wp-block-heading">Method 3: Using the <code>tkinter.ttk.Treeview</code> as a Table</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>ttk.Treeview</code> widget works as a multi-column listbox that can be configured to look like a table. It&#8217;s a part of Tkinter&#8217;s themed widget set <code>ttk</code> and offers a powerful alternative for displaying table data with functionalities like sorting and selecting rows.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import ttk

root = tk.Tk()
tree = ttk.Treeview(root, columns=('Column 1', 'Column 2'), show='headings')
tree.heading('Column 1', text='Column 1')
tree.heading('Column 2', text='Column 2')

data = [('row1col1', 'row1col2'), ('row2col1', 'row2col2')]
for row in data:
    tree.insert('', tk.END, values=row)

tree.pack()
root.mainloop()
</pre>


<p class="wp-block-paragraph">Output: A Treeview widget displaying data in two columns with headers, resembling a table.</p>


<p class="wp-block-paragraph">This code demonstrates how to set up a <code>ttk.Treeview</code> widget as a table with two columns. The Treeview widget can be a perfect component for a table editor in a Tkinter application when you want a more sophisticated interface that includes functionalities like column headings and row selection.</p>



<h2 class="wp-block-heading">Method 4: Embedding <code>matplotlib</code> Table in Tkinter</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">For a more visually appealing and customizable table, consider embedding a <code>matplotlib</code> table into your Tkinter application using a FigureCanvasTkAgg widget. Though primarily used for plotting graphs, <code>matplotlib</code> can also render tables that can be highly stylized.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

root = tk.Tk()
fig = Figure(figsize=(2, 1), dpi=100)
table = fig.add_subplot(111)

cell_text = [['1', '2'], ['3', '4']]
table.table(cellText=cell_text, loc='center')
table.axis('off')

canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack()

root.mainloop()
</pre>


<p class="wp-block-paragraph">Output: A Tkinter window displaying a <code>matplotlib</code> table with two rows and two columns.</p>


<p class="wp-block-paragraph">This code integrates a <code>matplotlib</code> figure as a table within a Tkinter application, providing the ability to stylize and format the table extensively. However, editing functionality is not inherently available and would require additional coding to enable.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using the <code>pandastable</code> Library</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>pandastable</code> library offers an out-of-the-box table editor that can be integrated into Tkinter apps. It&#8217;s specifically designed for displaying, editing, and analyzing pandas DataFrames within a Tkinter GUI.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from pandastable import Table
import pandas as pd

root = tk.Tk()
frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

df = pd.DataFrame({'Column 1': [1, 3], 'Column 2': [2, 4]})
pt = Table(frame, dataframe=df, showtoolbar=True, showstatusbar=True)
pt.show()

root.mainloop()
</pre>


<p class="wp-block-paragraph">Output: A Tkinter frame containing an interactive table editor with dataframe editing capability.</p>


<p class="wp-block-paragraph">This snippet swiftly integrates a full-featured table editor into the Tkinter application, using a pandas DataFrame as the data source. The <code>pandastable</code> library takes care of rendering and provides toolbars and status bars for quick DataFrame editing.</p>



<h2 class="wp-block-heading">Summary/Discussion</h2>


<ul class="wp-block-list">
    
<li><b>Method 1:</b> Manual Spacing in Text Widget. Simple and fast for basic use. Lacks interactivity and scalability.</li>

    
<li><b>Method 2:</b> Custom Canvas and Entry Widgets. Customizable and interactive. Requires complex widget placement and event handling.</li>

    
<li><b>Method 3:</b> Treeview Widget. Advanced out-of-the-box features. Appearance and behavior more rigid than custom implementations.</li>

    
<li><b>Method 4:</b> Matplotlib Tables. Attractive and stylizable. Not inherently editable and requires additional code for interaction.</li>

    
<li><b>Method 5:</b> Pandastable library. Convenient with extensive features for DataFrame editing. Relies on external library and pandas.</li>

</ul>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-display-a-table-editor-in-a-tkinter-text-widget/">5 Best Ways to Display a Table Editor in a Tkinter Text Widget</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>5 Best Ways to Ask a User to Select a Folder to Read the Files in Python</title>
		<link>https://blog.finxter.com/5-best-ways-to-ask-a-user-to-select-a-folder-to-read-the-files-in-python/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sat, 02 Mar 2024 21:06:24 +0000</pubDate>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1660730</guid>

					<description><![CDATA[<p>💡 Problem Formulation: This article provides solutions to the common task of prompting a user to select a directory from which a Python script can read files. The aim is to enable file processing or analysis based on user-selected content. For instance, input could be the user&#8217;s selection of a &#8216;Photos&#8217; folder and the desired ... <a title="5 Best Ways to Ask a User to Select a Folder to Read the Files in Python" class="read-more" href="https://blog.finxter.com/5-best-ways-to-ask-a-user-to-select-a-folder-to-read-the-files-in-python/" aria-label="Read more about 5 Best Ways to Ask a User to Select a Folder to Read the Files in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-ask-a-user-to-select-a-folder-to-read-the-files-in-python/">5 Best Ways to Ask a User to Select a Folder to Read the Files in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p class="has-base-2-background-color has-background wp-block-paragraph"><b><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Problem Formulation:</b> This article provides solutions to the common task of prompting a user to select a directory from which a Python script can read files. The aim is to enable file processing or analysis based on user-selected content. For instance, input could be the user&#8217;s selection of a &#8216;Photos&#8217; folder and the desired output would be a list of file paths of the photos contained therein.</p>



<h2 class="wp-block-heading">Method 1: Using <code>os</code> and <code>input</code> Functions</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>os</code> module in Python provides a way to interact with the operating system. Combined with the built-in <code>input</code> function, it can prompt users to enter the path of the folder they wish to select manually. This method is platform-independent and doesn&#8217;t require additional installations.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os

folder_path = input("Please enter the path of your folder: ")
file_list = os.listdir(folder_path)

print("Files in the selected folder:")
print(file_list)
</pre>


<p class="wp-block-paragraph"><b>Output:</b> A list of files in the user-specified folder.</p>


<p class="wp-block-paragraph">This code snippet captures the path of the folder directly from the user through the command line and then uses the <code>os.listdir()</code> function to retrieve a list of files in that folder. The user needs to know the exact path and enter it correctly, which may not be the most user-friendly method, especially for non-technical users.</p>



<h2 class="wp-block-heading">Method 2: Using <code>tkinter</code> File Dialog</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>tkinter</code> library includes file dialog utilities that can provide a graphical interface for folder selection. This approach enhances user experience by offering a familiar and interactive way to navigate the filesystem and select a directory.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()  # Hide the main window

folder_path = filedialog.askdirectory()

print("Selected folder:", folder_path)
</pre>


<p class="wp-block-paragraph"><b>Output:</b> The path of the selected folder.</p>


<p class="wp-block-paragraph">This snippet makes use of the <code>askdirectory</code> function from the <code>tkinter</code> library&#8217;s <code>filedialog</code> module, providing a UI for directory selection. It is a user-friendly approach as it does not require the user to type a path; however, it requires the <code>tkinter</code> library, which might not be installed by default in some Python environments.</p>



<h2 class="wp-block-heading">Method 3: Utilizing <code>pathlib</code> with <code>input</code></h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The modern <code>pathlib</code> module abstracts paths into an object-oriented hierarchy, making path manipulations more intuitive. In this method, the power of <code>pathlib</code> is combined with the simplicity of <code>input</code> to manually select a directory and list its contents.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from pathlib import Path

folder_path = Path(input("Please enter the path of your folder: "))
file_list = [file for file in folder_path.iterdir() if file.is_file()]

print("Files in the selected folder:")
print(file_list)
</pre>


<p class="wp-block-paragraph"><b>Output:</b> A list of the <code>Path</code> objects of the files in the selected folder.</p>


<p class="wp-block-paragraph">Using <code>Path.iterdir()</code>, this approach filters out directories and only lists files. The <code>pathlib</code> module can make path manipulations easier and more readable but still requires users to input the path accurately.</p>



<h2 class="wp-block-heading">Method 4: Implementing <code>os.walk</code></h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>os.walk</code> function is a generator that navigates the directory tree and retrieves the file paths. This method provides an automatic way to read files from a user-defined base folder, including files in subdirectories.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os

folder_path = input("Please enter the path of your folder: ")

file_paths = []
for root, dirs, files in os.walk(folder_path):
    for file in files:
        file_paths.append(os.path.join(root, file))

print("Files in the selected folder and subfolders:")
print(file_paths)
</pre>


<p class="wp-block-paragraph"><b>Output:</b> A list of file paths in the selected directory and all subdirectories.</p>


<p class="wp-block-paragraph">This code uses <code>os.walk()</code> to walk through the directory tree and compile a list of file paths. This is useful when the files are in different subdirectories within a common base directory. Like the <code>os.listdir()</code> method, the user must then properly input the base folder path.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using <code>glob</code> with Wildcards</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">For quick and simple file listing including pattern matching, the <code>glob</code> module provides a way to specify file patterns (using wildcards) directly in folder paths—useful for when you want files of a certain type from the selected directory.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import glob

folder_path = input("Please enter the path of your folder: ")
file_paths = glob.glob(f"{folder_path}/*")

print("Files and directories directly under the selected folder:")
print(file_paths)
</pre>


<p class="wp-block-paragraph"><b>Output:</b> A list of files and directories that match the wildcard pattern in the selected directory.</p>


<p class="wp-block-paragraph">This example uses <code>glob.glob()</code> to generate file paths based on a pattern. It&#8217;s straightforward and can be handy for filtering specific file types by modifying the wildcard pattern, though it won&#8217;t recursively search through subdirectories.</p>



<h2 class="wp-block-heading">Summary/Discussion</h2>


<ul class="wp-block-list">
  
<li><b>Method 1:</b> <code>os</code> and <code>input</code>. Strengths: No additional libraries needed; platform-independent. Weaknesses: Requires user to know and enter correct path.</li>

  
<li><b>Method 2:</b> <code>tkinter</code> File Dialog. Strengths: User-friendly graphical interface. Weaknesses: Requires <code>tkinter</code>; not installed by default on some systems.</li>

  
<li><b>Method 3:</b> <code>pathlib</code> with <code>input</code>. Strengths: Easier path manipulation; modern API. Weaknesses: User input still needed; not as interactive as file dialogs.</li>

  
<li><b>Method 4:</b> <code>os.walk</code>. Strengths: Recursive directory traversal; automatic. Weaknesses: Can be complex for large directory trees; user input required for base path.</li>

  
<li><b>Bonus Method 5:</b> <code>glob</code> with Wildcards. Strengths: Pattern matching capabilities; very concise. Weaknesses: No recursive search; user must specify patterns.</li>

</ul>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-ask-a-user-to-select-a-folder-to-read-the-files-in-python/">5 Best Ways to Ask a User to Select a Folder to Read the Files in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>5 Best Ways to Get a String from a Tkinter Filedialog in Python 3</title>
		<link>https://blog.finxter.com/5-best-ways-to-get-a-string-from-a-tkinter-filedialog-in-python-3/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sat, 02 Mar 2024 21:06:24 +0000</pubDate>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1660731</guid>

					<description><![CDATA[<p>💡 Problem Formulation: When working with graphical user interfaces in Python, developers may need to obtain file paths from users through dialogs. The popular library Tkinter provides a module named filedialog for this purpose. This article explains how to use the tkinter.filedialog module to get a file path as a string, which is essential for ... <a title="5 Best Ways to Get a String from a Tkinter Filedialog in Python 3" class="read-more" href="https://blog.finxter.com/5-best-ways-to-get-a-string-from-a-tkinter-filedialog-in-python-3/" aria-label="Read more about 5 Best Ways to Get a String from a Tkinter Filedialog in Python 3">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-get-a-string-from-a-tkinter-filedialog-in-python-3/">5 Best Ways to Get a String from a Tkinter Filedialog in Python 3</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p class="has-base-2-background-color has-background wp-block-paragraph"><b><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Problem Formulation:</b> When working with graphical user interfaces in Python, developers may need to obtain file paths from users through dialogs. The popular library Tkinter provides a module named filedialog for this purpose. This article explains how to use the <code>tkinter.filedialog</code> module to get a file path as a string, which is essential for opening, saving, or processing files within a Python application. The goal is to show different methods to present a dialog that allows the user to select a file and then capture the absolute path of that file as a string.</p>



<h2 class="wp-block-heading">Method 1: Using <code>filedialog.askopenfilename()</code></h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">This method uses the <code>askopenfilename()</code> function from Tkinter’s filedialog module, which prompts the user with a file open dialog and returns the selected file path as a string.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()  # Hide the root window

file_path = filedialog.askopenfilename()
print(file_path)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/home/user/Documents/example.txt</pre>


<p class="wp-block-paragraph">The code snippet initializes a TK window and hides it, then it immediately opens a file dialog for the user to select a file. Once a file is selected, the absolute path is printed to the console. The root window is hidden because we only want to show the file dialog and not a full GUI window.</p>



<h2 class="wp-block-heading">Method 2: Using <code>filedialog.askopenfile()</code></h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>askopenfile()</code> function opens a file dialog but, in addition to returning the file path, it also opens the file for reading and returns a file object. You can then call the <code>name</code> attribute to get the path as a string.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_obj = filedialog.askopenfile(mode='r')
if file_obj:
    file_path = file_obj.name
    file_obj.close()
    print(file_path)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/home/user/Documents/example.txt</pre>


<p class="wp-block-paragraph">After invoking the <code>askopenfile()</code> function, we check if the user has chosen a file rather than cancelling the dialog. If a file is selected, we get the file path through the <code>file_obj.name</code>, close the file, and print the path. This method gives you both the file object and the path, which can be useful if you need to perform immediate file operations.</p>



<h2 class="wp-block-heading">Method 3: Customizing Options with <code>askopenfilename()</code></h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">This method is a variation of the first one, adding customization to the file dialog such as setting the title, initial directory, and file types to provide a better user experience.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename(
    title = "Select a text file",
    initialdir = "/",
    filetypes = (("text files","*.txt"),("all files","*.*"))
)
print(file_path)</pre>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/home/user/Documents/example.txt</pre>


<p class="wp-block-paragraph">The snippet is enhanced with additional arguments to <code>askopenfilename()</code> to customize the dialog’s appearance and functionality. The title is set to &#8220;Select a text file&#8221;, the dialog opens in the root directory initially, and it filters the view to show only text files or all files. Customizing the dialog helps to guide the user in selecting the correct type of file.</p>



<h2 class="wp-block-heading">Method 4: Using <code>askopenfilenames()</code> for Multiple Files</p>
</h2>
<!-- /wp:post-content -->
<!-- wp:paragraph {"backgroundColor":"global-color-8"} -->
<p class="has-global-color-8-background-color has-background">When the application requires the selection of multiple files, <code>askopenfilenames()</code> can be used. This opens a file dialog that allows users to select multiple files, returning a tuple of file paths.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>Here&#8217;s an example:</p>
<!-- /wp:paragraph -->
<!-- wp:enlighter/codeblock {"language":"python"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_paths_tuple = filedialog.askopenfilenames()
file_paths_list = list(file_paths_tuple)
print(file_paths_list)</pre>
<!-- /wp:enlighter/codeblock -->
<!-- wp:paragraph -->
<p>Output:</p>
<!-- /wp:paragraph -->
<!-- wp:enlighter/codeblock {"language":"python"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['/home/user/Documents/example1.txt', '/home/user/Documents/example2.txt']</pre>
<!-- /wp:enlighter/codeblock -->
<!-- wp:paragraph -->
<p>With <code>askopenfilenames()</code>, users can select more than one file. The returned file paths are in a tuple, which we convert to a list to work with more easily. This method is beneficial when the user needs to open multiple files at once.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Bonus One-Liner Method 5: Lambda Function with <code>askopenfilename()</code></h2>
<!-- /wp:heading -->
<!-- wp:paragraph {"backgroundColor":"global-color-8"} -->
<p class="has-global-color-8-background-color has-background">A lambda function can be used to create a one-liner for obtaining the file path. While it&#8217;s compact, it’s not always recommended for readability reasons unless you&#8217;re comfortable with the syntax.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>Here&#8217;s an example:</p>
<!-- /wp:paragraph -->
<!-- wp:enlighter/codeblock {"language":"python"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk
from tkinter import filedialog

get_file_path = lambda: filedialog.askopenfilename()
print(get_file_path())</pre>
<!-- /wp:enlighter/codeblock -->
<!-- wp:paragraph -->
<p>Output:</p>
<!-- /wp:paragraph -->
<!-- wp:enlighter/codeblock {"language":"python"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/home/user/Documents/example.txt</pre>
<!-- /wp:enlighter/codeblock -->
<!-- wp:paragraph -->
<p>This single line of code, when called, triggers the file dialog and returns the file path. While it seems efficient, it&#8217;s often better to write clear and readable code, so use this technique with caution.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Summary/Discussion</h2>
<!-- /wp:heading -->
<!-- wp:list -->
<ul>
    <!-- wp:list-item -->
<li><b>Method 1: <code>askopenfilename()</code></b>. Simple and direct. Returns a string. Does not open the file.</li>
<!-- /wp:list-item -->
    <!-- wp:list-item -->
<li><b>Method 2: <code>askopenfile()</code></b>. Opens the file and returns a file object. Best when you need to read the file as well.</li>
<!-- /wp:list-item -->
    <!-- wp:list-item -->
<li><b>Method 3: Custom options</b>. Enhances user experience by customizing the dialog. Helps in narrowing down file selection.</li>
<!-- /wp:list-item -->
    <!-- wp:list-item -->
<li><b>Method 4: <code>askopenfilenames()</code></b>. Best for multiple file selection. Returns a tuple of file paths.</li>
<!-- /wp:list-item -->
    <!-- wp:list-item -->
<li><b>Method 5: Lambda function</b>. Compact and concise. May sacrifice readability for brevity.</li>
<!-- /wp:list-item -->
</ul><!-- /wp:list -->
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-get-a-string-from-a-tkinter-filedialog-in-python-3/">5 Best Ways to Get a String from a Tkinter Filedialog in Python 3</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>5 Best Ways to Close Only the Top-Level Window in Python Tkinter</title>
		<link>https://blog.finxter.com/5-best-ways-to-close-only-the-top-level-window-in-python-tkinter/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sat, 02 Mar 2024 21:06:24 +0000</pubDate>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1660732</guid>

					<description><![CDATA[<p>💡 Problem Formulation: When working with Python&#8217;s Tkinter library, you might encounter a situation where you have multiple windows open, and you want to close just the top-level one without terminating the entire application. This is especially common in GUI applications where multiple dialogs or child windows are involved. How do you close only the ... <a title="5 Best Ways to Close Only the Top-Level Window in Python Tkinter" class="read-more" href="https://blog.finxter.com/5-best-ways-to-close-only-the-top-level-window-in-python-tkinter/" aria-label="Read more about 5 Best Ways to Close Only the Top-Level Window in Python Tkinter">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-best-ways-to-close-only-the-top-level-window-in-python-tkinter/">5 Best Ways to Close Only the Top-Level Window in Python Tkinter</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[



<p class="has-base-2-background-color has-background wp-block-paragraph"><b><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Problem Formulation:</b> When working with Python&#8217;s Tkinter library, you might encounter a situation where you have multiple windows open, and you want to close just the top-level one without terminating the entire application. This is especially common in GUI applications where multiple dialogs or child windows are involved. How do you close only the top-level window without affecting other windows? Let&#8217;s go over some methods to achieve this.</p>



<h2 class="wp-block-heading">Method 1: Using the <code>destroy()</code> Method</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">One standard way to close the top-level window in Tkinter is by invoking the <code>destroy()</code> method on the top-level window object. This method effectively closes the window and terminates its mainloop, without closing the entire application if there are other windows open.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

root = tk.Tk()
top = tk.Toplevel(root)
top.title("Top-Level Window")

def close_top():
    top.destroy()

close_button = tk.Button(top, text="Close", command=close_top)
close_button.pack()

root.mainloop()</pre>


<p class="wp-block-paragraph">The output of this code snippet is the closing of only the top-level window when the &#8220;Close&#8221; button is clicked, while the root window remains open.</p>


<p class="wp-block-paragraph">This code snippet creates a root window and a top-level window, each with their respective widgets. When the user presses the &#8220;Close&#8221; button on the top-level window, the <code>close_top()</code> function is called, triggering the <code>destroy()</code> method and closing just the top-level window without terminating the entire program.</p>



<h2 class="wp-block-heading">Method 2: Overriding the Window Close Button</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">To prevent the default behavior of closing the entire application when the window close button is clicked, you can override the close button&#8217;s functionality to only destroy the top-level window. This keeps the root window or any other windows open.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

root = tk.Tk()
top = tk.Toplevel(root)

top.protocol("WM_DELETE_WINDOW", top.destroy)

root.mainloop()</pre>


<p class="wp-block-paragraph">The output of this code is that clicking the close button (typically an &#8220;X&#8221; at the corner of the window) on the top-level window will close only that window.</p>


<p class="wp-block-paragraph">With the <code>protocol()</code> method, we are changing the behavior of the &#8220;WM_DELETE_WINDOW&#8221; event (which is triggered when the window&#8217;s close button is clicked), to execute the <code>destroy()</code> method for the top-level window only. This ensures that other windows remain unaffected when the top-level window is closed.</p>



<h2 class="wp-block-heading">Method 3: Using the <code>withdraw()</code> Method</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">The <code>withdraw()</code> method is another Tkinter function that can be used to hide a window without terminating its process. It can be particularly useful when you want to close the top-level window but may want to reopen it again without losing its state.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

root = tk.Tk()
top = tk.Toplevel(root)

def hide_top():
    top.withdraw()

hide_button = tk.Button(top, text="Hide", command=hide_top)
hide_button.pack()

root.mainloop()</pre>


<p class="wp-block-paragraph">This code will result in the top-level window being hidden from view when the &#8220;Hide&#8221; button is clicked, without closing the root window.</p>


<p class="wp-block-paragraph">The <code>hide_top()</code> function is connected to a button within the top-level window. When this button is clicked, the <code>withdraw()</code> method is called on the top-level window, which effectively hides it. Unlike <code>destroy()</code>, this window can be later shown again using <code>deiconify()</code>.</p>



<h2 class="wp-block-heading">Method 4: Disconnecting the Top-Level Window from the Mainloop</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">Creating the top-level window without tying it to the root window&#8217;s mainloop can allow for it to be closed independently. Although this approach is unconventional, it might be useful in certain scenarios.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

def create_toplevel():
    top = tk.Toplevel()
    top.title("Independent Top-Level")
    top.mainloop()

root = tk.Tk()
open_button = tk.Button(root, text="Open Independent Top-Level", command=create_toplevel)
open_button.pack()

root.mainloop()</pre>


<p class="wp-block-paragraph">With this code, closing the top-level window created by pressing the &#8220;Open Independent Top-Level&#8221; button will only affect that window and not the main application.</p>


<p class="wp-block-paragraph">By running a separate <code>mainloop()</code> for the top-level window, you are splitting it off from the main application loop. This makes the top-level window behave as an independent entity, but be aware that it could lead to unexpected behavior and is not recommended without a good understanding of Tkinter&#8217;s event loop.</p>



<h2 class="wp-block-heading">Bonus One-Liner Method 5: Using Lambda Functions</h2>


<p class="has-global-color-8-background-color has-background wp-block-paragraph">A quick and easy one-liner that allows you to close the top-level window involves using a lambda function inline with the button&#8217;s command parameter.</p>


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


<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import tkinter as tk

root = tk.Tk()
top = tk.Toplevel(root)

close_button = tk.Button(top, text="Close", command=lambda: top.destroy())
close_button.pack()

root.mainloop()</pre>


<p class="wp-block-paragraph">This code snippet will provide the same outcome as the first method with a more concise syntax.</p>


<p class="wp-block-paragraph">Using a lambda function, we immediately pass the <code>destroy()</code> method of the top-level window as a command parameter to the button. This simplifies the code by negating the need for an explicitly defined function.</p>



<h2 class="wp-block-heading">Summary/Discussion</h2>


<ul class="wp-block-list">
    
<li><b>Method 1: Using the <code>destroy()</code> Method.</b> This method is straightforward and ideal for most scenarios, and it&#8217;s the recommended way to close a window in Tkinter. However, it completely removes the window, so you cannot bring it back without re-creating it.</li>

    
<li><b>Method 2: Overriding the Window Close Button.</b> It provides a seamless user experience by intercepting the default close action, which is familiar to users. Its limitation is that you have to set it up for each top-level window you create.</li>

    
<li><b>Method 3: Using the <code>withdraw()</code> Method.</b> Offers the ability to hide and reuse a window, preserving its state. While flexible, users may not realize that the window is still running in the background, potentially leaving unnoticed processes open.</li>

    
<li><b>Method 4: Disconnecting the Top-Level Window from the Mainloop.</b> Useful for creating a truly independent window, but it&#8217;s not typical and can complicate the program&#8217;s flow and event management.</li>

    
<li><b>Method 5: Using Lambda Functions.</b> A quick and compact way to close the window, but may not be as clear to read as a separately defined function, especially for beginners.</li>

</ul>

<p>The post <a href="https://blog.finxter.com/5-best-ways-to-close-only-the-top-level-window-in-python-tkinter/">5 Best Ways to Close Only the Top-Level Window in Python Tkinter</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</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-08-24 20:13:10 by W3 Total Cache
-->