Home  >  Article  >  Backend Development  >  How to use python variable data types and operators

How to use python variable data types and operators

王林
王林forward
2023-05-13 18:22:061494browse

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

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
## 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

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

eb18138301f26536200990b6b7c6f6b7 1 and a cd910ed2b782d08f2ab47b4a3e85b372 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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete