Table of Contents
1 Data type
1.2 Type judgment
2. Operators and expressions
2.1 Arithmetic operators
2.4 随机函数
2.5 赋值运算符
2.6 关系运算
2.7 逻辑运算
2.7.1 逻辑与
2.7.2 逻辑或
2.7.3 Logic Not
2.8 Short-circuit calculation
2.9 Notes
2.10 Identity operator
2.11 Member operator
2.12 if-else expression
Home Backend Development Python Tutorial How to use python variable data types and operators

How to use python variable data types and operators

May 13, 2023 pm 06:22 PM
python

1 Data type

Different types of variables can perform different operations, so the type of the variable must be understood. Data types in python can be divided into:

Built-in types :

  • Numeric type: Integer type int, floating point type float, complex number (complex) 3 5j

  • str:String

  • bool:Boolean value [True, False]

  • None: Null value, indicating that the variable has no determined value

  • list: List

  • tuple:tuple

  • dict:dict

  • set:Collection

Custom type:

  • ##class: Class

1.1 Basic type

Numeric type:

  • Integer type (int): There is only one type of int in python3, which can represent integers, for example: 10, -5, 10000

  • Floating point type (float): represents a real number with a decimal point, There are two representations:

    • Decimal representation: 1.9 .23

    • Scientific notation: Use e to represent the exponent of 10 , 1e2 represents 100. Note that e must be preceded by a numerical value, and e must be followed by an integer

  • Complex: represents an irrational number in mathematics , in the form: a bj

  • Boolean type (bool): represents the two states of the transaction, male and female, cloudy and sunny, light and dark Wait, it has only two values: True, False

  • None: represents an empty object, generally used for judgment, different from 0 and empty characters

  • String (str): In python, use quotes (single quotes, double quotes, triple quotes) to represent strings

Representation of string:

# Use single quotes to express: 'hello'

# Use double quotes to express: "I use python"
# Use 3 A single quotation mark means: it can represent multi-line text, for example:
'''The great
's
motherland
'''
# It means 3 double quotation marks: it can represent multi-line text , for example:
"""Be optimistic about life and death,
Just do it if you don't accept it"""

  • Escape characters: Some special characters cannot Input from the keyboard can be represented by escape characters. In addition, whether it is a single quotation mark, double quotation mark or triple quotation mark string, the quotation mark is the string delimiter, and the quotation mark is not the content of the string. So how to enter a single quotation mark string? Indicates a single quote, which can also be expressed using escape characters. Common escape characters

represents an ordinary character single quote \nline break represents an ordinary character double quote \r##\'''\"""tab key\bDelete one character back
Escape characters

Description

Escape characters

Description

##\'

\"

##Enter

An ordinary three single quotes

\\

An ordinary character\

##An ordinary triple double quotation mark

\a

Ring

##\t

  • String encoding: The computer can only recognize binary, so how to store the string in the computer

The computer cannot store it directly String, but we can encode the characters, for example, use 65 to represent uppercase character A, 66 to represent uppercase character B... etc. This representation method is the American ASCII code, which can only represent 127 characters, but for Americans That's enough. Once we can use integers to represent characters, we can easily represent integers in binary, and strings can be easily stored in the computer.
But there are many languages ​​in other countries that cannot be represented by ASCII. All ISO organizations have introduced unicode codes, which are used to represent characters in any language. Unicode codes are also called universal codes and universal codes. Represents any character in any language. There are many representation methods of unicdoe code, such as: utf-8, utf-16, utf-32, etc. The most commonly used one is utf-8. utf-8 is a variable-length encoding, which means that a character may use one byte or three bytes.
Commonly used Chinese encodings generally use GBK encoding, using 2 Bytes represent a Chinese character

1.2 Type judgment

We can use type and isinstance to test and judge the data type

