search
HomeBackend DevelopmentPython Tutorialwhat are operators in python

what are operators in python

Aug 27, 2020 pm 01:36 PM
pythonoperator

Python operators are: 1. Arithmetic operations, used for mathematical operations such as addition, subtraction, multiplication and division; 2. Assignment operations, used to receive results returned by operators or method calls; 3. Comparison operations, used to do Large or equal comparison operations; 4. Logical operations, used for AND, OR, and NOT operations; 5. Bit operations, used for binary operations.

what are operators in python

Related learning recommendations: python tutorial

Python operators are:

After talking about commonly used data types, let’s talk about operators. Operators are used to perform operations on various types of data to make static data run.

Operations in programming languages ​​are roughly divided into the following categories:

  • Arithmetic operations, used for mathematical operations such as addition, subtraction, multiplication and division

  • Assignment operations, used to receive results returned by operators or method calls

  • Comparison operations, used to perform size or equality comparison operations

  • Logical operations, used for AND, OR, NOT operations

  • Bit operations, used for binary operations

Each type The symbols included in the operation are called corresponding operators, such as arithmetic operators, comparison operators, etc.

1. Arithmetic operations

what are operators in python

2. Assignment operations

what are operators in python

3. Comparison operations

Python has 8 comparison operations, and they have the same priority. Comparison operations can be chained arbitrarily, for example x

what are operators in python

Explanation:

a) Objects of different types are compared and never equal (except for different numeric types);

b) When using the and >= operators, a TypeError exception will be thrown in the following situations: (1) When used to compare complex numbers with other built-in numeric types; (2) When the compared objects are of different types and cannot be compared; (3) In other undefined cases;

c) Different instances of a class are usually not equal unless the class defines __eq__() Method;

d) Instances of a class cannot be sorted relative to other instances of the same class or other classes, unless the class defines sufficient methods __lt__(), __le__(), __gt__(), __ge__(). If you want the conventional meaning of the comparison operators, __lt__() and __eq__() are sufficient;

e) The behavior of the is and is not operators cannot be customized; otherwise, they can be applied If two objects of different types are detected, no exception will be thrown.

f) Two other operations with the same syntactic precedence are in and not in, which support objects of sequence, set, and map types.

g) The result of the comparison operation is a Boolean value: True or False

4. Logical operation

Truth Value Testing )

Before explaining "Boolean operations", let's first talk about a special operation in Python-"true" value testing.

Any object in Python can be tested for a "true" value. The "true" value test mentioned here can be understood like this: any object in Python can be converted into a Boolean value, and this "true" value test is the process of obtaining the Boolean value corresponding to an object.

In Python, only the following values ​​correspond to Boolean values ​​that are False:

NoneFalse 0 in the numeric type, such as: 0, 0.0, 0j Any empty sequence, such as: '', () , [] Any empty mapping, such as: {} An instance of a user-defined class - a __bool__() or __len__() method is defined in the user-defined class, and the instance returns the integer 0 when calling the method. Or the Boolean value False

In addition, all other values ​​corresponding to the Boolean value are True, so many types of objects are always True.

"True" value testing can be used in if or while conditions, or as the operand of a Boolean operation.

Boolean Operations

The logical operations in Python are called "Boolean Operations". The operators include: and (and), or (or), not ( No).

The following are explained in ascending order of their priority:

what are operators in python

Explanation:

a) or is a short-circuit operator, also That is to say, the second parameter will be evaluated only when the evaluation result of the first parameter is False;

b) and is also a short-circuit operator, that is, only when the evaluation result of the first parameter is True, the second parameter will be evaluated;

c) The not operator is better than the non Boolean operators have low precedence, so not a == b is interpreted as not (a == b); if written as a == not b, a syntax error will occur.

5. Bitwise operations

Bitwise operations refer to converting numbers into binary for calculation. Bitwise operators include the following:

Assume:

a = 60, the corresponding binary format is 0011 1100

b = 13, the corresponding binary format is 0000 1101

what are operators in python

## If you want to know more about related learning, please pay attention to the

php training column!

The above is the detailed content of what are operators in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Completed python blockbuster online viewing entrance python free finished website collectionCompleted python blockbuster online viewing entrance python free finished website collectionJul 23, 2025 pm 12:36 PM

This article has selected several top Python "finished" project websites and high-level "blockbuster" learning resource portals for you. Whether you are looking for development inspiration, observing and learning master-level source code, or systematically improving your practical capabilities, these platforms are not to be missed and can help you grow into a Python master quickly.

