Python_ Practical Introductory Article _07

Source: Internet
Author: User
Tags integer division mathematical functions square root string format

Python built-in types of numbers and the Zen of Python

1. Digital type concept

Python numeric data types are used to store numeric values, and data types are not allowed to change, which means that if you change the value of a numeric data type, the memory space is redistributed.

Look at the figure, the number type is immutable, suppose you create a Number object type box for the number 1, if you want to add 2 to the box, is not allowed, which involves the knowledge of memory address. So you can only create one more number Type box for 2. The memory address of the two boxes is different. ↓

2. Types of Numbers

   1. Integral type (INT)

       is usually referred to as an integral or integer, a positive or negative integer, with no decimal points. The Python3 integral type is not limited in size and can be used as a Long type. That is, in Python3, you can create very large integers and not go out of scope.

The integers are represented by 16 binary and octal:

# hex >>> number#  octal >>> number 31

2. Float type (float)

        floating-point types consist of integral and fractional parts, and floating-point types can also be represented by scientific notation (2.5e2 = 2.5 x 2 = +)

3. plural ((complex))

       ① The complex number is made up of real and imaginary parts and can be represented by a + BJ, or complex (a, b), where both the real and imaginary part of a complex number are floating-point types.

② complex functions for complex types:

The complex () function is used to create a complex number or to convert a count or a string to a complex form with a return value of one plural. The syntax for this function is: Class complex (Real,imag)

Where real can be an int, a long, a float, or a string type, and an image can be of type int, long, or float only.

a=4.7+0.666j           # defines an imaginary print(a)               # output This imaginary print(a.real          # output Real part print(a.imag)          # output imaginary part print( A.conjugate ())   # outputs the conjugate complex number of the complex number

Note: conjugate () is a built-in function of the complex class, acting as the conjugate complex of the output complex number.

         ③ the output of complex numbers

1. string format character output