#type用法:
type(obj)
功能:返回obj的数据类型
参数:obj是你要测试变量或数值
示例:
age = 10
name = 'hello'
print(type(name),type(age))
#判断变量是否是指定类型
if type(age) is int:
print('是')
else:
print('否')

#isinstance用法:
isinstance(obj,typename)
功能:判断obj是否是指定类型,是返回True,否返回False
参数: objobj是你要判断的变量或数值
typename是指定数据类型,可以是int,float,str等。也可是一个
类型的元组,例如:(int,float)
示例:
age = 10
name = 'hello'
print(isinstance(age,int))
print(isinstance(name,(str,int)) #只要name是str或int的一种就返回True

if isinstance(age,int):
print('是')
else:
print('否')

#type和isinstance的区别
type判断基本类型是没问题的,但无法判断子类对象是父类的一种
isinstance可以判断子类对象是父类的一种
class A:
pass
class B(A):
pass

objA = A()
objB = B()

#输出否
if type(objB) is A:
print('是')
else:
print('否')
print(isinstance(objB,A)) #True
Copy after login

Conclusion:Use first isinstance

2. Operators and expressions

In order to calculate the results in mathematics, we will write some formulas to calculate, for example:

30 5

This is a calculation formula in mathematics. There are similar formulas in python for calculation, called expressions. In the expression, 30 and 5 are called operands, called operators. The purpose of an expression is to compute a result. Expression composition:

  • The most basic expressions are some numerical values, variables, and functions, for example: 3, a (variable) print(‘hello’)

  • Complex expressions are composed of basic expressions plus appropriate operators: 3 a

Based on the above, the so-called expression is composed of operands and operators An expression that conforms to python syntax. To write expressions, you first need to learn operators. There are two things to know about operators

  • Calculation order: Is it calculated from left to right or right to left

  • Priority: For example, multiplication and division first, then addition and subtraction

2.1 Arithmetic operators

a = 20
b = 10
Copy after login
## Modulo operation, that is Find the remainder when a is divided by ba % 10 = 0//Divisibilitya // b = 2##**2.2 Description of modular operation

Operator

Description

Example

-

Negative sign, take the opposite of the original number

a = 10 print(-a) #-10

- * /

Addition, subtraction, multiplication and division are the same as in mathematics

a b = 30 a - b = 10 a * b = 200 a / b = 2

##%

Calculate the exponent (power) of the operator

a ** b represents 20 raised to the 10th power

The sign of modular operation depends on the second operand (right operand)
  • Calculation formula of modular operation: r = a % b = a - n * b, where n is the largest integer less than a/b
  • Integer division (//) operation if there is an operation The number is a floating point number, and the result is a floating point number
  • Uses: Determining parity, determining whether it is divisible, greatest common divisor, narcissus number
  • 2.3 Mathematical functions

Function nameabs##pow(x,y)##Find the minimum value of the given parametersNeed to import the import math library and round upNeed to import the import math library and round downNeed to import the import math library to find the square root

2.4 随机函数

获取随机数,需要引入random库。

import random

Description of function

Example

Get the absolute value

abs(- 10)

x to the power of y

pow(10,2) finds the square of 10

##round(x,[n])
Floating point numbers are rounded from 4 to 5, n represents the number of decimal digits to retain

round(3.456)

max()
Find the maximum value of the given parameter

max(21,43,65,75,86,32, 3,45)

##min()

min(21,43,65,75,86,32,3,45)

math.ceil()

math.ceil(18.1) #19

math.floor()

math.floor(18.1) # 18

math.sqrt

math.sqrt(100)

python3.5.2 Chinese Help Document

函数名

函数说明

random.randrange(start,stop,step)

start 指定范围的起始值 包含本身,默认是0;stop 指定范围的结束值 不包含本身; step 步长,默认步长是1。该函数返回一个整数

random.randint(start,end)

返回[start end]之间的一个随机整数,start必须小于end

random.random()

返回一个[0.0,1.0)之间的随机小数

注意:

  • 优先级: ** >正负号 > // % * / > + -

  • 从左向右算

  • 在幂运算和一元运算符联合计算时,从右向左算,例如: -1 ** 2 = -1

2.5 赋值运算符

a = 5; b = 10; c = 20

运算符

说明

示例

=

简单赋值, 将b+c的结果赋给a

a = b +c #a=30

+=

a += b等价于 a = a +b

a = 15

-=

a -= b等价于 a = a - b

a = -5

*=

a *= b等价于 a = a * b

a = 50

/=

a /= b 等价于a = a / b

a = 0.5

%=

a %= b等价于a = a % b

a = 5

//=

a //= b等价于 a = a // b

a = 0

**=

a **= b等价于a = a ** b

注意:

  • 赋值运算符左边必须是变量

  • 从右向左算

  • 没有赋值表达式

  • 所有赋值运算符优先级相同,赋值运算符优先级非常低,仅高于成员运算符和身份运算符、逻辑运算符

  • 注意在复合赋值中

a = 2
b = 3
a *= b + 2 #等价于 a = a * (b + 2)
print(a) # a = 10
Copy after login

2.6 关系运算

关系运算就是比较运算,如果表达式成立,返回True,否则返回False。关系运算的结果是布尔值。

运算符

示例

说明

==

a == b

a和b值相等,结果是True,a和b值不相等结果为False

!=

a != b

a不等于b 结果为True,否则结果为True

>

a > b

a大于b结果为True,否则为False

>=

a >= b

a大于等于b结果为True,否则为False

<

a < b

a小于b结果为True,否则为False

<=

a <= b

a小于等于b结果为True,否则为False

注意

  • 优先级: 比较运算符优先级相同

  • 从左向右算

  • 可以这样算:1 < a < 3 等价于 a > 1 and a < 3

2.7 逻辑运算

逻辑运算符可以用于构造复杂条件。逻辑运算符包括:

  • 逻辑与 and 对应汉语的意思是“并且” 、 “同时”

  • 逻辑或 or 对应汉语意思为"或者"

  • 逻辑非 not 对应汉语意思为”相反“

在逻辑运算中,False、None、0、0.0、‘’(空字符串)被看做假(False),其它的看做真(True)

2.7.1 逻辑与

a

b

a and b

任意值

b的值

任意值

a的值

  • 表达式 a and b的值为: 如果a为真,结果为b的值,否则结果是a的值

2.7.2 逻辑或

a

b

a or b

任意值

a的值

任意值

b的值

  • The value of expression a or b is: if a is true, the result is the value of a, otherwise the result is the value of b

2.7.3 Logic Not

a

not a

True

False

False

True

Summary: If a is true, the expression is False, otherwise the expression is True

2.8 Short-circuit calculation

  • For the logical AND expression a and b, if a is false, b is not evaluated

  • For the logical OR expression a or b, if a is true, Then b

2.9 Notes

  • priority is not > and >or

    2.10 Identity operator

    is: Determine whether two identifiers refer to the same entity [object]. What is compared is whether the ids of the two objects are the same. If they are the same, it is true, otherwise it is false

    is not: Determine whether two identifiers refer to different entities [objects] If the ids of the two objects are different, the result is true, otherwise it is false

    id() function gets the id of the entity ( Address)

    Note: The difference between is and ==

    • is is used to determine whether the entity referenced by two variables is the same [id]

    • == is used to determine whether the values ​​​​of two variables are the same, but the id is not necessarily the same

    2.11 Member operator

    is mainly used in sequences in

    in: Returns True if the specified value is found in the specified sequence, otherwise returns False

    not in: Returns if the specified value is not found in the specified sequence True, otherwise it returns False

    2.12 if-else expression

    expression 1 if condition else expression 2, if the condition is true or false, the result is the value of expression 1, otherwise the result is expression Value of equation 2

The above is the detailed content of How to use python variable data types and operators. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

See all articles