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

<channel>
	<title>Python Operators Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/python-operators/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/python-operators/</link>
	<description></description>
	<lastBuildDate>Wed, 24 Apr 2024 11:18:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Python Operators Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/python-operators/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>What is the Python Dunder Method for the &#8220;not and&#8221; Operator?</title>
		<link>https://blog.finxter.com/what-is-the-python-dunder-method-for-the-not-and-operator/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 22 Sep 2023 20:35:01 +0000</pubDate>
				<category><![CDATA[Dunder Methods]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651730</guid>

					<description><![CDATA[<p>In Python, &#8220;dunder&#8221; methods, short for &#8220;double underscore&#8221; methods, are special methods that allow developers to define the behavior of built-in operations for custom objects. For instance, when you use the + operator to add two objects, Python internally calls the __add__ method. Similarly, other operators have their corresponding dunder methods. However, the term &#8220;not ... <a title="What is the Python Dunder Method for the &#8220;not and&#8221; Operator?" class="read-more" href="https://blog.finxter.com/what-is-the-python-dunder-method-for-the-not-and-operator/" aria-label="Read more about What is the Python Dunder Method for the &#8220;not and&#8221; Operator?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/what-is-the-python-dunder-method-for-the-not-and-operator/">What is the Python Dunder Method for the &#8220;not and&#8221; Operator?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In Python, &#8220;dunder&#8221; methods, short for &#8220;double underscore&#8221; methods, are special methods that allow developers to define the behavior of built-in operations for custom objects. For instance, when you use the <a href="https://blog.finxter.com/python-arithmetic-operators/"><code>+</code> operator</a> to add two objects, Python internally calls the <code><a href="https://blog.finxter.com/python-__add__/">__add__</a></code> method. Similarly, other operators have their corresponding dunder methods.</p>



<p>However, the term &#8220;<code>not and</code>&#8221; operator might be a bit misleading, as there isn&#8217;t a direct &#8220;<code>not and</code>&#8221; operator in Python. </p>



<p>Instead, Python provides individual operators for <code>not</code>, and <code>and</code>. But if we delve into the realm of <a href="https://blog.finxter.com/python-bitwise-operators/">bitwise operations</a>, we find operators that might resemble this behavior: the <a href="https://blog.finxter.com/python-bitwise-not-operator/">bitwise NOT (<code>~</code>)</a> and the <a href="https://blog.finxter.com/python-bitwise-and-operator/">bitwise AND (<code>&amp;</code>)</a>.</p>



<p>Let&#8217;s explore the dunder methods associated with these operators.</p>



<h2 class="wp-block-heading">Bitwise NOT (~) and its Dunder Method __invert__</h2>



<p class="has-global-color-8-background-color has-background">The bitwise NOT operator flips the bits of a number. For a custom class, if you want to define or override the behavior of the <code>~</code> operator, you&#8217;d use the <code><a href="https://blog.finxter.com/python-__invert__-magic-method/">__invert__</a></code> method.</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="">class BitwiseNumber:
    def __init__(self, value):
        self.value = value

    def __invert__(self):
        return BitwiseNumber(~self.value)

    def __repr__(self):
        return str(self.value)

number = BitwiseNumber(5)
print(~number)  # Outputs: -6</pre>



<p>In the above example, the <code>__invert__</code> method returns a new <code>BitwiseNumber</code> object with its value inverted.</p>



<h2 class="wp-block-heading">Bitwise AND (&amp;) and its Dunder Method __and__</h2>



<p class="has-global-color-8-background-color has-background">The bitwise AND operator performs a bitwise AND operation between two numbers. For custom classes, the behavior of the <code>&amp;</code> operator can be defined or overridden using the <code><a href="https://blog.finxter.com/python-__and__/">__and__</a></code> method.</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="">class BitwiseNumber:
    def __init__(self, value):
        self.value = value

    def __and__(self, other):
        if isinstance(other, BitwiseNumber):
            return BitwiseNumber(self.value &amp; other.value)
        return NotImplemented

    def __repr__(self):
        return str(self.value)

number1 = BitwiseNumber(5)  # Binary: 101
number2 = BitwiseNumber(3)  # Binary: 011
print(number1 &amp; number2)    # Outputs: 1 (Binary: 001)</pre>



<p>In this example, the <code>__and__</code> method checks if the other object is an instance of <code>BitwiseNumber</code> and then performs a bitwise AND operation.</p>



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



<p>While there isn&#8217;t a direct &#8220;not and&#8221; operator in Python, leveraging the <code>__invert__</code> and <code>__and__</code> methods, you can define how the bitwise NOT and AND operations work for custom objects, respectively.</p>
<p>The post <a href="https://blog.finxter.com/what-is-the-python-dunder-method-for-the-not-and-operator/">What is the Python Dunder Method for the &#8220;not and&#8221; Operator?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Boolean Operators in Python (and, or, not): Mastering Logical Expressions</title>
		<link>https://blog.finxter.com/boolean-operators-in-python-and-or-not-mastering-logical-expressions/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 21 Aug 2023 19:22:44 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1646651</guid>

					<description><![CDATA[<p>Understanding Boolean Operators Boolean operators in Python help you create conditional statements to control the flow of your program. Python provides three basic Boolean operators: and, or, and not. These operators help you construct sophisticated expressions to evaluate the truth or falsity of different conditions. And Operator The and operator returns True if both of ... <a title="Boolean Operators in Python (and, or, not): Mastering Logical Expressions" class="read-more" href="https://blog.finxter.com/boolean-operators-in-python-and-or-not-mastering-logical-expressions/" aria-label="Read more about Boolean Operators in Python (and, or, not): Mastering Logical Expressions">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/boolean-operators-in-python-and-or-not-mastering-logical-expressions/">Boolean Operators in Python (and, or, not): Mastering Logical Expressions</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">Understanding Boolean Operators</h2>



<p>Boolean operators in Python help you create conditional statements to control the flow of your program. Python provides three basic Boolean operators: <code>and</code>, <code>or</code>, and <code>not</code>. These operators help you construct sophisticated expressions to evaluate the truth or falsity of different conditions.</p>



<h3 class="wp-block-heading">And Operator</h3>



<p class="has-global-color-8-background-color has-background">The <code>and</code> operator returns <code>True</code> if both of its operands are true, and <code>False</code> otherwise. You can use it to check multiple conditions at once. </p>



<p>Here is a simple example involving the <code>and</code> operator:</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="">age = 25
income = 50000

if age >= 18 and income >= 30000:
    print("Eligible for loan")
else:
    print("Not eligible for loan")
</pre>



<p>In this example, the condition <code>age >= 18 and income >= 30000</code> must be <code>True</code> for the program to print <code>"Eligible for loan"</code>. If either <code>age</code> is less than 18 or <code>income</code> is less than 30,000, the condition evaluates to <code>False</code>, and the program will print <code>"Not eligible for loan"</code>.</p>



<h3 class="wp-block-heading">Or Operator</h3>



<p class="has-global-color-8-background-color has-background">The <code>or</code> operator returns <code>True</code> as long as at least one of its operands is true. You can use it to specify alternatives in your code. </p>



<p>Here&#8217;s an example of how to use the <code>or</code> operator:</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="">student_score = 80
extra_credit = 5

if student_score >= 90 or extra_credit >= 10:
    print("Student grade: A")
else:
    print("Student grade: B")
</pre>



<p>In this case, if the <code>student_score</code> is 90 or higher, or if the student has completed 10 or more extra credit, the program will print &#8220;Student grade: A&#8221;. Otherwise, it will print <code>"Student grade: B"</code>.</p>



<h3 class="wp-block-heading">Not Operator</h3>



<p class="has-global-color-8-background-color has-background">The <code>not</code> operator inverts the truth value of the expression that follows it. It takes only one operand and returns <code>True</code> if the operand is <code>False</code>, and vice versa. The <code>not</code> operator can be used to check if a certain condition is not met. </p>



<p>Here is an example:</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="">message = "Hello, World!"

if not message.startswith("Hi"):
    print("Message does not start with 'Hi'")
else:
    print("Message starts with 'Hi'")
</pre>



<p>In this example, the program checks whether the <code>message</code> <em>does not</em> start with the string <code>"Hi"</code>. If it doesn&#8217;t, the condition <code>not message.startswith("Hi")</code> evaluates to <code>True</code>, and the program prints <code>"Message does not start with 'Hi'"</code>. If the condition is <code>False</code>, the program prints <code>"Message starts with 'Hi'"</code>.</p>



<h2 class="wp-block-heading">Boolean Values in Python</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="553" height="553" src="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_66b42b72-1bb0-4976-a8ce-a550d984d5ae.png" alt="" class="wp-image-1646648" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_66b42b72-1bb0-4976-a8ce-a550d984d5ae.png 553w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_66b42b72-1bb0-4976-a8ce-a550d984d5ae-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_66b42b72-1bb0-4976-a8ce-a550d984d5ae-150x150.png 150w" sizes="(max-width: 553px) 100vw, 553px" /></figure>
</div>


<p>In Python, Boolean values represent one of two states: <strong>True</strong> or <strong>False</strong>. These values are essential for making decisions and controlling the flow of your program. This section covers the basics of Boolean values, the <code><a href="https://blog.finxter.com/python-return-nothing-null-none-nan-from-function/">None</a></code> value, and how to convert different data types into Boolean values.</p>



<h3 class="wp-block-heading">True and False Values</h3>



<p>Boolean values in Python can be represented using the keywords <code>True</code> and <code>False</code>. They are instances of the <code><a href="https://blog.finxter.com/python-bool/">bool</a></code> class and can be used with various types of <a href="https://blog.finxter.com/python-operators-overview/">operators</a> such as <a href="https://blog.finxter.com/python-logical-operators-blog-video/">logical</a>, <a href="https://blog.finxter.com/python-comparison-operators/">comparison</a>, and <a href="https://blog.finxter.com/is-vs-python-identity-and-equality/">equality operators</a>. </p>



<p>Here&#8217;s an example using Boolean values with the logical <code>and</code> operator:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = True
y = False
result = x and y
print(result)  # Output: False
</pre>



<h3 class="wp-block-heading">None Value</h3>



<p>In addition to <code>True</code> and <code>False</code>, Python provides a special value called <code>None</code>. <code>None</code> is used to represent the absence of a value or a null value. While it&#8217;s not a Boolean value, it is considered <strong><a href="https://blog.finxter.com/how-to-convert-a-list-of-booleans-to-integers/">falsy</a></strong> when used in a Boolean context:</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="">if None:
    print("This won't be printed.")
</pre>



<h3 class="wp-block-heading">Converting to Boolean Type</h3>



<p>In Python, various data types such as numbers, <a href="https://blog.finxter.com/python-strings-made-easy/">strings</a>, <a href="https://blog.finxter.com/sets-in-python/">sets</a>, <a href="https://blog.finxter.com/python-lists/">lists</a>, and <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/">tuples</a> can also be converted to Boolean values using the <code><a href="https://blog.finxter.com/python-bool/">bool()</a></code> function. When converted, these data types will yield a <a href="https://blog.finxter.com/how-to-convert-bool-true-false-to-a-string-in-python/"><strong>Truthy</strong> or <strong>Falsy</strong></a> value:</p>



<ul class="wp-block-list">
<li><strong>Numbers</strong>: Any non-zero number will be <code>True</code>, whereas <code>0</code> will be <code>False</code>.</li>



<li><strong>Strings</strong>: Non-empty strings will be <code>True</code>, and an empty string <code>''</code> will be <code>False</code>.</li>



<li><strong>Sets, Lists, and Tuples</strong>: Non-empty collections will be <code>True</code>, and empty collections will be <code>False</code>.</li>
</ul>



<p>Here are a few examples of converting different data types into Boolean values:</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=""># Converting numbers
print(bool(10))  # Output: True
print(bool(0))   # Output: False

# Converting strings
print(bool("Hello"))  # Output: True
print(bool(""))       # Output: False

# Converting lists
print(bool([1, 2, 3]))  # Output: True
print(bool([]))         # Output: False
</pre>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-to-check-if-a-python-list-is-empty/">How to Check If a Python List is Empty?</a></p>



<h2 class="wp-block-heading">Working with Boolean Expressions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="553" height="553" src="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_241edbbc-715d-4a0b-83d0-b07f5f2749e9.png" alt="" class="wp-image-1646647" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_241edbbc-715d-4a0b-83d0-b07f5f2749e9.png 553w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_241edbbc-715d-4a0b-83d0-b07f5f2749e9-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_241edbbc-715d-4a0b-83d0-b07f5f2749e9-150x150.png 150w" sizes="(max-width: 553px) 100vw, 553px" /></figure>
</div>


<p>In Python, <a href="https://blog.finxter.com/a-simple-introduction-to-boolean-logic-operators-in-python/">Boolean operators</a> (<code>and</code>, <code>or</code>, <code>not</code>) allow you to create and manipulate Boolean expressions to control the flow of your code. This section will cover creating Boolean expressions and using them in <a href="https://blog.finxter.com/if-then-else-in-one-line-python/"><code>if</code> statements</a>.</p>



<h3 class="wp-block-heading">Creating Boolean Expressions</h3>



<p class="has-global-color-8-background-color has-background">A Boolean expression is a statement that yields a truth value, either <code>True</code> or <code>False</code>. You can create Boolean expressions by combining conditions using the <code>and</code>, <code>or</code>, and <code>not</code> operators, along with <a href="https://blog.finxter.com/python-comparison-operators/">comparison operators</a> such as <code>==</code>, <code>!=</code>, <code>></code>, <code>&lt;</code>, <code>>=</code>, and <code>&lt;=</code>. </p>



<p>Here are some examples:</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="">a = 10
b = 20

# Expression with "and" operator
expr1 = a > 5 and b > 30

# Expression with "or" operator
expr2 = a > 5 or b > 15

# Expression with "not" operator
expr3 = not (a == b)
</pre>



<p>In the above code snippet, <code>expr1</code> evaluates to <code>True</code>, <code>expr2</code> evaluates to <code>True</code>, and <code>expr3</code> evaluates to <code>True</code>. You can also create complex expressions by combining multiple operators:</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="">expr4 = (a > 5 and b &lt; 30) or not (a == b)
</pre>



<p>This expression yields <code>True</code>, since both <code>(a &gt; 5 and b &lt; 30)</code> and <code>not (a == b)</code> evaluate to <code>True</code>.</p>



<h3 class="wp-block-heading">Using Boolean Expressions in If Statements</h3>



<p class="has-global-color-8-background-color has-background">Boolean expressions are commonly used in <code>if</code> statements to control the execution path of your code. You can use a single expression or combine multiple expressions to check various conditions before executing a particular block of code. </p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 10
y = 20

if x > 5 and y > 30:
    print("Both conditions are met.")
elif x > 5 or y > 15:
    print("At least one condition is met.")
else:
    print("Neither condition is met.")
</pre>



<p>In this example, the <code>if</code> statement checks if both conditions are met (<code>x > 5 and y &lt; 30</code>); if true, it prints <code>"Both conditions are met"</code>. If that expression is false, it checks the <code>elif</code> statement (x > 5 or y > 15); if true, it prints <code>"At least one condition is met."</code> If both expressions are false, it prints <code>"Neither condition is met."</code></p>



<h2 class="wp-block-heading">Logical Operators and Precedence</h2>



<p>In Python, there are three main logical operators: <code>and</code>, <code>or</code>, and <code>not</code>. These operators are used to perform logical operations, such as comparing values and testing conditions in your code.</p>



<h3 class="wp-block-heading">Operator Precedence</h3>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Python Operator Precedence [Simple Guide]" width="937" height="527" src="https://www.youtube.com/embed/abBw5X1MihA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><a href="https://blog.finxter.com/python-operator-precedence/">Operator precedence</a> determines the order in which these logical operators are evaluated in a complex expression. Python follows a specific order for logical operators:</p>



<ol class="wp-block-list">
<li><code>not</code></li>



<li><code>and</code></li>



<li><code>or</code></li>
</ol>



<p>Here is an example to illustrate precedence:</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="">result = True and False or True
</pre>



<p>In this case, <code>and</code> has a higher precedence than <code>or</code>, so it is evaluated first. The result would be:</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="">result = (True and False) or True
</pre>



<p>After the <code>and</code> operation, it becomes:</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="">result = False or True
</pre>



<p>Finally, the <code>result</code> will be <code>True</code> after evaluating the <code>or</code> operation.</p>



<h3 class="wp-block-heading">Applying Parentheses</h3>



<p class="has-global-color-8-background-color has-background">You can use parentheses to change the order of evaluation or make your expressions more readable. When using parentheses, operations enclosed within them are evaluated first, regardless of precedence rules. </p>



<p>Let&#8217;s modify our previous example:</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="">result = True and (False or True)
</pre>



<p>Now the <code>or</code> operation is performed first, resulting in:</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="">result = True and True
</pre>



<p>And the final <code>result</code> is <code>True</code>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="553" height="553" src="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_9d8738f2-d376-45d3-a9c0-c3db8c7262fc.png" alt="" class="wp-image-1646645" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_9d8738f2-d376-45d3-a9c0-c3db8c7262fc.png 553w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_9d8738f2-d376-45d3-a9c0-c3db8c7262fc-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_9d8738f2-d376-45d3-a9c0-c3db8c7262fc-150x150.png 150w" sizes="auto, (max-width: 553px) 100vw, 553px" /></figure>
</div>


<h2 class="wp-block-heading">Truthy and Falsy Values</h2>



<p class="has-global-color-8-background-color has-background"><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;" /> <strong>Tip</strong>: In Python, values can be considered either &#8220;truthy&#8221; or &#8220;falsy&#8221; when they are used in a boolean context, such as in an <code>if</code> statement or a <a href="https://blog.finxter.com/python-one-line-while-loop-a-simple-tutorial/"><code>while</code> loop</a>. Truthy values evaluate to <code>True</code>, while falsy values evaluate to <code>False</code>. Various data types, like numerics, strings, lists, tuples, dictionaries, sets, and other sequences, can have truthy or falsy values.</p>



<h3 class="wp-block-heading">Determining Truthy and Falsy Values</h3>



<p>When determining the truth value of an object in Python, the following rules apply:</p>



<ul class="wp-block-list">
<li><strong>Numeric types</strong> (<code>int</code>, <code>float</code>, <code>complex</code>): Zero values are falsy, while non-zero values are truthy.</li>



<li><strong>Strings</strong>: Empty strings are falsy, whereas non-empty strings are truthy.</li>



<li><strong>Lists, tuples, dictionaries, sets, and other sequences</strong>: Empty sequences are falsy, while non-empty sequences are truthy.</li>
</ul>



<p>Here are some examples:</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="">if 42: # truthy (non-zero integer)
    pass

if "hello": # truthy (non-empty string)
    pass

if [1, 2, 3]: # truthy (non-empty list)
    pass

if (None,): # truthy (non-empty tuple)
    pass

if {}: # falsy (empty dictionary)
    pass
</pre>



<h3 class="wp-block-heading">Using <code>__bool__()</code> and <code>__len__()</code></h3>



<p>Python classes can control their truth value by implementing the <code><a href="https://blog.finxter.com/python-__bool__-magic-method/">__bool__()</a></code> or <code><a href="https://blog.finxter.com/python-__len__-magic-method/">__len__()</a></code> methods. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Expert Knowledge</strong>: If a class defines the <code>__bool__()</code> method, it should return a boolean value representing the object&#8217;s truth value. If the class does not define <code>__bool__()</code>, Python uses the <code>__len__()</code> method to determine the truth value: if the length of an object is nonzero, the object is truthy; otherwise, it is falsy.</p>



<p>Here&#8217;s an example of a custom class implementing both <code>__bool__()</code> and <code>__len__()</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="">class CustomClass:
    def __init__(self, data):
        self.data = data

    def __bool__(self):
        return bool(self.data) # custom truth value based on data

    def __len__(self):
        return len(self.data) # custom length based on data

custom_obj = CustomClass([1, 2, 3])

if custom_obj: # truthy because custom_obj.data is a non-empty list
    pass
</pre>



<p></p>



<h2 class="wp-block-heading">Comparisons and Boolean Expressions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="553" height="553" src="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_1456a54a-4d79-4c72-8b03-a6754b56dcd3.png" alt="" class="wp-image-1646644" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_1456a54a-4d79-4c72-8b03-a6754b56dcd3.png 553w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_1456a54a-4d79-4c72-8b03-a6754b56dcd3-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2023/08/Finxter_a_digital_brain_on_a_growth_chart_with_cyberspace_envir_1456a54a-4d79-4c72-8b03-a6754b56dcd3-150x150.png 150w" sizes="auto, (max-width: 553px) 100vw, 553px" /></figure>
</div>


<p>In Python, boolean expressions are formed using comparison operators such as <a href="https://blog.finxter.com/python-greater-than/">greater than</a>, <a href="https://blog.finxter.com/python-less-than/">less than</a>, and <a href="https://blog.finxter.com/is-vs-python-identity-and-equality/">equality</a>. Understanding these operators can help you write more efficient and logical code. In this section, we will dive into the different comparison operators and how they work with various expressions in Python.</p>



<h3 class="wp-block-heading">Combining Comparisons</h3>



<p>Some common <a href="https://blog.finxter.com/python-comparison-operators/">comparison operators</a> in Python include:</p>



<ul class="wp-block-list">
<li><code>&gt;</code>: Greater than</li>



<li><code>&lt;</code>: Less than</li>



<li><code>&gt;=</code>: Greater than or equal to</li>



<li><code>&lt;=</code>: Less than or equal to</li>



<li><code>==</code>: Equality</li>



<li><code>!=</code>: Inequality</li>
</ul>



<p class="has-global-color-8-background-color has-background">To combine multiple comparisons, you can use logical operators like <code>and</code>, <code>or</code>, and <code>not</code>. These operators can be used to create more complex conditions with multiple operands. </p>



<p>Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 5
y = 10
z = 15

if x > y and y &lt; z:
    print("All conditions are true")
</pre>



<p>In this example, the <code>and</code> operator checks if both conditions are <code>True</code>. If so, it prints the message. We can also use the <code>or</code> operator, which checks if any one of the conditions is <code>True</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="">if x > y or y &lt; z:
    print("At least one condition is true")
</pre>



<h3 class="wp-block-heading">Short-Circuit Evaluation</h3>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="What is Short Circuit Evaluation in Coding (Python)?" width="937" height="527" src="https://www.youtube.com/embed/oV1JOkjCw5E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-global-color-8-background-color has-background">Python uses <a href="https://blog.finxter.com/what-is-short-circuit-evaluation-in-python/">short-circuit evaluation</a> for boolean expressions, meaning that it will stop evaluating further expressions as soon as it finds one that determines the final result. This can help improve the efficiency of your code.</p>



<p>For instance, when using the <code>and</code> operator, if the first operand is <code>False</code>, Python will not evaluate the second operand, because it knows the entire condition will be <code>False</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="">if False and expensive_function():
    # This won't execute because the first operand is False
    pass
</pre>



<p>Similarly, when using the <code>or</code> operator, if the first operand is <code>True</code>, Python will not evaluate the second operand because it knows the entire condition will be <code>True</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="">if True or expensive_function():
    # This will execute because the first operand is True
    pass
</pre>



<p></p>



<h2 class="wp-block-heading">Common Applications of Boolean Operations</h2>



<p>In Python, Boolean operations are an essential part of programming, with <strong>and</strong>, <strong>or</strong>, <strong>not</strong> being the most common operators. They play a crucial role in decision-making processes like determining the execution paths that your program will follow. In this section, we will explore two major applications of Boolean operations &#8211; Conditional Statements and While Loops.</p>



<h3 class="wp-block-heading">Conditional Statements</h3>



<p>Conditional statements in Python, like <code>if</code>, <code>elif</code>, and <code>else</code>, are often used along with Boolean operators to compare values and determine which block of code will be executed. For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 5
y = 10

if x > 0 and y > 0:
    print("Both x and y are positive")
elif x &lt; 0 or y &lt; 0:
    print("Either x or y is negative (or both)")
else:
    print("Both x and y are zero or one is positive and the other is negative")
</pre>



<p>Here, the <code>and</code> operator checks if both <code>x</code> and <code>y</code> are positive, while the <code>or</code> operator checks if either <code>x</code> or <code>y</code> is negative. These operations allow your code to make complex decisions based on multiple conditions.</p>



<h3 class="wp-block-heading">While Loops</h3>



<p>While loops in Python are often paired with Boolean operations to carry out a specific task until a condition is met. The loop continues as long as the test condition remains <code>True</code>. For example:</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="">count = 0

while count &lt; 10:
    if count % 2 == 0:
        print(f"{count} is an even number")
    else:
        print(f"{count} is an odd number")
    count += 1
</pre>



<p>In this case, the <code>while</code> loop iterates through the numbers 0 to 9, using the <code>not</code> operator to check if the number is even or odd. The loop stops when the variable <code>count</code> reaches 10.</p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="952" height="636" src="https://blog.finxter.com/wp-content/uploads/2023/08/image-96.png" alt="" class="wp-image-1646562" srcset="https://blog.finxter.com/wp-content/uploads/2023/08/image-96.png 952w, https://blog.finxter.com/wp-content/uploads/2023/08/image-96-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/08/image-96-768x513.png 768w" sizes="auto, (max-width: 952px) 100vw, 952px" /></figure>
</div>


<h3 class="wp-block-heading">How do you use &#8216;and&#8217;, &#8216;or&#8217;, &#8216;not&#8217; in Python boolean expressions?</h3>



<p>In Python, <code>and</code>, <code>or</code>, and <code>not</code> are used to combine or modify boolean expressions.</p>



<ul class="wp-block-list">
<li><code>and</code>: Returns <code>True</code> if both operands are <code>True</code>, otherwise returns <code>False</code>.</li>



<li><code>or</code>: Returns <code>True</code> if at least one of the operands is <code>True</code>, otherwise returns <code>False</code>.</li>



<li><code>not</code>: Negates the boolean value.</li>
</ul>



<p>Example:</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="">a = True
b = False

print(a and b) # False
print(a or b)  # True
print(not a)   # False
</pre>



<h3 class="wp-block-heading">How are boolean values assigned in Python?</h3>



<p>In Python, boolean values can be assigned using the keywords <code>True</code> and <code>False</code>. They are both <a href="https://realpython.com/python-boolean/">instances of the <code>bool</code> type</a>. For example:</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="">is_true = True
is_false = False
</pre>



<h3 class="wp-block-heading">What are the differences between &#8216;and&#8217;, &#8216;or&#8217;, and &#8216;and-not&#8217; operators in Python?</h3>



<p><code>and</code> and <code>or</code> are both binary operators that work with two boolean expressions, while <code>and-not</code> is not a single operator but a combination of <code>and</code> and <code>not</code>. Examples:</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="">a = True
b = False

print(a and b)     # False
print(a or b)      # True
print(a and not b) # True (since 'not b' is True)
</pre>



<h3 class="wp-block-heading">How do I use the &#8216;not equal&#8217; relational operator in Python?</h3>



<p>In Python, the <code>not equal</code> relational operator is represented by the symbol <code>!=</code>. It returns <code>True</code> if the two operands are different and <code>False</code> if they are equal. Example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 5
y = 7

print(x != y) # True
</pre>



<h3 class="wp-block-heading">What are the common mistakes with Python&#8217;s boolean and operator usage?</h3>



<p>Common mistakes include misunderstanding operator precedence and mixing <code>and</code>, <code>or</code>, and <code>not</code> without proper grouping using parentheses.</p>



<p>Example:</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="">a = True
b = False
c = True

print(a and b or c)    # True (because 'and' is evaluated before 'or')
print(a and (b or c))  # False (using parentheses to change precedence)
</pre>



<h3 class="wp-block-heading">How is the &#8216;//&#8217; floor division operator related to boolean operators in Python?</h3>



<p>The <code>//</code> floor division operator is not directly related to boolean operators. It&#8217;s an arithmetic operator that performs division and rounds the result down to the nearest integer. However, you can use it in boolean expressions as part of a condition, like any other operator.</p>



<p>Example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 9
y = 4

is_divisible = x // y == 2
print(is_divisible) # True
</pre>
<p>The post <a href="https://blog.finxter.com/boolean-operators-in-python-and-or-not-mastering-logical-expressions/">Boolean Operators in Python (and, or, not): Mastering Logical Expressions</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>&#8220;is&#8221; vs &#8220;==&#8221; Python Identity and Equality</title>
		<link>https://blog.finxter.com/is-vs-python-identity-and-equality/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 20 Nov 2022 08:13:24 +0000</pubDate>
				<category><![CDATA[Object Orientation]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Keywords]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=908308</guid>

					<description><![CDATA[<p>💬 Question: What is the difference between Python&#8217;s is and == operators? Answer The Python &#8220;==&#8221; operator compares equality of values whereas the Python &#8220;is&#8221; operator compares identity of objects, i.e., do the two operands point to the same object in memory. For example, the expression [1, 2, 3] == [1, 2, 3] returns True ... <a title="&#8220;is&#8221; vs &#8220;==&#8221; Python Identity and Equality" class="read-more" href="https://blog.finxter.com/is-vs-python-identity-and-equality/" aria-label="Read more about &#8220;is&#8221; vs &#8220;==&#8221; Python Identity and Equality">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/is-vs-python-identity-and-equality/">&#8220;is&#8221; vs &#8220;==&#8221; Python Identity and Equality</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-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: What is the difference between Python&#8217;s <code>is</code> and <code>==</code> operators?</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-212-1024x683.png" alt="" class="wp-image-908402" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-212-1024x683.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/image-212-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/image-212-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/image-212.png 1100w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


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



<p class="has-global-color-8-background-color has-background"><strong>The Python &#8220;<code>==</code>&#8221; operator compares <em>equality</em> of values whereas the Python &#8220;<code>is</code>&#8221; operator compares <em>identity</em> of objects, i.e., do the two operands point to the same object in memory. </strong></p>



<p>For example, the expression <code>[1, 2, 3] == [1, 2, 3]</code> returns <code>True</code> because both lists contain the same elements, they are <strong><em>equal</em></strong>. But the expression <code>[1, 2, 3]</code> is <code>[1, 2, 3]</code> returns <code>False</code> because they are two different lists that point to different objects in memory, they are <strong><em>not identical</em></strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False</pre>



<p>However, the expression <code>123 == 123</code> returns <code>True</code> because both integers are the same. And the expression <code>123 is 123</code> will also return <code>True</code> because the values point to the same object in memory!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 123 == 123
True
>>> 123 is 123
True</pre>



<p>Feel free to dive into both tutorials to learn about the <code>is</code> and <code>==</code> operators. But we&#8217;ll give a short intro at the end of this article too!</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-213-1024x682.png" alt="" class="wp-image-908404" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-213-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/image-213-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/image-213-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/image-213.png 1100w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p><strong>Recommended Tutorials:</strong></p>



<ul class="wp-block-list">
<li><a href="https://blog.finxter.com/python-is-operator/" data-type="post" data-id="33954" target="_blank" rel="noreferrer noopener">Python <code>is</code> Operator</a></li>



<li><a href="https://blog.finxter.com/python-equal-to/" data-type="post" data-id="31075" target="_blank" rel="noreferrer noopener">Python <code>==</code> Operator</a></li>
</ul>



<p>Before you learn about the important concept of <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">mutable and immutable objects</a> in Python, as well as about both of those operators, feel free to check out our <strong>memory visualizer</strong> tool first:</p>



<h2 class="wp-block-heading">Try It Yourself Example &#8211; Memory Visualization &#8220;is&#8221; vs &#8220;==&#8221;</h2>



<p>You can try our interactive memory visualization by clicking &#8220;Next&#8221; to see how identity and equality are two different concepts:</p>



<iframe loading="lazy" width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=lst_1%20%3D%20%5B1,%202,%203%5D%0Alst_2%20%3D%20%5B1,%202,%203%5D%0A%0Aprint%28lst_1%20%3D%3D%20lst_2%29%0A%23%20True%0A%0Aprint%28lst_1%20is%20lst_2%29%0A%23%20False%0A%0A%23%20Change%20one%20list%3A%0Alst_1.append%284%29%0A%0Aprint%28lst_1%29%0A%23%20%5B1,%202,%203,%204%5D%0A%0Aprint%28lst_2%29%0A%23%20%5B1,%202,%203%5D%0A%0Aprint%28lst_1%20%3D%3D%20lst_2%29%0A%23%20False&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=2&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false"> </iframe>



<p>Here&#8217;s the code for copy&amp;paste:</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="">lst_1 = [1, 2, 3]
lst_2 = [1, 2, 3]

print(lst_1 == lst_2)
# True

print(lst_1 is lst_2)
# False</pre>



<p>If you change one list, the other won&#8217;t be affected by the change. After changing the initially equal but non-identical list, they become non-equal and non-identical:</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=""># Change one list:
lst_1.append(4)

print(lst_1)
# [1, 2, 3, 4]

print(lst_2)
# [1, 2, 3]

print(lst_1 == lst_2)
# False
</pre>



<p>Similarly, you can check out equality and identity for integers where it works differently:</p>



<iframe loading="lazy" width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=val_1%20%3D%20123%0Aval_2%20%3D%20123%0A%0Aprint%28val_1%20%3D%3D%20val_2%29%0A%23%20True%0A%0Aprint%28val_1%20is%20val_2%29%0A%23%20True&#038;codeDivHeight=400&#038;codeDivWidth=350&#038;cumulative=false&#038;curInstr=4&#038;heapPrimitives=nevernest&#038;origin=opt-frontend.js&#038;py=3&#038;rawInputLstJSON=%5B%5D&#038;textReferences=false"> </iframe>



<p>Here&#8217;s the code for copy&amp;paste:</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="">val_1 = 123
val_2 = 123

# Equality:
print(val_1 == val_2)
# True

# Identity:
print(val_1 is val_2)
# True
</pre>



<p>Let&#8217;s quickly recap the <code>is</code> and <code>==</code> operators, you can watch our two video tutorials on both operators to keep improving your understanding of Python basics! <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">Python &#8220;is&#8221; Operator</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="727" height="911" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-214.png" alt="" class="wp-image-908408" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-214.png 727w, https://blog.finxter.com/wp-content/uploads/2022/11/image-214-239x300.png 239w" sizes="auto, (max-width: 727px) 100vw, 727px" /></figure>
</div>


<p>The Python <code>is</code> keyword tests if the left and right operands refer to the same object—in which case it returns <code>True</code>. </p>



<p>It returns <code>False</code> if they are not the same object, even if the two objects are equal. </p>



<p>For example, the expression <code>[1, 2, 3] is [1, 2, 3]</code> returns <code>False</code> because although both lists are equal, they are two independent objects in memory.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python &quot;is&quot; and &quot;is not&quot; Operators" width="937" height="527" src="https://www.youtube.com/embed/fZxf0a3ryJw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-is-operator/" data-type="URL" data-id="https://blog.finxter.com/python-is-operator/" target="_blank" rel="noreferrer noopener">Python is Operator — Checking Identity</a></p>



<h2 class="wp-block-heading">Python &#8220;==&#8221; Operator</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="604" height="911" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-215.png" alt="" class="wp-image-908409" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-215.png 604w, https://blog.finxter.com/wp-content/uploads/2022/11/image-215-199x300.png 199w" sizes="auto, (max-width: 604px) 100vw, 604px" /><figcaption class="wp-element-caption"><em><strong>Image</strong>: Equal but not the same!</em></figcaption></figure>
</div>


<p>The Python equal to (<code>left==right</code>) operator returns <code>True</code> when its <code>left</code> operand is equal to its <code>right</code> operand. Otherwise, it returns <code>False</code>. </p>



<p>For example, <code>3==3</code> evaluates to <code>True</code>, but <code>3==2</code> evaluates to <code>False</code>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Equal To Operator Deep Dive" width="937" height="527" src="https://www.youtube.com/embed/79wEqZkJ0b0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-equal-to/" data-type="URL" data-id="https://blog.finxter.com/python-equal-to/" target="_blank" rel="noreferrer noopener">Python Equal To Operator — Checking Equality</a></p>



<h2 class="wp-block-heading">A Word on Mutability</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="759" height="912" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-216.png" alt="" class="wp-image-908413" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-216.png 759w, https://blog.finxter.com/wp-content/uploads/2022/11/image-216-250x300.png 250w" sizes="auto, (max-width: 759px) 100vw, 759px" /></figure>
</div>


<p>Why are some variables compared using equality and others using identity?</p>



<p>The reason why two equal lists are considered <em>equal but not necessarily identical</em> and two equal numbers are considered <em>equal but necessarily identical</em> is that lists are <strong>mutable</strong> (they can be changed) and integers are <strong>immutable</strong> (they cannot be changed). </p>



<p>As you can change a list object, Python must create two list objects even if they contain the same elements. Why? Because you may change one list in your code and the change should not affect the other list.</p>



<p>Well &#8212; you <strong><em>cannot</em></strong> change objects such as integers or strings. </p>



<p>So, Python may decide to optimize for memory and let both variables point to the same object in memory. No variable pointing to that immutable object can ever change the object. Thus, there is no risk of <strong><em>aliasing</em></strong> where one variable is changed and the change is visible at the other variable too.</p>



<p>You can learn more about mutable vs immutable objects in the following video:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Mutable vs. Immutable Objects in Python" width="937" height="527" src="https://www.youtube.com/embed/FSE3Jp6hbss?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><strong>Recommended Finxter Tutorials:</strong></p>



<ul class="wp-block-list">
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="URL" data-id="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" target="_blank">Python Mutable vs Immutable Objects</a> (1/2)</li>



<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-mutable-vs-immutable-objects-in-python/" data-type="post" data-id="66189" target="_blank">Python Mutable vs Immutable Objects</a> (2/2)</li>
</ul>



<h2 class="wp-block-heading">When to Use Which &#8220;==&#8221; vs &#8220;is&#8221;?</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="608" height="912" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-217.png" alt="" class="wp-image-908418" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-217.png 608w, https://blog.finxter.com/wp-content/uploads/2022/11/image-217-200x300.png 200w" sizes="auto, (max-width: 608px) 100vw, 608px" /></figure>
</div>


<p>Use the <strong>equality operator</strong> <code>==</code> when comparing whether a certain variable has obtained a certain value. In fact, you&#8217;ll use the <code>==</code> operator in the vast majority of cases in <code>if</code> conditions, <code><a href="https://blog.finxter.com/python-one-line-while-loop-a-simple-tutorial/" data-type="post" data-id="11338" target="_blank" rel="noreferrer noopener">while</a></code> loops, or <a href="https://blog.finxter.com/python-one-line-ternary/" data-type="post" data-id="10641" target="_blank" rel="noreferrer noopener">ternary operators</a>. Each time you must know if a variable has obtained a certain value programmatically or by means of user input, you&#8217;ll use the <code>==</code> operator.</p>



<p>Use the <strong>identity operator</strong> <code>is</code> when comparing whether two variables refer to the same object. This is usually only done in debugging when you want to uncover some <a href="https://en.wikipedia.org/wiki/Aliasing_(computing)" data-type="URL" data-id="https://en.wikipedia.org/wiki/Aliasing_(computing)" target="_blank" rel="noreferrer noopener">aliasing problems</a> etc., i.e., whether the change of one variable unexpectedly results in a change of another variable. Outside of debugging, you&#8217;ll seldomly use the identity operator.</p>



<p>The most frequent use of the identity operator would be comparing a value to <code>None</code>, i.e., you would write</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if x is None:
    print('hello')</pre>



<p>and not</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if x == None:
    print('hello')</pre>



<p>The reason is that there is only one instance of the <code>None</code> type, the <code>None</code> object itself. All variables set to <code>None</code> would point to the same <code>None</code> object in memory. There cannot be two variables that point to different <code>None </code>objects.</p>



<h2 class="wp-block-heading">Thanks for Reading this Tutorial <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2764.png" alt="❤" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p>If you want to keep learning, feel free to download my cheat sheets&#8212;they are 100% free and super helpful, promised!</p>



<p>The post <a href="https://blog.finxter.com/is-vs-python-identity-and-equality/">&#8220;is&#8221; vs &#8220;==&#8221; Python Identity and Equality</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Check If a Number is Between Two Numbers in Python</title>
		<link>https://blog.finxter.com/check-if-a-number-is-between-two-numbers-in-python/</link>
		
		<dc:creator><![CDATA[Shubham Sayon]]></dc:creator>
		<pubDate>Tue, 20 Sep 2022 18:36:57 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python One-Liners]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=699542</guid>

					<description><![CDATA[<p>Problem Formulation You have been given a number. How will you check if the number lies between two numbers? 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 ... <a title="Check If a Number is Between Two Numbers in Python" class="read-more" href="https://blog.finxter.com/check-if-a-number-is-between-two-numbers-in-python/" aria-label="Read more about Check If a Number is Between Two Numbers in Python">Read more</a></p>
<p>The post <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> 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>You have been given a number. How will you check if the number lies between two numbers?</p>



<p>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. Here&#8217;s an example that demonstrates the problem:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Example 1:</strong> <br>Is 25 between 15 and 35?<br><strong>Output: </strong>True<br><strong>Example 2</strong>:<br>Is 0.5 between 1 and 5?<br><strong>Output: </strong>False<br><strong>Example 3</strong>:<br>Is 10 between 10 and 20?<br><strong>Output: </strong>True</td></tr></tbody></table></figure>



<p>That explains the given problem. We will have a look at few other conditions and examples. But before we discuss complex scenarios, let us dive into the solutions to the given question.</p>



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



<p>Python comparison operators can compare numerical values such as integers and floats in Python. The operators are: equal to ( == ), not equal to ( != ), greater than ( &gt; ), less than ( &lt; ), less than or equal to ( &lt;= ), and greater than or equal to ( &gt;= ).</p>



<p>Thus, you can use the &lt;= and the &gt;= operators to check if a number lies between the upper limit (maximum number) and lower limit(minimum number).</p>



<p><strong>Code:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(15 &lt;= 25 &lt; 35)  # True
print(1 &lt;= 0.5 &lt; 5)  # False
print(10 &lt;= 10 &lt; 20)  # True</pre>



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



<p>The second way of checking whether a value lies between two other values is quite similar to the one used above. The only difference, in this case, is to use the <em>and </em>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>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"><strong>Method 3: Using &#8220;<a href="https://blog.finxter.com/python-membership-in-operator/" target="_blank" rel="noreferrer noopener">in</a>&#8221; Keyword with range() Function</strong></h2>



<p>You can use the <code>range()</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>in</strong> keyword to check it. So, if the number lies in the specified range then the output will be &#8220;<em>True</em>&#8221; else &#8220;<em>False</em>&#8220;.</p>



<p><strong>Code: </strong></p>



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



<p>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: <strong><a href="https://blog.finxter.com/python-range-function/" target="_blank" rel="noreferrer noopener">Python range() Function — A Helpful Illustrated Guide</a></strong></p>



<p><strong>TIDBIT:</strong></p>



<p>Python’s “<code>in</code>” operator is a reserved <a rel="noreferrer noopener" href="https://blog.finxter.com/python-cheat-sheet/" target="_blank">keyword </a>to test membership of the left operand in the collection defined as the right operand. 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. You can check membership using the “<code>in</code>” operator in collections such as <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">lists</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/sets-in-python/" target="_blank">sets</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" target="_blank">strings</a>, and <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank">tuples</a>.</p>



<figure class="wp-block-image size-full is-style-default"><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" /></figure>



<h2 class="wp-block-heading"><strong>Exercises</strong></h2>



<p>Before we wrap up our discussion, let&#8217;s discuss some other variations of the given problem to further stregthen our grip on the concept. </p>



<p><strong>Challenge 1:</strong> How will you check if an alphabet lies between two other alphabets or not based on the alphabetical order of English language?</p>



<p><strong>Example: </strong>When you check if the alphabet &#8220;Y&#8221; lies between &#8220;X&#8221; and &#8220;Z&#8221; or not, the output should be &#8220;True&#8221;.</p>



<p><strong>Solution: </strong></p>



<p>Python comparison operators can also compare strings in Python. The comparison ordering is given by the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-ord-function/" target="_blank">ord()</a></code> function that returns the Unicode integer for a given character <code>c</code>. The operators that can be used are: equal to ( == ), not equal to ( != ), greater than ( &gt; ), less than ( &lt; ), less than or equal to ( &lt;= ), and greater than or equal to ( &gt;= ). </p>



<p>We will be using the &lt; and &gt; operators to solve the programming challenge.</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("X" &lt; "Y" &lt; "Z")  # True
# In case you want to ignore the case (make the letters case-insensitive)
print("x".upper() &lt; "Y".upper() &lt; "z".upper()) # True</pre>



<p><strong>Challenge 2: </strong>Consider a real-time scenario where you have to allocate a specific grade to a student based on the marks obtained by him/her. Here’s the grade allocation table that determines the range of marks that correspond to a certain grade:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Marks</td><td>Grade</td></tr><tr><td>91-100</td><td>A+</td></tr><tr><td>81-90</td><td>A</td></tr><tr><td>71-80</td><td>B</td></tr><tr><td>61-70</td><td>C</td></tr><tr><td>40-60</td><td>D</td></tr><tr><td>0-39</td><td>Fail</td></tr></tbody></table></figure>



<p>How will you use the above grading system and allocate the appropriate grade to a student based on the marks received? Let’s have a quick look at three examples that explain the desired goal of the given problem. </p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Input: marks = 90</strong><br><strong>Output: </strong>“Grade A”<br><br><strong>Input: </strong>marks = 55<br><strong>Output: </strong>“Grade D”<br><br><strong>Input: </strong>marks = 10<br><strong>Output: </strong>“Fail”</td></tr></tbody></table></figure>



<p><strong>Question: </strong>Can you formulate a one-liner code snippet that solves the programming challenge?</p>



<p><strong>Solution:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">marks = 95
# One-liner
grade = 'Grade: A+' if marks &gt; 90 else 'Grade: A' if marks &gt; 80 else 'Grade: B' if marks &gt; 70 else 'Grade: C' if marks &gt; 60 else 'Grade = D' if marks &gt; 39 else 'Fail'
# Result
print(grade)
# Grade: A+</pre>



<p>This solution is a classic example of using a nested ternary operator. Let’s examine the one-liner to understand how it works.</p>



<p>If the value of marks is greater than 90, we print &#8216;Grade: A+&#8217; on the shell. Otherwise, the remainder of the code gets executed, which represents a ternary operator by itself. The next condition gets evaluated and if the value of marks is greater than 80, we print &#8216;Grade: A&#8217; on the shell. This is how each condition gets evaluated until a certain condition is <strong>True. </strong>Thus, if the value of marks is less than 80, then the next condition gets evaluated. Hence, if the value of marks is greater than 70, we print &#8216;Grade: B&#8217; on the shell. Otherwise, the next condition is executed. If the value is greater than 60, we print &#8216;Grade: C&#8217; on the shell. Otherwise, we move on to the next condition and if the value of marks is greater than 39, we print &#8216;Grade: D&#8217; on the shell. Otherwise, the final else block is evaluated and we print &#8216;Grade: D&#8217; on the shell.</p>



<p><strong>Challenge 3: </strong>Examine the snippet given below and guess the output:</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="">num1 = float('Inf')
num2 = float('-Inf')
print(num1 &lt;= float('Inf') &lt;= num2)</pre>



<p><strong>Answer: </strong>You cannot compare two Positive Infinite values with each other. Similarly, you cannot compare two Negative Infinite values with each other. Hence, the output will be <strong>False</strong>.</p>



<p class="has-base-background-color has-background">Read More: <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/python-infinity/" target="_blank">Python Infinity </a></strong></p>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p>I hope this article answers all your queries. Please <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a></strong> and stay tuned for more interesting discussions. Meanwhile, you may want to have a look at this comprehensive guide to comparison operators in Python: <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/python-comparison-operators" target="_blank">Python Comparison Operators [Blog + Videos]</a></strong>.</p>



<p>Happy coding! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <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> 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 Repeat a String Multiple Times in Python</title>
		<link>https://blog.finxter.com/how-to-repeat-a-string-multiple-times-in-python/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Fri, 29 Jul 2022 00:42:37 +0000</pubDate>
				<category><![CDATA[Input/Output]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Operators]]></category>
		<category><![CDATA[Python String]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=519561</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview In this article, you&#8217;ll learn how to repeat a string multiple times in Python. Over your career as a Python coder, you will encounter situations when a string needs to be output/displayed a specified number of times. The examples below offer you various ways to accomplish this task. 💬 Question: ... <a title="How to Repeat a String Multiple Times in Python" class="read-more" href="https://blog.finxter.com/how-to-repeat-a-string-multiple-times-in-python/" aria-label="Read more about How to Repeat a String Multiple Times in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-repeat-a-string-multiple-times-in-python/">How to Repeat a String Multiple Times 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[
<h2 class="wp-embed-aspect-4-3 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-4-3 wp-has-aspect-ratio">In this article, you&#8217;ll learn how to repeat a string multiple times in Python.</p>



<p><em>Over your career as a Python coder, you will encounter situations when a string needs to be output/displayed a specified number of times. The examples below offer you various ways to accomplish this task.</em></p>



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



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write Python code that repeats a string multiple times?</em></p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>



<ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-list"><li><strong>Method 1</strong>: Use  <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> and an <a rel="noreferrer noopener" href="https://blog.finxter.com/python-arithmetic-operators/" data-type="URL" data-id="https://blog.finxter.com/python-arithmetic-operators/" target="_blank"><code>arithmetic operator</code></a></li><li><strong>Method 2</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a> Loop and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-range-function/" data-type="URL" data-id="https://blog.finxter.com/python-range-function/" target="_blank"><code>range()</code></a></li><li><strong>Method 3</strong>: Use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-input-function/" data-type="URL" data-id="https://blog.finxter.com/python-input-function/" target="_blank"><code>input()</code></a> function</li><li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="URL" data-id="https://blog.finxter.com/iterators-iterables-and-itertools/" target="_blank"><code>itertools.repeat()</code></a></li><li><strong>Method 5</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" target="_blank"><code>Pandas</code></a> DataFrame</li></ul>



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



<h2 class="wp-block-heading">Method 1: Use print() and multiplication operator</h2>



<p class="has-global-color-8-background-color has-background">This method uses Python&#8217;s built-in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> statement combined with a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-arithmetic-operators/" data-type="URL" data-id="https://blog.finxter.com/python-arithmetic-operators/" target="_blank"><code>multiplication operator</code></a> to output a string multiple times.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">saying = 'Wash. Rinse. Repeat!\t'
print(saying * 3)</pre>



<p>Above declares the string &#8216;<code>Wash. Rinse. Repeat!</code>&#8216; followed by a tab character, also known as an <a rel="noreferrer noopener" href="https://blog.finxter.com/python-escape-characters/" data-type="URL" data-id="https://blog.finxter.com/python-escape-characters/" target="_blank">escape character</a> (<code>\t</code>). The results save to <code>saying</code>.</p>



<p>Next, the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> statement outputs the <code>saying </code>three (3) times, with the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-escape-characters/" data-type="URL" data-id="https://blog.finxter.com/python-escape-characters/" target="_blank">escape character</a> (<code>\t</code>) between each <code>saying </code>on the same line.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code>Wash. Rinse. Repeat!    Wash. Rinse. Repeat!    Wash. Rinse. Repeat!</code></td></tr></tbody></table></figure>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Multiplication - Deep Dive" width="937" height="527" src="https://www.youtube.com/embed/EaOwCDCrl0g?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



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



<h2 class="wp-block-heading">Method 2: Use a For Loop and range()</h2>



<p class="has-global-color-8-background-color has-background">This method uses a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop with the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-range-function/" data-type="URL" data-id="https://blog.finxter.com/python-range-function/" target="_blank"><code>range()</code></a> function to iterate and output a string a set number of times.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for i in range(3):
    print('I never want to grow up!')</pre>



<p>Above instantiates a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a> loop with the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-range-function/" data-type="URL" data-id="https://blog.finxter.com/python-range-function/" target="_blank"><code>range()</code></a>  function. This function accepts a start position (not required), a stop position (required) and a step (not required). The start position is always zero (<code>0</code>) unless otherwise stated. The stop position is always stop-1.</p>



<p>The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> statement outputs a line to the terminal, with each iteration as shown below.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code>I never want to grow up!<br>I never want to grow up!<br>I never want to grow up!</code></td></tr></tbody></table></figure>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python range() Function | A Helpful Illustrated Guide" width="937" height="527" src="https://www.youtube.com/embed/vcu2Q-6sr-Q?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



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



<h2 class="wp-block-heading">Method 3: Use the <code>input()</code> function</h2>



<p class="has-global-color-8-background-color has-background">This method prompts the user to enter a specified number of times to repeat a string using the <code><a href="https://blog.finxter.com/python-int-function/" data-type="post" data-id="22715" target="_blank" rel="noreferrer noopener">int()</a></code> and <code><a href="https://blog.finxter.com/python-input-function/" data-type="post" data-id="24632" target="_blank" rel="noreferrer noopener">input()</a></code> functions.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = int(input('Number of times to repeat a string? '))
print('Hello World!\n' * num)</pre>



<p>Above, prompts the user to enter how many times a string will display. Their answer is converted to an integer (<code>int()</code>) and saved to <code>num</code>.</p>



<p>Next, the string &#8216;<code>Hello World</code>&#8216; is output to the terminal. The newline character is appended (<code>\n</code>) so the output displays on a new line each time.</p>



<p>For this example, the number three (3) was entered.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code>Hello World!<br>Hello World!<br>Hello World!</code></td></tr></tbody></table></figure>



<p class="has-global-color-8-background-color has-background"><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;" />Note: The newline character (<code>\n</code>) caused the last line (line 3) to have an additional blank line.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python input() Function [6-Minute Primer]" width="937" height="527" src="https://www.youtube.com/embed/5CtmbtHk8QI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



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



<h2 class="wp-block-heading">Method 4: Use itertools.repeat()</h2>



<p class="has-global-color-8-background-color has-background">This method uses Python&#8217;s built-in library <code><a rel="noreferrer noopener" href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="URL" data-id="https://blog.finxter.com/iterators-iterables-and-itertools/" target="_blank">itertools</a></code> to call the <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/itertools.html" data-type="URL" data-id="https://docs.python.org/3/library/itertools.html" target="_blank">repeat()</a></code> function, which repeats a number or a string a stated number of times.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import itertools   
print(list(itertools.repeat('HELP ME', 3)))</pre>



<p>Above, imports the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="URL" data-id="https://blog.finxter.com/iterators-iterables-and-itertools/" target="_blank">itertools</a></code> library.</p>



<p>Then, the <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/itertools.html" data-type="URL" data-id="https://docs.python.org/3/library/itertools.html" target="_blank">repeat()</a></code> function is called and passed two (2) arguments: the string to repeat and the number of times to repeat. This is then converted to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> and output to the terminal.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code>['HELP ME', 'HELP ME', 'HELP ME']</code></td></tr></tbody></table></figure>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Iterators, Iterables and Itertools" width="937" height="527" src="https://www.youtube.com/embed/Yyliq2-hVDw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



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



<h2 class="wp-block-heading">Method 5: Use a DataFrame</h2>



<p class="has-global-color-8-background-color has-background">This method uses a DataFrame and an empty column to assign a default value.</p>



<p>The <a rel="noreferrer noopener" href="https://blog.finxter.com/category/pandas-library/" target="_blank"><code>Pandas</code></a> library must be installed and imported to run this code error-free. Click <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-on-pycharm/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-on-pycharm/" target="_blank">here</a><a href="https://blog.finxter.com/how-to-install-regex-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-regex-in-python/"> </a>for installation instructions. </p>



<p>To follow along, click <a rel="noreferrer noopener" href="https://blog.finxter.com/wp-content/uploads/2022/01/finxter.csv" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2022/01/finxter.csv" target="_blank">here</a> to download the <code>finxters.csv</code> file and move this file to the current working directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2-3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd 
df = pd.read_csv('finxters.csv', usecols=['FID', 'First_Name', 'Last_Name'])
df['Award'] = 'TBD'
df.to_csv('finxter1.csv')
print(df.head(3))</pre>



<p>Above, imports the <a rel="noreferrer noopener" href="https://blog.finxter.com/category/pandas-library/" data-type="URL" data-id="https://blog.finxter.com/category/pandas-library/" target="_blank"><code>Pandas</code></a> library to <a href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="post" data-id="440655" target="_blank" rel="noreferrer noopener">read in the CSV file</a> and work with a DataFrame.</p>



<p>Then, only a few columns of <code>finters.csv</code> are read into the DataFrame <code>df</code>.</p>



<p>Next, the DataFrame <code>df </code> is saved to a new CSV file, <code>finxters1.csv</code> and placed in the current working directory.</p>



<p>Finally, the output is sent to the terminal. For this example, only three (3) rows are displayed.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td>FID</td><td>First_Name</td><td>Last_Name</td><td>Award</td></tr><tr><td>0</td><td>30022145</td><td>Steve</td><td>Hamilton</td><td>TBD</td></tr><tr><td>1</td><td>30022192 </td><td>Amy</td><td>Pullister</td><td>TBD</td></tr><tr><td>2</td><td>30022331</td><td>Peter</td><td>Dunn </td><td>TBD</td></tr></tbody></table></figure>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="10 Minutes to Pandas in 5 Minutes (Okay 8)" width="937" height="527" src="https://www.youtube.com/embed/-JKVy_HliQE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



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



<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Summary</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">These five (5) methods of printing a string multiple times should give you enough information to select the best one for your coding requirements.</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Good Luck &amp; Happy Coding!</p>



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



<h2 class="wp-block-heading">Regex Humor</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-133.png" alt="" class="wp-image-428862" width="700" height="629" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-133.png 785w, https://blog.finxter.com/wp-content/uploads/2022/06/image-133-300x270.png 300w, https://blog.finxter.com/wp-content/uploads/2022/06/image-133-768x691.png 768w" sizes="auto, (max-width: 700px) 100vw, 700px" /><figcaption><em>Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.</em> (<a href="https://imgs.xkcd.com/comics/regular_expressions.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/regular_expressions.png" target="_blank" rel="noreferrer noopener">source</a>)</figcaption></figure>
</div>


<p></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-repeat-a-string-multiple-times-in-python/">How to Repeat a String Multiple Times 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>Python&#8217;s &#038;&#038; Equivalent: Logical And</title>
		<link>https://blog.finxter.com/what-is-pythons-equivalent-of-logical-and-in-an-if-statement/</link>
		
		<dc:creator><![CDATA[Shubham Sayon]]></dc:creator>
		<pubDate>Sun, 06 Feb 2022 09:31:49 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=174864</guid>

					<description><![CDATA[<p>In Python, the equivalent of &#38;&#38; (logical-and) in programming languages such as C++ or Java in an if-statement is and. Using &#38;&#38; will raise a SyntaxError, so use and instead! Overview Problem: What is the equivalent of &#38;&#38;(logical-and) in Python? Example: Let&#8217;s have a look at the following example: Output: You will get the following ... <a title="Python&#8217;s &#038;&#038; Equivalent: Logical And" class="read-more" href="https://blog.finxter.com/what-is-pythons-equivalent-of-logical-and-in-an-if-statement/" aria-label="Read more about Python&#8217;s &#038;&#038; Equivalent: Logical And">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/what-is-pythons-equivalent-of-logical-and-in-an-if-statement/">Python&#8217;s &#038;&#038; Equivalent: Logical And</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-global-color-8-background-color has-background">In Python, the equivalent of <code>&amp;&amp;</code> (logical-and) in programming languages such as C++ or Java in an if-statement is <code>and</code>. Using <code>&amp;&amp;</code> will raise a SyntaxError, so use <code>and</code> instead!</p>



<h2 class="wp-block-heading" id="overview"><strong>Overview</strong></h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="406" src="https://blog.finxter.com/wp-content/uploads/2022/02/logical-and-1024x406.png" alt="" class="wp-image-175011" srcset="https://blog.finxter.com/wp-content/uploads/2022/02/logical-and-1024x406.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/02/logical-and-300x119.png 300w, https://blog.finxter.com/wp-content/uploads/2022/02/logical-and-768x304.png 768w, https://blog.finxter.com/wp-content/uploads/2022/02/logical-and.png 1249w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>Problem: </strong>What is the equivalent of &amp;&amp;(logical-and) in Python?</p>



<p><strong>Example: </strong>Let&#8217;s have a look at the following example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3,5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num_1 = [11, 21, 31, 41, 51]
num_2 = [15, 16, 17, 18, 19, 20, 21]
if len(num_1) % 2 == 0 &amp;&amp; len(num_2) % 2 == 0:
    print("The lists has even number of elements")
elif len(num_1) % 2 != 0 &amp;&amp; len(num_2) % 2 != 0:
    print("odd numbers")
else:
    print("mix of odd and even numbers")</pre>



<p><strong>Output:</strong> You will get the following error inside the &#8220;if&#8221; statement.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="atomic" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    if len(num_1) % 2 == 0 &amp;&amp; len(num_2) % 2 == 0:
                            ^
SyntaxError: invalid syntax</pre>



<p>Well! This can be really frustrating. You have got the logic right, yet there&#8217;s an error. Why? The answer is not as difficult as you might have thought. </p>



<p class="has-contrast-color has-global-color-8-background-color has-text-color has-background">We encountered the syntax error because of the usage of <strong><code>&amp;&amp;</code></strong> operator in our code. Python does not have the provision for the <strong><code>&amp;&amp;</code></strong> operator. Hence, when Python comes across &#8220;<code>&amp;&amp;</code>&#8221; in the program, it is unable to identify the operator and deems it as invalid. Therefore, we see the<em> Syntax Error.</em> </p>



<p class="has-contrast-color has-base-background-color has-text-color has-background"><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><span style="text-decoration: underline">Instant Fix</span>: </strong>Replace the <code>&amp;&amp;</code> operator with <strong><code>and</code></strong>, which will solve the issue.</p>



<h2 class="wp-block-heading" id="logical-operators-in-python"><strong>Logical Operators in Python</strong></h2>



<p><strong>What are Operators in Python?</strong> Operators are the special symbols that are used to perform operations on the variables and values. They carry out arithmetic and logical computations. </p>



<p>The <strong>logical operators</strong> in Python are used on conditional statements, i.e, either <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code> or <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code>. The three logical operations are:</p>



<ul class="wp-block-list">
<li>(i) Logical AND</li>



<li>(ii) Logical OR </li>



<li>(iii) Logical NOT.</li>
</ul>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><th>Operator</th><th>Description</th><th>Example</th></tr><tr><td><code><a href="https://blog.finxter.com/python-and-operator/" target="_blank" rel="noreferrer noopener">and</a></code></td><td>Returns&nbsp;<code>True</code>&nbsp;if both operands are&nbsp;<code>True</code>, and&nbsp;<code>False</code>&nbsp;otherwise.</td><td><code>(True and True) == True</code></td></tr><tr><td><code><a href="https://blog.finxter.com/python-or-operator/" target="_blank" rel="noreferrer noopener">or</a></code></td><td>Returns&nbsp;<code>True</code>&nbsp;if one operand is&nbsp;<code>True</code>, and otherwise it returns&nbsp;<code>False</code>.</td><td><code>(False or True) == True</code></td></tr><tr><td><code><a href="https://blog.finxter.com/python-not-operator/" target="_blank" rel="noreferrer noopener">not</a></code></td><td>Returns&nbsp;<code>True</code>&nbsp;if the single operand is&nbsp;<code>False</code>, otherwise returns <code>False</code>.</td><td><code>(not True) == False</code></td></tr></tbody></table></figure>



<h3 class="wp-block-heading" id="logical-and"><strong>Logical AND</strong></h3>



<p>The Logical AND operator is used to return <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code> if both operands are <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code>. However, if any one of the two operands is <code data-enlighter-language="csharp" class="EnlighterJSRAW">False</code>, then it returns False. </p>



<p>Let&#8217;s look at an example to understand this:</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=""># functioning of Logical and operator
val_1 = -5
val_2 = 10  
if val_1 > 0 and val_2 > 0:
    print("The numbers are positive numbers")
elif val_1 &lt; 0 and val_2 &lt; 0:
    print("The numbers are negative numbers")
else:
    print("One of the given numbers is positive while the other number is negative!")</pre>



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">One of the given numbers is positive while the other number is negative!</pre>



<p>Now let&#8217;s get back to our first example. When we replace the <strong><code>&amp;&amp;</code></strong> with <strong><code>and</code></strong> the error gets solved.</p>



<p><strong>Solution:</strong></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="">val_1 = [11, 21, 31, 41, 51]
val_2 = [15, 16, 17, 18, 19, 20, 21]
# Using logical and
if len(val_1) % 2 == 0 and len(val_2) % 2 == 0:
    print("List has Even number of elements.")
elif len(val_1) % 2 != 0 and len(val_2) % 2 != 0:
    print("List has odd number of elements.")
else:
    print("List 1 has Odd number of elements while list 2 has even number of elements!")</pre>



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">List has odd number of elements.</pre>



<p>Hence, <strong>&#8220;<code>and</code>&#8221; is Python&#8217;s equivalent of <code>&amp;&amp;</code> (logical-and) in an if-statement</strong>. In the same way, we cannot use the <strong><code>||</code></strong> operator in Python as it is not valid. We have to use its equivalent logical or which is denoted by &#8220;<strong><code>or</code></strong>&#8221; in Python.</p>



<h3 class="wp-block-heading" id="logical-or"><strong>Logical OR</strong></h3>



<p>The Logical OR operator is used to return <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code> if either of the operands is <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code>. It returns <code data-enlighter-language="generic" class="EnlighterJSRAW">false</code> only if both of the operands are <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code>.&nbsp;</p>



<p>Let&#8217;s look at one example to understand this:</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=""># functioning of Logical or operator
num_1 = -5
num_2 = -10  
num_3 = 8
print("For the first two numbers:")
if num_1 > 0 or num_2 > 0:
    print("Either of the numbers is positive")
else:
    print("Numbers are negative numbers")
print("For the last two numbers")
if num_2 > 0 or num_3 > 0:
    print("Either of the numbers is positive")
else:
    print("Numbers are negative numbers")</pre>



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">For the first two numbers:
Numbers are negative numbers
For the last two numbers
Either of the numbers is positive</pre>



<h2 class="wp-block-heading" id="the-python-advantage-of-logical-operators"><strong>The Python Advantage of Logical Operators</strong></h2>



<p>Python is a way more user-friendly language. While you have to use symbols like &#8220;<code>&amp;&amp;</code>&#8221; and &#8220;<code>||</code>&#8221; in some other languages like <a rel="noreferrer noopener" href="https://blog.finxter.com/c-plus-plus-developer-income-and-opportunity/" data-type="post" data-id="196896" target="_blank">C++</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/java-developer-income-and-opportunity/" data-type="post" data-id="217907" target="_blank">Java</a>, Python makes life easy for you by providing direct words like &#8220;<code>and</code>&#8221; , &#8220;<code>or</code>&#8220;, etc which make more sense and resemble normal English.   </p>



<p>Further, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-logical-operators-blog-video/" data-type="post" data-id="33318" target="_blank">logical operators</a> (in most languages) have the advantage of being short-circuited. This means that it first evaluates the first operand, and if only the first operand defines the result, then the second operand is not evaluated at all.</p>



<p>Look at the following 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="">def check(v):
    print(v)
    return v
temp = check(False) and check(True)

# False</pre>



<p>In the above example, only one <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">print</a> statement is executed, i.e., Python evaluated only the first operand. As we know the <code data-enlighter-language="generic" class="EnlighterJSRAW">AND</code> operator returns <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code>, if one of the operands is <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code>. The first operand, in this case, was <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code> hence Python did not evaluate the second operand.  </p>



<p>However, let&#8217;s look at a different situation-</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="">def check(v):
    print(v)
    return v


print("Output for first call: ")
temp = check(True) and check(True)
print("Output for the second call:")
temp = check(True) and check(False)</pre>



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Output for first call: 
True
True
Output for the second call:
True
False</pre>



<p>In the above example, as the first operand is <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code> we cannot determine the result for the &#8220;<code data-enlighter-language="generic" class="EnlighterJSRAW">and</code>&#8221; operation. Hence, Python needs to evaluate the second operand as well.&nbsp;</p>



<p>It works similarly for the OR operand where Python first checks the first operand. As we know, the OR logical operator returns <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code> only if both of the operands are <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code>. So, if the first operand is <code data-enlighter-language="generic" class="EnlighterJSRAW">False</code> only then it evaluates the second operand. However, if the first operand is <code>True</code>, it concludes that the output is <code data-enlighter-language="generic" class="EnlighterJSRAW">True</code> without even checking the second operand. </p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Bonus: </strong>Pseudocode for AND and OR function is as follows:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="godzilla" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def and(oper1, oper2):
    left = evaluate(oper1)
    if bool(left):
        return evaluate(oper2)
    else:
        return left
def or(oper1, oper2):
    left = evaluate(oper1)
    if bool(left):
        return left
    else:
        return evaluate(oper2)</pre>



<h2 class="wp-block-heading" id="related-video"><strong>Related Video</strong></h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python And Operator - Deep Dive" width="937" height="527" src="https://www.youtube.com/embed/3uBRAbl6Tno?start=1&#038;feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading" id="related-questions"><strong>Related Questions</strong></h2>



<p>Here are some questions and their quick solution, which are frequently asked along with the problem discussed in this article &#8211;</p>



<h3 class="wp-block-heading" id="how-to-use-and-operator-to-check-equality-between-strings"><strong>How to use &#8220;and&#8221; operator to check equality between strings?</strong></h3>



<p><strong>Solution:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">word = "MADAM"
if word and word[::-1]:
    print("PALINDROME!")

# PALINDROME</pre>



<h3 class="wp-block-heading" id="what-is-the-replacement-for-switch-statement-in-python"><strong>What is the replacement for the switch statement in Python?</strong></h3>



<p><strong>Solution:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def switch(x):
    return {
        "1": 'One',
        "2": 'Two'
    }.get(x, "wrong entry!")


n = input("Enter your Choice: ")
print(switch(n))</pre>



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



<pre class="wp-block-preformatted"><code>Enter your Choice: 1
One</code></pre>



<h2 class="wp-block-heading" id="conclusion"><strong>Conclusion</strong></h2>



<p>In this article, we learned about the logical operators and<strong> Python&#8217;s equivalent of <code>&amp;&amp;</code> (logical-and) and <code>||</code> (logical-or) in an if-statement.</strong> I hope this article has helped you. Please stay tuned and <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a></strong> for more such articles.</p>



<p class="has-text-align-center has-background" style="background-color:#dbbebe"><strong>Recommended Read: <a href="https://blog.finxter.com/python-and-operator/" target="_blank" rel="noreferrer noopener">Python And Operator</a></strong></p>
<p>The post <a href="https://blog.finxter.com/what-is-pythons-equivalent-of-logical-and-in-an-if-statement/">Python&#8217;s &#038;&#038; Equivalent: Logical And</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 __init_subclass__() Magic Method</title>
		<link>https://blog.finxter.com/python-__init_subclass__-magic-method/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 10 Jan 2022 16:34:13 +0000</pubDate>
				<category><![CDATA[Dunder Methods]]></category>
		<category><![CDATA[Object Orientation]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=128830</guid>

					<description><![CDATA[<p>The Python class.__init_subclass__(cls) method is called on a given class each time a subclass cls for that class is created. Syntax class.__init_subclass__(cls) We call this a &#8220;Dunder Method&#8221; for &#8220;Double Underscore Method&#8221; (also called &#8220;magic method&#8221;). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this ... <a title="Python __init_subclass__() Magic Method" class="read-more" href="https://blog.finxter.com/python-__init_subclass__-magic-method/" aria-label="Read more about Python __init_subclass__() Magic Method">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-__init_subclass__-magic-method/">Python __init_subclass__() Magic Method</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>The Python <code>class.__init_subclass__(cls)</code> method is called on a given <code>class</code> each time a subclass <code>cls</code> for that class is created.</p>



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



<pre class="wp-block-preformatted"><code>class.__init_subclass__(cls)</code></pre>



<p>We call this a <em><a href="https://blog.finxter.com/python-list-of-dunder-methods/" title="Python List of Dunder Methods" target="_blank" rel="noreferrer noopener">&#8220;Dunder Method&#8221;</a></em> for <em>&#8220;<strong>D</strong>ouble <strong>Under</strong>score Method&#8221;</em> (also called <em>&#8220;magic method&#8221;</em>). To get a <a href="https://blog.finxter.com/python-list-of-dunder-methods/" target="_blank" rel="noreferrer noopener" title="Python List of Dunder Methods">list of all dunder methods</a> with explanation, check out our <a href="https://blog.finxter.com/python-dunder-methods-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="Python Dunder Methods Cheat Sheet">dunder cheat sheet article</a> on this blog.</p>



<h2 class="wp-block-heading">Minimal Example</h2>



<p>The following example shows how as soon as you create a subclass <code>Child</code> that <a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179" target="_blank" rel="noreferrer noopener">inherits</a> from a <code>Parent</code> class, the method <code>__init_subclass__()</code> is called.</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="">class Parent:
    def __init_subclass__(cls):
        print('Subclass of Parent Created!')

class Child(Parent):
    pass</pre>



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



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Subclass of Parent Created!</pre>



<p class="has-base-background-color has-background"><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;" /> <strong>Note</strong>: The method is called on the definition of the class and not on the creation of an instance of the class. For example, even if you created 1000 instances of <code>Child</code>, the method <code>__init_subclass__()</code> would be called only once on <code>Parent</code>.</p>



<h2 class="wp-block-heading">Class Hierarchy with __init_subclass__()</h2>



<p>What happens if a <strong>child of a child class is created&#8212;does it trigger another execution</strong> of <code>__init_subclass__()</code>? </p>



<p>The answer is yes!</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="">class Parent:
    def __init_subclass__(cls):
        print('Subclass of Parent Created!')

class Child(Parent):
    pass

class Grandchild(Child):
    pass
</pre>



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Subclass of Parent Created!
Subclass of Parent Created!</pre>



<h2 class="wp-block-heading">Precedence of Defining __init_subclass__() on Multiple Inheritance Levels</h2>



<p>If both a class and a subclass define the <code>__init_subclass__()</code> method and a subclass of the subclass is created. Which <code>__init_subclass__()</code> definition applies in this scenario?</p>



<p>The normal <strong><em>subclass hierarchy rules</em></strong> apply: The closest parent class wins! Python goes from children to parents searching for <code>__init_subclass__()</code>. The first occurrence of the method is called.</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="">class Parent:
    def __init_subclass__(cls):
        print('AAA')

class Child(Parent):
    def __init_subclass__(cls):
        print('BBB')

class Grandchild(Child):
    pass</pre>



<p><strong>Output:</strong></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="">AAA  # --> Output of Child()
BBB  # --> Output of Grandchild()</pre>



<h2 class="wp-block-heading">Background Inheritance</h2>



<p>Inheritance allows you to define a class that inherits all methods and properties from another class.</p>



<ul class="wp-block-list"><li><strong><em>Parent class</em></strong>, also denoted as <strong><em>base class</em></strong>, is the class you inherit from. In Python, every class can be a parent class.</li><li><strong><em>Child class</em></strong>, also denoted as <strong><em>derived class</em></strong>, inherits from the Parent class. In Python, you can create a child class that inherits all methods and attributes from the Parent using the <code><strong>class Child(Parent)</strong></code> syntax with the parent class enclosed in parentheses.</li></ul>



<p>You can watch our related video on inheritance here:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Five Types of Inheritance in Python" width="937" height="527" src="https://www.youtube.com/embed/M9kUpZOubBQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p> <strong>Learn more</strong> in our detailed articles: </p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179">Python Inherita</a><a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179" target="_blank" rel="noreferrer noopener">n</a><a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179">ce</a></li><li><a href="https://blog.finxter.com/understanding-inheritance-types-in-python/" data-type="post" data-id="31321" target="_blank" rel="noreferrer noopener">Five Types of Inheritance in Python</a></li></ul>
<p>The post <a href="https://blog.finxter.com/python-__init_subclass__-magic-method/">Python __init_subclass__() Magic Method</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 __subclasscheck__() Magic Method</title>
		<link>https://blog.finxter.com/python-__subclasscheck__-magic-method/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Mon, 27 Dec 2021 10:54:09 +0000</pubDate>
				<category><![CDATA[Dunder Methods]]></category>
		<category><![CDATA[Object Orientation]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<category><![CDATA[Python Operators]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=105892</guid>

					<description><![CDATA[<p>Syntax class.__subclasscheck__(self, subclass) Python&#8217;s class.__subclasscheck__(self, subclass) method implements the issubclass(subclass, class) built-in function. It should return True if subclass is a direct or indirect subclass of class using Python inheritance to define the subclass relationship. We call this a &#8220;Dunder Method&#8221; for &#8220;Double Underscore Method&#8221; (also called &#8220;magic method&#8221;). To get a list of all ... <a title="Python __subclasscheck__() Magic Method" class="read-more" href="https://blog.finxter.com/python-__subclasscheck__-magic-method/" aria-label="Read more about Python __subclasscheck__() Magic Method">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-__subclasscheck__-magic-method/">Python __subclasscheck__() Magic Method</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">Syntax</h2>



<pre class="wp-block-preformatted"><code>class.__subclasscheck__(self, subclass)</code></pre>



<p>Python&#8217;s <code>class.__subclasscheck__(self, subclass)</code> method implements the  <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-issubclass/" data-type="post" data-id="23648" target="_blank">issubclass(subclass, class)</a></code> built-in function. It should return <code>True</code> if <code>subclass</code> is a direct or indirect subclass of <code>class</code> using <a rel="noreferrer noopener" href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179" target="_blank">Python inheritance</a> to define the subclass relationship.</p>



<p>We call this a <em><a href="https://blog.finxter.com/python-list-of-dunder-methods/" title="Python List of Dunder Methods" target="_blank" rel="noreferrer noopener">&#8220;Dunder Method&#8221;</a></em> for <em>&#8220;<strong>D</strong>ouble <strong>Under</strong>score Method&#8221;</em> (also called <em>&#8220;magic method&#8221;</em>). To get a <a href="https://blog.finxter.com/python-list-of-dunder-methods/" target="_blank" rel="noreferrer noopener" title="Python List of Dunder Methods">list of all dunder methods</a> with explanation, check out our <a href="https://blog.finxter.com/python-dunder-methods-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="Python Dunder Methods Cheat Sheet">dunder cheat sheet article</a> on this blog.</p>



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



<p>In the following example, you create custom classes <code>Person</code>, <code>Friend</code>, <code>Parent</code>, and <code>Child</code>. Both <code>Parent</code> and <code>Friend</code> inherit from <code>Person</code>. <code>Child</code> inherits from <code>Parent</code>. Thus, per transitive inheritance, <code>Child</code> inherits from <code>Parent</code> as well. However, <code>Child</code> doesn&#8217;t inherit from <code>Friend</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="">class Person:
    pass

class Friend(Person):
    pass

class Parent(Person):
    pass

class Child(Parent):
    pass


# Is Child a Parent? Yes!
print(issubclass(Child, Parent))
# True

# Is Child a Friend? No!
print(issubclass(Child, Friend))
# False

# Is Child a Person? Yes!
print(issubclass(Child, Person))
# True
</pre>



<p>The <code>__subclasscheck__()</code> dunder method is implemented implicitly and by default. That&#8217;s why you don&#8217;t need to define it explicitly. However, if you do so, you can manipulate the output of these function calls!</p>



<p>To override the <code>__subclasscheck__</code> magic method, you need to define it on the <a href="https://blog.finxter.com/python-metaclasses/" data-type="post" data-id="13944" target="_blank" rel="noreferrer noopener">metaclass</a> as exemplified in <a rel="noreferrer noopener" href="https://www.python.org/dev/peps/pep-3119/#overloading-isinstance-and-issubclass" data-type="URL" data-id="https://www.python.org/dev/peps/pep-3119/#overloading-isinstance-and-issubclass" target="_blank">PEP 3119</a>. </p>



<p>This is how you&#8217;d override the <code>__subclasscheck__</code> magic method for our example to now return <code>False</code>, no matter what:</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="">class PersonMeta(type):
    def __subclasscheck__(self, subclass):
        return False
    
class Person(metaclass=PersonMeta):
    pass

class Friend(Person):
    pass

class Parent(Person):
    pass

class Child(Parent):
    pass


# Is Child a Person? Not anymore!
print(issubclass(Child, Person))
# False
</pre>



<p>Note that the same statement <code>print(issubclass(Child, Person))</code> previously <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">printed</a> True to the standard output&#8212;but with the override, it now prints <code>False</code>.</p>



<h2 class="wp-block-heading">Background issubclass()</h2>



<p>Python’s built-in <code>issubclass(X, Y)</code> function takes a class <code>X</code> and a class <code>Y</code> and returns <code>True</code> if the <code>X</code> is an instance of <code>Y</code> and otherwise <code>False</code>. The argument <code>Y</code> can also be a tuple in which case it checks whether <code>X</code> is a subclass of any class in the tuple—such as in <code>issubclass(X, (class_1, class_2, ...))</code>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python issubclass() -- A Simple Video Guide Into Class Inheritance" width="937" height="527" src="https://www.youtube.com/embed/A5lrHeVfAhc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p><strong>Learn more</strong> in our detailed article:</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/python-issubclass/" data-type="post" data-id="23648">Python <code>issubclass()</code></a></li></ul>



<h2 class="wp-block-heading">Background Inheritance</h2>



<p>Inheritance allows you to define a class that inherits all methods and properties from another class.</p>



<ul class="wp-block-list"><li><strong><em>Parent class</em></strong>, also denoted as <strong><em>base class</em></strong>, is the class you inherit from. In Python, every class can be a parent class.</li><li><strong><em>Child class</em></strong>, also denoted as <strong><em>derived class</em></strong>, inherits from the Parent class. In Python, you can create a child class that inherits all methods and attributes from the Parent using the <code><strong>class Child(Parent)</strong></code> syntax with the parent class enclosed in parentheses.</li></ul>



<p>You can watch our related video on inheritance here:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Five Types of Inheritance in Python" width="937" height="527" src="https://www.youtube.com/embed/M9kUpZOubBQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p> <strong>Learn more</strong> in our detailed articles: </p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179">Python Inherita</a><a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179" target="_blank" rel="noreferrer noopener">n</a><a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" data-type="post" data-id="2179">ce</a></li><li><a href="https://blog.finxter.com/understanding-inheritance-types-in-python/" data-type="post" data-id="31321" target="_blank" rel="noreferrer noopener">Five Types of Inheritance in Python</a></li></ul>
<p>The post <a href="https://blog.finxter.com/python-__subclasscheck__-magic-method/">Python __subclasscheck__() Magic Method</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 __sizeof__() Method</title>
		<link>https://blog.finxter.com/python-__sizeof__-method/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 26 Dec 2021 10:42:33 +0000</pubDate>
				<category><![CDATA[Dunder Methods]]></category>
		<category><![CDATA[Object Orientation]]></category>
		<category><![CDATA[Operating System]]></category>
		<category><![CDATA[Python Operators]]></category>
		<category><![CDATA[Python sys]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=104493</guid>

					<description><![CDATA[<p>Syntax object.__sizeof__(self, other) The Python __sizeof__() method returns the size of the object in bytes. The sys.getsizeof() method internally call&#8217;s __sizeof__() and adds some additional byte overhead, e.g., for garbage collection. Basic Example The following code snippet creates a list object x with three integers and measures its size in bytes (104) using the x.__sizeof__() ... <a title="Python __sizeof__() Method" class="read-more" href="https://blog.finxter.com/python-__sizeof__-method/" aria-label="Read more about Python __sizeof__() Method">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-__sizeof__-method/">Python __sizeof__() Method</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">Syntax</h2>



<pre class="wp-block-preformatted"><code>object.__sizeof__(self, other)</code></pre>



<p>The Python <code>__sizeof__()</code> method returns the size of the object in bytes. The <code>sys.getsizeof()</code> method internally call&#8217;s <code>__sizeof__()</code> and adds some additional byte overhead, e.g., for garbage collection. </p>



<h2 class="wp-block-heading">Basic Example</h2>



<p>The following code snippet creates a list object <code>x</code> with three integers and measures its size in bytes (104) using the <code>x.__sizeof__()</code> method call. </p>



<p>It then measures the size with overhead using <code>sys.getsizeof(x)</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 sys
>>> x = [1, 2, 3]
>>> x.__sizeof__()
104
>>> sys.getsizeof(x)
120</pre>



<p>Let&#8217;s make the list much larger to measure if it has any impact on the size in bytes.</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 sys
>>> x = list(range(10000))
>>> x.__sizeof__()
80040
>>> sys.getsizeof(x)
80056</pre>



<p>This list is built using the <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290" target="_blank" rel="noreferrer noopener">range()</a></code> function. It has 10000 integers, each needing 8 bytes with a constant overhead of 40 bytes for the list structure, the <code>x.__sizeof__()</code> method call results in 10000 * 8 + 40 = 80040 bytes.</p>



<p>You can see that in both cases, the <code>sys.getsizeof(x)</code> has 16 more bytes than <code>x.__sizeof__()</code> which seems to be the overhead on my particular machine for this particular example.</p>



<h2 class="wp-block-heading">Overriding __sizeof__()</h2>



<p>You can override the <code>__sizeof__()</code> method for your own custom data type by defining the <code>__sizeof__()</code> method with one argument <code>self</code> (that is passed automatically by Python). </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 sys

class Data:
    def __sizeof__(self):
        return 42
    
    
x = Data()
print(x.__sizeof__())

</pre>



<p>The <code>__sizeof__()</code> method returns the integer 42 that was returned by us&#8212;not the number of bytes. </p>



<p>Let&#8217;s call the <code>sys.getsizeof()</code> method to see if the difference is 16 bytes for the GC overhead!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="10,11,13,14" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import sys

class Data:
    def __sizeof__(self):
        return 42
    
    
x = Data()

print(x.__sizeof__())
# 42

print(sys.getsizeof(x))
# 58</pre>



<p><strong>References:</strong></p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://docs.python.org/3/reference/datamodel.html" target="_blank">https://docs.python.org/3/reference/datamodel.html</a></li></ul>



<h2 class="wp-block-heading">Where to Go From Here?</h2>



<p>Enough theory. Let’s get some practice!</p>



<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>



<p>To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>



<p><strong>You build high-value coding skills by working on practical coding projects!</strong></p>



<p>Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>



<p>If you just want to learn about the freelancing opportunity, feel free to watch my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and learn how I grew my coding business online and how you can, too—from the comfort of your own home.</p>



<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/python-__sizeof__-method/">Python __sizeof__() Method</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 __reversed__ Magic Method</title>
		<link>https://blog.finxter.com/python-__reversed__-magic-method/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 25 Dec 2021 17:31:46 +0000</pubDate>
				<category><![CDATA[Dunder Methods]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<category><![CDATA[Python Operators]]></category>
		<category><![CDATA[Python String]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=103342</guid>

					<description><![CDATA[<p>Python&#8217;s __reversed__ magic method implements the reversed() built-in function that returns a reverse iterator over the values of the given sequence such as a list, a tuple, or a string. Syntax __reversed__(self) Let&#8217;s have a look at an example next. Example In the following code, you create a Person class with one name attribute. The ... <a title="Python __reversed__ Magic Method" class="read-more" href="https://blog.finxter.com/python-__reversed__-magic-method/" aria-label="Read more about Python __reversed__ Magic Method">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-__reversed__-magic-method/">Python __reversed__ Magic Method</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-background-color has-background">Python&#8217;s <code>__reversed__</code> magic method implements the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-reversed/" data-type="post" data-id="23565" target="_blank">reversed()</a></code> built-in function that returns a reverse iterator over the values of the given sequence such as a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list</a>, a <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank">tuple</a>, or a string.</p>



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



<pre class="wp-block-preformatted"><code>__reversed__(self)</code></pre>



<p>Let&#8217;s have a look at an example next.</p>



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



<p>In the following code, you create a Person class with one name attribute. The <code>__reversed__</code> dunder method uses <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="post" data-id="731" target="_blank" rel="noreferrer noopener">slicing</a> with negative step size to return the <a href="https://blog.finxter.com/reverse-a-string-in-python/" data-type="URL" data-id="https://blog.finxter.com/reverse-a-string-in-python/" target="_blank" rel="noreferrer noopener">reversed string</a> object when calling <code>reversed(alice)</code> on a Person object <code>alice</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="">class Person:
    def __init__(self, name):
        self.name = name

    def __reversed__(self):
        return self.name[::-1]



alice = Person('alice')
print(reversed(alice))
# ecila</pre>



<p>Note that the returned string object is an iterator, so this is a perfectly valid implementation of the <code>__reversed__</code> magic method.</p>



<h2 class="wp-block-heading">Background Video Reversing a List</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Reverse a List in Python?" width="937" height="527" src="https://www.youtube.com/embed/OSkQYTlvOXw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Background Video Slicing</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="The Ultimate Guide to Slicing in Python" width="937" height="527" src="https://www.youtube.com/embed/D2ZueuWXST8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>






<h2 class="wp-block-heading">Where to Go From Here?</h2>



<p>Enough theory. Let’s get some practice!</p>



<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>



<p>To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>



<p><strong>You build high-value coding skills by working on practical coding projects!</strong></p>



<p>Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>



<p>If you just want to learn about the freelancing opportunity, feel free to watch my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and learn how I grew my coding business online and how you can, too—from the comfort of your own home.</p>



<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/python-__reversed__-magic-method/">Python __reversed__ Magic Method</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-05-25 23:01:59 by W3 Total Cache
-->