Get the App
SLTechnology News&Howtos  ›  Development  › 

Introduction to the usage of comparison operator in Python

Shulou Source: shulou.com Published: 2022-06-03 15:07:36 11月14日 Update

This article mainly introduces "Introduction to the usage of comparison operators in Python". In daily operation, I believe many people have doubts about the introduction to the usage of comparison operators in Python. Xiaobian consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts of "Introduction to the usage of comparison operators in Python"! Next, please follow the small series to learn together!

== AND!=

== and!= It's an equivalence check.

These two operators are the most familiar comparison operators.== The magic method__eq__detects whether the values of the left and right objects are equal.

For example, x == y, the operation behind it is x.__ eq__(y)。

is

Is is identity verification. It detects whether the left and right sides are the same object.

The same object must satisfy:

values are the same

Same memory address

It is therefore easy to understand why is and is not are used in singletons comparisons.

What are singletons?

A singleton is a design pattern that applies to a class that generates only one instance.

The singleton pattern ensures that only one instance of the same object can be fetched at different locations in the program:

If an instance does not exist: an instance is created

If an instance already exists: this instance will be returned

not

not is a logical predicate word in Python, often used for Boolean True and False.

not True -> Falsenot False -> True logical judgment a = False# not a is Trueif not a: pass Judge whether the element exists a = 100b = [1, 2, 3]#Element a is not in the list b if a is not in b: pass Summary

You can use ==/!= when simply comparing values Operator:

a = 1b = 2if a == b: passelse: pass

is is used to compare single cases, e.g. None:

if a is None: pass if a is not None: pass

If it involves a Boolean True/False judgment, use not, do not directly compare with True or False:

a = Falseb = True#if not a: passif b: pass#if a = False: pass #

Not can also be used to determine if an element exists in a list/dictionary.

At this point, the study of "Introduction to the Usage of Comparison Operators in Python" is over, hoping to solve everyone's doubts. Theory and practice can better match to help you learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Tags: Operators operations instances objects learning elements patterns same writing Boolean methods more logic help detection different practical and then two will create Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Xiaomi OPPO Reno Shulou Technology Shulou Information