Basic data type of Python language - Number/Bool/String(3-1)

2, Data type

Like dynamic type programming languages such as Scheme, Ruby, Perl and Tcl, python has a dynamic type system and garbage collection function, which can automatically manage memory usage. Python's built-in basic types mainly include number, bool, string, list, tuple, set, and * * dictionary *.

1. Number

Number types in Python 3.x include int (integer), float (floating point) and complex (complex). Python 3.x combines long with int, leaving int. Generally, the definition and assignment of numerical variables can be completed in one step, as follows:

a = 12
b = -30

1.1 in the Python environment, you can use the following code to view the maximum value of int type that can be used by the current computer.

>>> import sys
>>> print(sys.maxsize)

1.2 the float type floating-point number of Python is represented by the native double precision (64bit) of the floating-point number on the machine, providing a precision of about 17 bits and an exponent from - 308 to 308. Python does not support 32bit single precision floating-point numbers. If the program needs to accurately control the interval and digital accuracy, consider using Numpy module. Floating point numbers of 3.x are 17 bit precision by default.

Floating point type in C language is divided into single precision type and double precision type. The single precision type is defined by float, and the double precision type is defined by double.
The single precision type occupies 4 bytes (32 bits) of memory space and can only provide 7 significant digits.
The double precision type occupies 8 bytes (64 bits) of memory space and can provide 16 significant digits.

int type and float type numerical values can be directly added, subtracted, multiplied, divided, multiplied and remainder. It should be noted that the single divisor "/" operator always returns a floating-point number. To obtain integer results, the double divisor "/ /" operator should be used. In mixed computation, Python converts an integer to a floating point number.

In practice, if higher precision (more than 17 decimal places) is required, the decimal module can be used in combination with getcontext() function to set the required precision, as follows:

from decimal import *
getcontext().prec = 50  # Set to retain 50 decimal places
print(Decimal(1)/Decimal(9))   # 0.11111111111111111111111111111111111111111111111111
print(Decimal(1)/Decimal(19))  # 0.052631578947368421052631578947368421052631578947368
# The default of float type is 17 bit precision
print(float(Decimal(1)/Decimal(19)))    # 0.05263157894736842

In specific work, it is usually necessary to convert high-precision float type values into low-precision values, such as * * "rounding": part of the data to the right of the decimal point is discarded. In Python, the built-in round() function * * is usually used, as follows:

round(1.5)      #  2
round(2.5)      #  2
round(2.6)      #  3

If there is only one number as a parameter and the number of digits is not specified, an integer is returned and is the integer closest to the number (similar to rounding). When ". 5" appears, the distances on both sides are the same, then the round() function takes an even number close to this number, as above.

If the number of decimal places is specified, if the leftmost part to be discarded is 5 and the left side of 5 is an odd number, it will be discarded directly; If 5 is an even number on the left, round it up as follows

round(2.635, 2)     # 2.63
round(2.645, 2)     # 2.65
round(2.655, 2)     # 2.65
round(2.665, 2)     # 2.67
round(2.675, 2)     # 2.67

In addition to the round() function, the ceil() and floor() functions in the math module can also round up or down, as follows:

from math import ceil, floor
round(2.5)   #  Returns the integer closest to this number. The distance between the two sides of. 5 is the same, and the even number close to this number is taken. two
ceil(2.5)    #  Round up 3
floor(2.5)   #  Round down 2
round(2.3)   #  Returns the integer 2 closest to this number
round(2.7)   # 3
ceil(2.3)    #   Round up 3
floor(2.3)   #   Round down 2

Python uses the complex() function to create a complex number. Its parameters can be numeric or string, as follows:

print(complex(1))        # (1+0j)
print(complex(1, 2))     # (1+2j)
print(complex('1+2j'))   # (1+2j)

Note: the second parameter cannot be passed in a string. When converting from the plural form of a string to the plural form, spaces cannot appear in the string, as follows:

complex('1+2j')      # The format is correct, and the value is (1+2j)
complex('1 +2j')     # Format error, error ValueError: complex() arg is a malformed string
complex('1 + 2j')    # Format error, error ValueError: complex() arg is a malformed string

2. Bool (Boolean)
Bool types in Python are mainly represented by reserved words of True and False. Bool types are usually used in statements such as if and while. It should be noted that the bool type in Python is a subclass of int (inherited from int), which will return True as follows:

True==1     # True
False==0    # True

Therefore, in the numerical context, True and False can participate in numerical operations, as follows:

True+3==4    # True

True can be understood as 1 and False as 0. In fact, Python will determine the following data as False
3) 0 value of numeric type, such as 0, 0.0, 0j (complex number with imaginary part of 0).
4) , empty sequence, such as' ', (), [].
5) , empty mapping, such as {}.
6) , a user-defined class that defines a bool() or len() method, and the method returns a value of 0 or False.


String is a string of characters composed of numbers, letters and underline. It is the data type expressing text in programming language. In Python 3.x, all strings are stored in Unicode encoding.
The declaration string can use single quotation marks or double quotation marks. The typical string assignment statements in Python are as follows:

str='hello world'

Python does not support single character type, which is also used as a string in Python. To get part of a string, you can use square brackets' [] 'to intercept the string, as follows:

str1='Hello World'
print(str1[0:5])    # hello Description: intercept the characters with subscripts from 0 to 4 (the left subscript starts from 0 and follows the principle of closing left and opening right)

String supports operations such as interception, connection and repeated output. The operation operators supported by string in Python are shown in the following table:

Escape characters are required to use special characters in strings. Python uses the backslash "\" to escape characters. The characters used for escape in Python are as follows:

Python supports formatting output strings. The purpose is to display the strings to be output in a preset format, as follows:

print("%s this year%d Years old!"%('millet',10))     # Xiaomi is 10 years old this year!

There are 13 symbols used to format the output string in Python, as shown in the following table:

Python also provides many functions related to string operation. The common string functions are as follows:

str='hello world'
print(str)           #  hello world
print(str.title())      # Hello World
print(str.istitle())     # False
print(str.capitalize())    #  Hello world
print(str.upper())           # HELLO WORLD
str1='Hello World'
print(str1)      # Hello World
print(str1.lower())    #   hello world
print(str1.swapcase())  # hELLO wORLD
print(str1.startswith("H"))    # True
print(str1.endswith("s"))     # False
print(str1.find("o"))    # 4
print(str1.count('l'))    # 3

Tags: Python Ruby

Posted on Fri, 10 Sep 2021 18:10:22 -0400 by doofystyle