a=4.7+0.666jPrint('%r effect is:')print('%r '%(a)'print('%s ' effect:')Print ('%s'%(a))The effect of >>>% R is: (4.7+0.666j  The effect of% s is: (4.7+0.666j)

2.format formatted output

"{0.real:.3f}{0.imag:+.3f}j". Format (4.2344+5.3445j

       ④python does not support the conversion of complex numbers to integers or floating-point numbers, error

>>> Float (4.5+0j) Traceback (most recent call last):  "<pyshell#5>"   in <module>

3. Conversion of numeric types

Sometimes, we need to convert the data-built type into the data type, and you just need to use the data type as the function name.

    • int (x) converts x to an integer.

    • float (x) converts the x to a floating-point number.

    • Complex (x) converts x to a complex number, the real part is x, and the imaginary part is divided into 0.

    • complex (x, y) converts x and y to a complex number, the real part is x, and the imaginary part is Y. X and y are numeric expressions.

>>> a = 1.0>>> int (a)1

4. Arithmetic of numeric type

1.+-*/(corresponds to subtraction respectively)

>>> 2 + 24>>> 50-5*620>>> (50-5*6)/45.0>>> 8/51.6

Note: Division returns must be a floating-point number

2.//and% (respectively, corresponding to the floor in addition to the modulo operation)

>>> 17/3  #  integer division returns floating-point 5.666666666666667>>>>>> +//3  # integer division Returns the result of rounding down 5>>> 3  #  % operator returns the remainder of Division 2

Note: The floor except//does not always return integers, such as 7.0//2>>>3.0. It depends on the number type of the numerator denominator.

3.** (Power operation)

>>> 5 * * 2  #  5 squared 25>>> 2 * * 7  #  2 7-Time Square 128

Note: The floating-point number in Python is multiplied by an integer or a floating-point number, as well as division.

5. Functions of numeric types

Mathematical functions:
function return value (description)
ABS (x) Returns the absolute value of a number, such as ABS (-10) returns 10
Ceil (x) Returns the top integer of a number, such as Math.ceil (4.1) returns 5

CMP (x, y)

If x < y returns 1, if x = = y returns 0, if x > y returns 1. Python 3 is deprecated . Replace with use (x>y)-(x<y) .
EXP (x) Returns the x power of E (ex), such as MATH.EXP (1) returns 2.718281828459045
Fabs (x) Returns the absolute value of a number, such as Math.fabs (-10) returns 10.0
Floor (x) Returns the lower integer of a number, such as Math.floor (4.9) returns 4
Log (x) If Math.log (MATH.E) returns 1.0,math.log (100,10) returns 2.0
LOG10 (x) Returns the logarithm of x with a base of 10, such as MATH.LOG10 (100) returns 2.0
Max (x1, x2,...) Returns the maximum value of a given parameter, which can be a sequence.
Min (x1, x2,...) Returns the minimum value for a given parameter, which can be a sequence.
MODF (x) Returns the integer portion of x and the fractional part, the two-part numeric symbol is the same as x, and the integer part is represented by a floating-point type.
Pow (x, y) The value after the x**y operation.
Round (x [, N]) Returns the rounded value of the floating-point number x, if given an n value, that represents the digits rounded to the decimal point.
sqrt (x) Returns the square root of the number x.
Random number function:

Random numbers can be used in mathematics, games, security and other fields, but also often embedded in the algorithm to improve the efficiency of the algorithm and improve the security of the program.

Python contains the following common random number functions:

function Description
Choice (seq) Pick an element randomly from the elements of the sequence, such as Random.choice (range (10)), and randomly pick an integer from 0 to 9.
Randrange ([Start,] stop [, step]) Gets a random number in the collection that increments by the specified cardinality from the specified range, and the base default value is 1
Random () Randomly generates the next real number, which is within the [0,1] range.
Seed ([x]) Changes the seeding seed of the random number generator. If you don't know how it works, you don't have to specifically set Seed,python to help you choose Seed.
Shuffle (LST) Randomly sort all elements of a sequence
Uniform (x, Y) Randomly generates the next real number, which is within the [x, Y] range.
Trigonometric function

Python includes the following trigonometric functions:

function Description
ACOs (x) Returns the inverse cosine radian value of x.
ASIN (x) Returns the arc value of the arc sine of X.
Atan (x) Returns the arc tangent value of x.
Atan2 (y, x) Returns the inverse tangent value of the given X and Y coordinate values.
COS (x) Returns the cosine of the arc of X.
Hypot (x, y) Returns Euclidean norm sqrt (x*x + y*y).
Sin (x) Returns the sine of the X radian.
Tan (x) Returns the tangent of x radians.
Degrees (x) Convert radians to angles, such as degrees (MATH.PI/2), returns 90.0
Radians (x) Convert an angle to radians

Zen of 6.Python

    1.Python programmers believe that code can be beautifully written and elegant. Programming is about solving problems, and a well-designed, efficient and beautiful solution will pay tribute to the programmer.

Simple is better than complex.

2. If there are two solutions, one simple, one complex, but all effective, choose a simple solution. This way, the code you write will be easier to maintain, and it will be easier for you or others to improve the code later.

Complex is better than complicated.

3. The reality is complex, and sometimes there may be no simple solution. In this case, choose the simplest and most feasible solution.

Readability counts.

4. Even complex code makes it easy to understand. When you develop a project that involves complex code, be sure to write useful comments for the code.

There should is one--and preferably only one--obvious the-do it.

5. If you let two Python programmers solve the same problem, they should provide a similar solution. This is not to say that programming has no creative space, but rather the opposite! However, most programming work uses common solutions to solve simple small problems, but these small problems are included in larger, more creative projects. In your program, the specifics of the details should be easy to understand for other Python programmers.

Now is better than never.

You can browse the guidelines by executing the command import this in a Python terminal session.

7. Supplementary knowledge about the type of digital

1.random.randint (x, y) #随机生一个整数int类型, you can specify the range of this integer

Random.randint (1000,9999)>>>8449

2.PYTHON3 obsolete CMP () function (if x < y returns 1, if x = = y returns 0, if x > y returns 1), the following five functions are substituted:

 import operator       # first the operator module to be imported operator.gt      #  meaning greater than (greater than)operator.ge (+)      # means greater and equal (greater than or equal)Operator.eq      # meaning equal (equals)Operator.le      # it means less and equal (below or equal)operator.lt      # means less than (smaller than)

PS (Bloggers hope you will inherit the will of Python, write more elegant and simple code, every day will update all content, make the content more refined)

Python_ Practical Introductory Article _07

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.