Python PostgreSQL Database IntegrationPython PostgreSQL Database IntegrationJul 23, 2025 am 03:29 AM

The most commonly used thing for Python to connect to PostgreSQL is the psycopg2 library. You need to install it through pipinstallpsycopg2 first; 1. Use the psycopg2.connect() method to pass in the host, database name, user name, password and port information to establish a connection; 2. Create a cursor object to execute SQL query and get the results; 3. Be sure to close the cursor and connection after the operation is completed; Common problems include connection failure, SQL statement errors, uncommitted transactions, and resource leakage, etc. It is recommended to use try-except for exception handling and cooperate with conn.commit() to submit transactions; if performance is required, you can use SQLAlchemy to multiplex database connections with connection pools.

Developing Event-Driven Microservices with Python and CeleryDeveloping Event-Driven Microservices with Python and CeleryJul 23, 2025 am 03:29 AM

The event-driven architecture triggers and transmits information through events, which can be effectively implemented by Python and Celery. 1. Use celery.send_task to send tasks and trigger events; 2. Define unified event formats such as user_registered and order_paid; 3. Decouple the corresponding queues of each service listening; 4. Turn on message confirmation and persistence to ensure reliability; 5. Pay attention to task retry, event order, idempotence and log tracking issues. Celery supports asynchronous processing based on message middleware, which is suitable for background tasks and event response scenarios, improving system scalability and real-timeness.

Practical Cryptography in Python for Data SecurityPractical Cryptography in Python for Data SecurityJul 23, 2025 am 03:26 AM

TosecuredatainPython,usethecryptographylibraryforencryption,understandsymmetricvsasymmetricencryption,andapplysigningfordataintegrity.1)InstallandusethecryptographylibrarywithFernetforsymmetricencryption,ensuringkeysafety.2)Choosesymmetricencryptionf

Python for Data GovernancePython for Data GovernanceJul 23, 2025 am 03:24 AM

Python is widely used in data governance, mainly reflected in the following aspects: 1. Data cleaning and standardization, using pandas for field replacement, missing value filling, format uniformity, etc.; 2. Automation of data quality inspection, realizing null value detection, range verification, enumeration matching and regular scanning tasks through scripts; 3. Metadata management and directory generation, extracting database structures with SQLAlchemy and pandas and exporting them into structured documents; 4. Cooperating with other tools to improve efficiency, such as Airflow to implement timing task scheduling, Flask/Django build management backend, and GreatExpectations to perform data verification. Python has its strong ecological support and spirit

Locking Mechanisms in Python ThreadsLocking Mechanisms in Python ThreadsJul 23, 2025 am 03:23 AM

Lock is a basic tool used in Python multithreading to synchronize threads to access shared resources, solving the race conditions and data inconsistency caused by multiple threads to modify shared data at the same time. 1.Lock ensures that only one thread executes protected code segments at the same time; 2. Common lock types include Lock, RLock, Condition, Semaphore and Event; 3. Use the with statement to automatically acquire and release the lock to protect the shared resource access path; 4. When using Lock, you should narrow the lock range, avoid deadlocks, and select Lock or RLock according to whether you call recursively.

Debugging Asynchronous Python Code EffectivelyDebugging Asynchronous Python Code EffectivelyJul 23, 2025 am 03:22 AM

The more complex reason for debugging asynchronous Python code is the uncertainty caused by event loops, coroutines, and callback mechanisms. 1. The asynchronous function is not executed because it is not put into the event loop and needs to be called using asyncio.run or await; 2. Log confusion is caused by the alternating execution of concurrent tasks, which can improve readability by adding task names or unique identifiers; 3. The debugger cannot enter the coroutine, so async/await support needs to be enabled, such as VSCode's launch.json configuration or using pdb.set_trace(). Mastering these basic methods can help quickly locate problems.

Strategy Pattern in PythonStrategy Pattern in PythonJul 23, 2025 am 03:21 AM

The strategy model is suitable for multiple similar algorithms that require dynamic switching scenarios, such as payment methods, promotional strategies, etc. When using it, first define a unified interface or protocol, then implement specific policy classes or functions separately, and call them through context. The structure includes context, policy interface, and specific policies. In Python, it can be implemented through classes, functions or protocols, and the functional writing method is more concise. The policy should be stateless as possible, and multiple policies can be managed by factories or dictionaries. Whether the runtime switching is supported is determined by the requirements, and the set_strategy method is omitted without it.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools