Python from Beginner to Master Chapter 3 (Basic Data Types)

1. Number type

1. Integer type

(1) The integer type is consistent with the concept of integers in mathematics. The theoretical value range is from negative infinity to positive infinity. In fact, as long as the computer memory is large enough, Python programs can use integers of any size (this is in C language difficult to achieve).

(2) By default, integers are expressed in decimal. If you want to use other bases, you need to add a pilot symbol, as shown in the following table.

Base type

guide symbol

describe

decimal

none

Default, such as 2005, 803

binary

0b or 0B

Composed of characters 0 and 1, such as 0b1010, 0B1001

Octal

0o or 0O

Composed of characters 0 to 7, such as 0o1712, 0O7753

hexadecimal

0x or 0X

It consists of characters 0 to 9, a to f or A to F, such as 0x3FFF, 0X7BC0

(3) Operation example:

# 0x3F2转换为十进制即1010,0o1762转换为十进制即1010
print((0x3F2 + 1010)/0o1762)

# 0x1010转换为十进制即4112
print(0x1010 == 4112)

2. Floating point type

(1) The floating-point number type is consistent with the concept of real numbers in mathematics, representing values ​​with decimals. Floating point numbers in Python must have a decimal part, and the decimal part can be 0. For example, 1010 is an integer, but 1010.0 is a floating point number (it should be noted that for integers and floating point numbers with the same value, the results of exponentiation may be different. The difference is mainly reflected in the accuracy).

(2) There are two representation methods for floating point numbers, one is general representation in decimal form, and the other is representation in scientific notation. The decimal form is relatively simple and will not be repeated here; scientific notation uses the letter e or E as the symbol for power, with 10 as the base, expressed as

        For example, the value of 1.01e3 is 1010.0, and the value of -1.01E-3 is -0.00101.

(3) The numerical range and decimal precision of Python floating point number types are limited by different computer systems. Generally speaking, the value range of floating point numbers is between -1.79×10308 and 1.79×10308. The distinction accuracy between floating point numbers is approximately is 2.22×10-16. (It can generally be considered that floating point number types have no range restrictions and the operation results are accurate)

3. Plural type

(1) The complex number type represents complex numbers in mathematics. In Python, complex numbers can be regarded as binary ordered real number pairs (a, b), representing a+bj, where a is the real number part and b is the imaginary number part (b=1 b) cannot be omitted.

(2) The real part and imaginary part of the complex number type are both floating point types. For the complex number z, you can use z.real and z.imag to obtain its real part and imaginary part respectively.

2. Operations on digital types

1. Numerical operation operators

(1) Arithmetic operators are a type of operator and are symbols used to complete basic arithmetic operations.

Operators and calculations

describe

+

x+y, the sum of x and y

-

xy, the difference between x and y

*

x*y, the product of x and y

/

x/y, the quotient of x and y, the operation result is a floating point number

//

x//y, the integer quotient of x and y, that is, the largest integer not greater than the quotient of x and y

%

x%y, the remainder after dividing x and y, also called modular operation

-x

The opposite of x

+x

x itself

**

x**y, x raised to the y power

(2) Priority of arithmetic operators: multiplication and division first, addition and subtraction; operators of the same level are calculated from left to right ; you can use () to adjust the priority of calculation. The following tables are arranged in order of arithmetic priority from highest to lowest.

(3) Numerical operations may change the data type of the result. The change of type is related to the operator. The basic rules are as follows:

① Mixed operation of integers and floating point numbers, the output result is a floating point number.

②For operations between integers, the result type is related to the operator. The result of division operation must be a floating point number.

③Arithmetic operations on integers or floating point numbers and complex numbers, the output result is a complex number.

(4) All binary operation operators (+, -, *, /, //, %, **) in the above table can be connected with the assignment symbol (=) to form a strong assignment operator (+=, - =, *=, /=, //=, %=, **=), in fact, the strong assignment operator is the compound operator in C language . For convenience of description, op is used to represent these binary operation operators. The usage of the enhanced assignment operator is as follows: x op = y is equivalent to x = x op y.

2. Numerical operation functions

function

describe

abs(x)

absolute value of x

divmod(x,y)

(x//y,x%y), the output is in the form of a tuple (also called a tuple type)

pow(x,y)或pow(x,y,z)

x**y or (x**y)%z, power operation

round(x)或round(x,d)

Round x and keep d as a decimal. If there is no parameter d, return the rounded integer value.

max(x1,x2,…,xn)

The maximum value of x1, x2,…,xn, n is not limited and can be any number

min(x1,x2,...,xn)

The minimum value of x1, x2,…,xn, n is not limited and can be any number

3. Numerical comparison operations

(1) For numeric types, comparison operations can be performed arbitrarily between integers and floating point numbers.

(2) Comparison operations involving complex number types are limited and can only determine whether they are equal, that is, only "==" and "!=" can be used. Other comparison symbols for determining size cannot be used, otherwise an error will be reported.

3. True, false, valueless and logical operations

1. True and false values: True and False

(1) True and False are keywords in Python that express opposite binary values ​​​​of "true" and "false". Strictly speaking, they also belong to numeric types, where True represents a value equal to 1, and False represents a value equal to 0. value.

(2) Generally, True and False are only used in true and false logic scenarios and are not compared with integers. For a wider range of application scenarios, Python equates all non-zero-valued numbers to True , and this equivalence will be widely used in logical judgments.

(3) When True and False operate with other numeric type data, the corresponding number for True is 1, and the corresponding number for False is 0.

2. No value: None

(1) None is a keyword in Python, expressing meanings such as none, nothing, and emptiness.

(2) None is not False, it does not represent 0, it does not represent an empty string, and it does not correspond to any numerical value.

(3) Example:

a = print("2005.08.03")
print(a == None)
# print函数运行后不会返回任何内容,因此变量a的值是空
# 作为程序设计逻辑完整性要求,需要用某个值赋给变量a,这个值就是None

3. Logical operations: and, or, not

(1) AND or NOT operations can be used in combination. In order to make the operation relationship clearer, you can group them with the help of parentheses.

(2) When and and or are used in combination without bracket grouping, calculations are performed from left to right until the result is generated.

4. Priority of operators

The following tables are arranged in order of arithmetic priority from highest to lowest.

5. String type and formatting

1. Representation of string

(1) A string is a sequence representation of characters, which is divided into single-line strings and multi-line strings according to the content of the string.

①A single-line string can be represented by a pair of single quotes (') or double quotes (") as boundaries. Single quotes and double quotes have the same effect. When using single quotes, double quotes can be used as part of the string; when using Single quotes can be used as part of a string when double quoted.

② A multi-line string can be represented by a pair of three single quotes (''') or three double quotes (""") as boundaries, both of which have the same effect.

"""
使用多行字符串,在敲代码时输入回车,输出也会自动换行
另外,三双引号也可以用来做注释
"""
print("""多行'字符串'1
多行"字符串"2""")

# 使用单行字符串,在敲代码时输入回车,输出并不会跟着换行
print("单行'字符串'1"
      "单行'字符'串2")

2. Backslash character

(1) The backslash character (\) is a special character, which means "escape" in a Python string. That is, this character and an adjacent character form a new meaning, such as \n means new line, \ \ represents backslash, \' represents single quotation mark, \" represents double quotation mark, \t represents tab character (Tab, to help maintain vertical alignment when outputting text ), etc.

print("这里\n有一个换行")
print("这里\\有一个反斜杠")
# 当字符串中既需要出现单引号又需要出现双引号,则需要使用转义字符
print("既需要'单引号'又需要\"双引号\"")
print("这里\t有一个制表符")

(2) The backslash character (\) can also be used as a line continuation character. This is introduced in Chapter 1 and will not be repeated here.

3. Index of string

(1) The search for a certain character in a string is called an index. The index is used as follows:

<string or string variable>[serial number]

(2) Strings include two serial number systems: forward increasing serial numbers and reverse decreasing serial numbers.

If the length of the string is L, the forward increment needs to be with the leftmost character number being 0, increasing to the right, and the rightmost character number being L-1; the reverse increment needs to be -1, with the rightmost character number being -1, going to the right Decreasingly from left to right, the leftmost character number is -L.

print("玛卡巴卡,唔西迪西"[4])
print("玛卡巴卡,唔西迪西"[1])
print("玛卡巴卡,唔西迪西"[0])
print("玛卡巴卡,唔西迪西"[-1])
print("玛卡巴卡,唔西迪西"[-8])

4. String slicing

(1) Retrieval of a certain substring or interval in a string is called slicing. Slicing is used as follows:

<String or string variable>[N:M]

① Slice to obtain the character substring of the string from N to M (excluding M), where N and M are the index serial numbers of the string. You can use a mixture of forward increasing serial numbers and reverse serial numbers.

② Slicing requires that both N and M are in the index range of the string. If N is greater than or equal to M, an empty string is returned.

③If N is missing, N will be set to 0 by default; if M is missing, it will default to the end of the string.

print("玛卡巴卡,唔西迪西"[1:4])
print("玛卡巴卡,唔西迪西"[8:4])
print("玛卡巴卡,唔西迪西"[:4])
print("玛卡巴卡,唔西迪西"[0:4])
print("玛卡巴卡,唔西迪西"[5:])
print("玛卡巴卡,唔西迪西"[5:9])

(2) There is also an advanced usage of string slicing, which is as follows:

<String or string variable>[N:M:K]

① This method obtains the string from N to M (excluding M), with K as the step size (which can be simply understood as taking one character for every K characters), where N and M are the index numbers of the string. You can Mix forward increasing serial numbers and reverse delivery serial numbers, K is an integer.

②When K is a negative number, the reverse string from M to N (excluding N) will be returned.

print("玛卡巴卡,唔西迪西"[1:4:2])
print("玛卡巴卡,唔西迪西"[1:8:2])
print("玛卡巴卡,唔西迪西"[::4])
print("玛卡巴卡,唔西迪西"[8:1:-1])
print("玛卡巴卡,唔西迪西"[:2:-2])
print("玛卡巴卡,唔西迪西"[::-1])

5. Basic formatting of strings

(1) When integrating variables in a string, you need to use the string formatting method. String formatting is used to solve the formatting problem when strings and variables are mixed in the output. Python recommends using the format formatting method, which is used as follows:

<template string>.format(<comma separated parameters>)

①Template string is a string composed of strings and slots, used to control the display effect of strings and variables. Slots are represented by braces ({}) and correspond to comma-separated parameters in the format method.

② If the template string has multiple slots and no serial number is specified in the slot, the different parameters in the format method will be corresponding to the order in which the slots appear.

# 输出字符串模板中采用大括号{}表示一个槽位置,每个槽位置对应format()中的一个变量
a = 2005
b = 803

print("数字{}和数字{}的乘积是{}".format(a,b,a*b))
print("数字{0}和数字{1}的乘积是{2}".format(a,b,a*b))
print("数字{1}和数字{0}的乘积是{2}".format(a,b,a*b))

③ If the number of slots appearing in the string is inconsistent with the number of parameters appearing in the format method, that is, the program cannot determine the parameter usage through simple sequence correspondence, it must use the parameters specified by the serial number in the slot, otherwise an IndexError will occur.

6. String format control

(1) In addition to the parameter serial number, the slot of the format method can also include format control information. The syntax is as follows:

{<parameter number>:<format control tag>}

:

<fill>

<alignment>

<width>

<,>

<.Accuracy>

<type>

guide symbol

a single character used for padding

<Left aligned

>right aligned

^center aligned

Set output width of slot

Thousands separator for numbers, suitable for integers and floating point numbers

The precision of the decimal part of a floating point number or the maximum output length of a string

Integer types b, c, d, o, x, X, floating point types e, E, f, %

(2) The format control mark includes: <Padding><Alignment><Width><,><.Precision><Type> 6 fields, with the leading symbol (:) as the leading mark. These fields are optional and can Use in combination. They can be divided into two groups.

①The first group is <Padding>, <Alignment> and <Width>, which are related fields and are mainly used to standardize the display format.

[1] Width refers to the set output character width of the current slot. If the actual value of the slot parameter is larger than the width setting value, the actual length of the parameter is used; if the actual value of the slot parameter is smaller than the width setting value, the alignment specification method is used. Aligned within width, padded with space characters by default.

[2] The alignment field uses three symbols: <, >, and ^ to represent left alignment, right alignment, and center alignment respectively. Left alignment is used by default.

[3] The default fill character can be modified in the fill field, and there can only be one fill character.

# 输出字符串模板中采用大括号{}表示一个槽位置,每个槽位置对应format()中的一个变量
s = "2005.08.03"

print("{:20}".format(s)+"字符串结束")    # 左对齐,宽度为20
print("{:2}".format(s)+"字符串结束")     # 左对齐,宽度为2,比变量s的宽度小,以s的宽度为准
print("{:^20}".format(s)+"字符串结束")   # 居中对齐,宽度为20
print("{:>20}".format(s)+"字符串结束")   # 右对齐,宽度为20
print("{:*^20}".format(s)+"字符串结束")  # 居中对齐,宽度为20,填充*
print("{:^20}".format(s)+"字符串结束")   # 居中对齐,宽度为20

[4] Format control tags can be represented by variables, that is, slots are used to specify the corresponding control tags and their quantities (slots within slots).

# 输出字符串模板中采用大括号{}表示一个槽位置,每个槽位置对应format()中的一个变量
s = "2005.08.03"

print("{0:{1}}".format(s,20)+"字符串结束")      # 左对齐,宽度为20
print("{0:{1}}".format(s,2)+"字符串结束")       # 左对齐,宽度为2,比变量s的宽度小,以s的宽度为准
print("{0:{1}^20}".format(s,"*")+"字符串结束")  # 居中对齐,宽度为20,填充*

②The second group is <,><.precision> and <type>, which are mainly used to standardize the value itself.

[1] Comma (,) is used to display the thousands separator for numeric types.

print("{:-^25,}".format(1234567890)+"字符串结束")
print("{:-^25}".format(1234567890)+"字符串结束")

[2]<.precision> starts with a decimal point. For floating point numbers, the precision represents the number of significant digits output in the decimal part; for strings, the precision represents the maximum length of the output. At this time, the decimal point can be understood as an effective truncation of the value. If the retained length of the decimal point exceeds the original output length, the original output length shall prevail.

print("{:.2f}".format(1234567890)+"字符串结束")          # 左对齐,精度为2
print("{:>25.3f}".format(1234567890)+"字符串结束")       # 右对齐,宽度为25,精度为3
print("{:.2f}".format(123456.7890)+"字符串结束")         # 左对齐,精度为2
print("{:>25.3f}".format(123456.7890)+"字符串结束")      # 右对齐,宽度为25,精度为3
print("{:.2}".format("1234567890")+"字符串结束")         # 左对齐,输出长度为2
print("{:>25.3}".format("1234567890")+"字符串结束")      # 右对齐,宽度为25,输出长度为3
print("{:>25.20}".format("1234567890")+"字符串结束")     # 右对齐,宽度为25,输出长度为20(过长,以字符串长度为准)

[3]<type> indicates the format rules for output integer and floating point number types.

b: Output the binary form of the integer.

c: Output the Unicode character corresponding to the integer.

d: Output the decimal form of the integer.

o: Output the octal form of the integer.

x: Output the lowercase (mainly for af) hexadecimal form of the integer.

X: Output the uppercase (mainly for AF) hexadecimal form of the integer.

e: Output the exponential form of the lowercase letter e corresponding to the floating point number.

E: Output the exponential form of the uppercase letter E corresponding to the floating point number.

f: Outputs the standard floating point form of floating point numbers.

%: Output the floating point number in percentage form.

6. String type operations

1. String operators

(1) String variables can be spliced ​​using "+" to generate a new string.

(2) String variables can be used to repeatedly splice the same string with integers using "*", and the calculation result is the result of repeating the string a specified number of times. (It is worth noting that other calculations other than "*" cannot be performed between numeric variables and strings)

(3) Operator in can determine whether a string is a substring of another string.

2. String processing function

function

describe

only(x)

Returns the length of the string

str(x)

Returns the string form corresponding to any type x

chr(x)

Returns the single character corresponding to Unicode encoding x

ord(x)

Returns the Unicode encoding represented by the single character x

hex(x)

Returns the lowercase string corresponding to the hexadecimal number of the integer x

oct(x)

Returns the uppercase string corresponding to the hexadecimal number of the integer x

3. String processing method

method

describe

str.lower()

Returns a copy of the string str, all characters in lowercase

str.upper()

Returns a copy of the string str, with all characters in uppercase

str.split(sep=None)

Returns a string list, consisting of the parts of str separated by sep. If spe is omitted, it will be separated by spaces by default (such as separating an English sentence into multiple English words)

str.count(sub)

Returns the number of times sub substring appears in str

str.replace(old,new)

Returns a copy of the string str with all old substrings replaced with new (the lengths of old and new can be different, or even the length of new can be 0)

str.center(width,fillchar)

String centering function, fillchar (characters filled on both sides of the centered string) parameter is optional, width is the overall width (when width is less than the length of str, the length of str shall prevail)

str.strip(chars)

Removes the characters listed in the left and right chars from the string str (default is whitespace characters)

str.join(iter)

Add a str string after each element (except the last element) of the iter variable (such as a list variable or string variable) and return the result

4. String comparison operations

Note: "Method" is a proper noun in programming and belongs to the field of object-oriented programming. Inside the Python interpreter, all data types are implemented in an object-oriented manner, so most data types have some processing methods. In fact, methods are also functions, but the calling method is different from ordinary functions. General functions are called by fun(x), while methods are called by <a>.func(x). Methods only act on the leading object< a>.

(1) Like numerical comparison operations, string comparison operations can also be performed, and there are also six operations.

(2) Two strings are compared by comparing characters in sequence from left to right. The string size relationship is determined according to the size of the corresponding Unicode encoding value. If the Unicode encoding value of the first character is different, there is no need to continue the comparison. Get the size relationship; if the Unicode encoding value of the first character is the same, continue the backward comparison. If the Unicode encoding value of each corresponding character is the same, the two strings are equal.

7. Type judgment and conversion between types

1. Type judgment

(1) The type function can output the variable type, as shown in the figure below.

(2) float represents the floating-point number type, int represents the integer type, str represents the string type, and bool represents the Boolean type.

(3)type函数的输出不是字符串,而是一种内部类型表示,所以不能采用字符串比较方式进行类型的判断,但是可以使用type函数直接进行比较。

name = "Zhang" + "San"
print(type(name) == type("123"))
print(type(name) == type(123))

2、数值与字符串类型转换

函数

描述

int(x)

将x转换为整数,x可以是浮点数(直接舍弃小数部分,不使用四舍五入)或字符串

float(x)

将x转换为浮点数,x可以是整数或字符串

str(x)

将x转换为字符串,x可以是整数或浮点数

(1)例1:

# 1. 输入单位重量的价格
price_str = input("请输入单位重量的价格:")

# 2. 输入购买重量
weight_str = input("请输入购买重量:")

# 3. 计算金额
# 1> 将单价转换成小数
price = float(price_str)

# 2> 将重量转换成小数
weight = float(weight_str)

# 3> 计算付款金额
money = price * weight

print(money)

(2)例2:

# 1.将单价转换成小数
price = float(input("请输入单位重量的价格:"))

# 2.将重量转换成小数
weight = float(input("请输入购买重量:"))

# 3.计算付款金额
money = price * weight

print(money)

Guess you like

Origin blog.csdn.net/Zevalin/article/details/135409460