# "Python Core Programming" chapter Fifth: Numbers

Source: Internet
Author: User

Outline of this chapter
Describes the many numeric types supported by Python, including: integer, long, Boolean, double-precision floating-point, decimal floating-point, and complex. Describes numbers-related operators and functions.

Knowledge point 5.1 Boolean
Support bool from Python2.3, value range: True, False

5.2 Standard integer
On 32-bit machines, the range of standard integer types is: 31 to the power of -2 to 31 to the power of 2 -1
-Python standard integer types are equivalent to C (signed) long integers.
-Octal integers begin with the number "0", hexadecimal integers begin with "0x" or "0X"

5.3 Long integer
The value that Python's long integer type can express is only related to the (virtual) memory size supported by the machine.
Add an uppercase L after an integer value to indicate a long integer.
Integers are automatically converted to long integers if necessary.
5.4 Double-precision floating-point numbers
8 bytes per floating point number
C-like double
Floating point values usually have a decimal point and an optional suffix e, eg: 9.384e-23
5.5 plural
Python 1.4 supports plurals
Imaginary number: real + imagj, eg: 6.23 + 1.5j
Plural attributes:
-num.real: the real part of the complex number
-num.imag: imaginary part of a complex number
-num.conjugate (): returns the complex conjugate of the complex number

5.6 Numerical type conversion
Before the operation between different data types, Python internally converts the two operands to the same data type (casting).

Basic principles for conversion of different data types: integers are converted to floating-point numbers, non-complex numbers are converted to complex numbers.

Numerical type coercion process:
Use the built-in function coerce () to perform a special type conversion on a data type.

5.7 Operators
/: Division operation. If both numbers are integers, the division is performed. Otherwise, real division is performed. (The standard behavior of division in future versions of Python: No matter whether the operand is an integer or a floating-point number, the division operation always returns the real quotient. At this stage, the true division can be achieved by executing the from __future__ import division instruction)
//: Floor division (rounded down)
%: Take the remainder. For floating-point numbers, the result is: x-(math.floor (x / y) * y)
**: power operation, the operator has higher priority than the unary operator of the left operand and lower priority than the unary operator of the right operand (the boss on the right)
-3 ** 2 # has higher priority than the left-
4.0 ** -1.0 # Priority is lower than on the right-
Bitwise operator: the highest priority is negation, followed by left shift and right shift, the lowest is AND, OR, XOR or
5.8 Numeric Functions 5.8.1 Conversion Factory Functions
int (4.25555) # 4
long (42) # 42L
float (4) # 4.0
complex (2.3e-10, 45.3e4) # (2.3e-10 + 453000j)
5.8.2 Function Functions
abs (num): Returns the absolute value of the given parameter. eg: abs (-1) # 1
coerce (num1, num2): Returns a tuple containing two numeric elements after type conversion. eg: coerce (1.23-41j, 134L) # ((1.23-41j), (134 + 0j))
divmod (num1, num2): Combines division and remainder operations to return a tuple containing quotient and remainder. eg: divmod (10,3) # (3, 1)
pow (num1, num2, mod = 1): exponential operation, eg: pow (2,3). If the mod parameter is provided, then the remainder operation is performed on the mod
round (flt, ndig = 0) takes a floating-point number flt and rounds it, and saves ndig decimal places. If no ndig parameter is provided, the default is 0 digits after the decimal point
5.8.3 Functions for integers only
5.9 Other Number Types 5.9.1 Boolean "Numbers"
There are two values that never change, True or False.
A boolean is a subclass of integer, but it can no longer be inherited to generate a subclass of it.
The default value for objects without the __nonzero __ () method is True.
The boolean value in Python is False for any number or empty set (zero list, empty tuple, empty dictionary, etc.) with a value of zero.
In mathematical operations, True and False for Boolean values correspond to 1 and 0, respectively.
Most standard library functions and built-in Boolean functions that previously returned integers now return Booleans.
Neither True nor False are keywords, but they will be in future versions of Python.
5.9.2 Decimal
from decimal import Decimal
dec = Decimal (‘. 1‘)
result = dec + Decimal (‘10 .1 ‘)
5.10 Digital Type Related Modules
Third-party packages: Numeric (NumPy) and SciPy
array: efficient array of numbers (characters, integers, floating point numbers, etc.)
math / cmath: Mathematical functions of the standard C library. General mathematical operations are in the match module, and complex number operations are in the cmath module.
operator: Function implementation of numeric operators
random: various pseudo-random number generators
random.randrange (100, 110, 3) # 103, return one item of range ([start,] stop [, step]) result randomly
random.uniform (1.1, 1.34) # 1.300319482480275, which returns a floating point number between the two (excluding the upper limit of the range)
random.randint (12,23) # 21, which returns an integer between the two (including the upper limit of the range)
random.random () # 0.926576527700594, similar to uniform (), except that the lower limit is always equal to 0.0 and the upper limit is always equal to 1.0
random.choice ([1,2,4]) # 4, return one element of the given sequence randomly
Exercise
5-1 Shaping. Talk about the difference between Python's ordinary integers and long integers.
Ordinary integer: 63 square -1 (64-bit machine)
Long integer: The maximum number that can be represented is only related to the memory of the machine. When an ordinary integer "overflows", Python can automatically convert it to a long integer.

5-2 operators.
(a) Write a function that calculates and returns the product of two numbers
(b) Write a code to call this function and display its result

def multiply (num1, num2):
return num1 * num2

print multiply (7, 11)
5-3 Standard type operator. Write a script, input a test score, and output his score (A-F) according to the following criteria. A: 90--100 B: 80--89 C: 70--79 D: 60--69 F: <60

if score> = 90:
return ‘A’
elif score> = 80:
return ‘B’
elif score> = 70:
return ‘C’
elif score> = 60:
return ‘D’
else:
return ‘F’
5-4 Take the remainder. Determines whether the given year is a leap year. Use the following formula: A leap year means that it is divisible by 4 but not by 100, or it is divisible by 400. For example, 1992, 1996 and 2000 are leap years, but 1967 and 1900 are not leap years. The next one is the entire age of the leap year is 2400 years.

def is_leep_year (year):
if year% 4 == 0:
if year% 100! = 0:
return True
elif year% 400 == 0:
return True
else:
return False
else:
return False

print is_leep_year (1992)
print is_leep_year (2000)
print is_leep_year (1900)
print is_leep_year (1999)
5-5 Take the remainder. Take any amount less than \$ 1 and calculate how many coins you can exchange for. There are four types of coins: 1 cent, 5 cents, 10 cents, and 25 cents. One dollar is equal to 100 cents. For example, a \$ 0.76 conversion result would be three 25 cents and one 1 cent. Results like 76 1 cents, 2 25 cents + 2 10 cents + 1 5 cents + 1 1 cent are not satisfactory.

Idea: first take the large denomination, then take the small denomination, and get the combination of the least coins

def get_cent_count (num):
cent_count_arr = []
cents = [25, 10, 5, 1]

left = num
i = 0
while left! = 0:
cent_count_arr.append (left // cents [i])
left = left% cents [i]
i + = 1

return cent_count_arr

print get_cent_count (76)
print get_cent_count (123)
print get_cent_count (88)
5-6 Arithmetic. Write a calculator program. Your code can accept such an expression. Two operands plus one operator: N1 operator N2. Where N1 and N2 are integers or floating point numbers. ,%, ** represent addition, subtraction, multiplication, integer division, remainder and power operations. The result of this expression is evaluated and then displayed. Tip: You can use the string method split (), but you cannot use the built-in function eval ().

Idea: If you use eval (), you can directly calculate the result of the expression: eval (‘3 * 4’). Here you need to convert a numeric string into a number. Since you don't know the type of the number, it is more convenient to use Decimal for conversion. Of course, it is possible to judge one by one number type.

import decimal

def num1_op_num2 (op_str):
arr = op_str.split ()
op = arr 
num1 = decimal.Decimal (arr )
num2 = decimal.Decimal (arr )

if op == ‘+‘:
return num1 + num2
elif op == ‘-‘:
return num1-num2
elif op == ‘*‘:
return num1 * num2
elif op == ‘/‘:
return num1 / num2
elif op == ‘%’:
return num1% num2
elif op == ‘**‘:
return num1 ** num2
else:
raise ValueError ("op do n‘t exist")

print num1_op_num2 ("3 * 4")
print num1_op_num2 ("11% 7")
print num1_op_num2 ("5 ** 2")
5-7 Business tax. Take a commodity amount at will, and then calculate the sales tax that should be paid based on the local sales tax amount.
slightly.

** 5-8 geometry. Calculate area and volume:
(a) Square and cube
(b) Circle and ball. **
slightly.

(a) Why is 17 + 32 equal to 49, 017 + 32 equals 47, and 017 + 032 equals 41 in the following example?

(B) Why does the following expression give us 134L instead of 1342?
Because: the number ends with l (L, not 1) for long

5-10 conversion. Write a pair of functions to do Fahrenheit to Celsius conversion. The conversion formula is C = (F-32) * (5/9) You should use true division in this exercise, otherwise you will get incorrect results.

from __future__ import division

def tran_F_to_C (F):
C = (F-32) * (5/9)
return round (C, 2) # take two decimal places

print tran_F_to_C (42)
5-11 Take the remainder.
(a) Use loops and arithmetic operations to find all even numbers between 0-20
(b) Same as above, but this time output all odd numbers
(c) Combining (a) and (b), what is the easiest way to distinguish between odd and even numbers?
(d) Using the result of (c), write a function that checks whether an integer is divisible by another integer. First ask the user to enter two numbers, then your function determines whether there is a divisibility relationship between the two, and returns True and False respectively according to the judgment results;
slightly.

5-12 System limitations. Write a script to verify the range of integers, long integers, floating point numbers, and complex numbers your Python can handle.

import sys

print sys.maxint
print -sys.maxint-1
print sys.float_info
print sys.long_info
result:

2147483647
-2147483648
sys.float_info (max = 1.7976931348623157e + 308, max_exp = 1024, max_10_exp = 308, min = 2.2250738585072014e-308, min_exp = -1021, min_10_exp = -307, dig = 15, mant_dig = 53, epsilon = 2.220446049250313e-16 , radix = 2, rounds = 1)
sys.long_info (bits_per_digit = 30, sizeof_digit = 4)
5-13 Conversion. Write a function that converts time represented by hours and minutes to time represented by minutes only.
slightly.

5-14 Bank interest. Write a function that takes the time deposit rate as a parameter. Assuming that the account calculates compound interest daily, please calculate and return the annual rate of return.

def compound_interest (rate):
return (1 + rate) ** 364

print compound_interest (0.0005)
5–15 Greatest common divisor and least common multiple. Calculate the greatest common divisor and the least common multiple of two integers.

def gcd (num1, num2):
while num2> 0:
tmp = num1% num2
num1 = num2
num2 = tmp
return num1

def lcm (num1, num2):
return num1 * num2 / gcd (num1, num2)

print gcd (24, 18)
print lcm (24,18)
5-16 Home finances. Given an initial amount and monthly expenses, use a cycle to determine the remaining amounts and expenses for the current month, including the final expenses. The Payment () function will use the initial amount and monthly amount. The output should be similar to the following format (the numbers in the example are for demonstration purposes only):
def pay ():
balance = float (raw_input (‘Enter opening balance:‘))
balance = round (balance, 2)
payment = float (raw_input (‘Enter monthly payment:‘))
payment = round (payment, 2)

print ‘\ tAmount \ tRemaining’
print ‘Pymt # \ tPaid \ tBalance’
print ‘------ \ t ------ \ t ------‘

print ‘0 \ t \$ 0.00 \ t \$% s’% balance
i = 1
while balance> payment:
balance-= payment
balance = round (balance, 2)
print ‘% d \ t \$% s \ t \$% s’% (i, payment, balance)
print ‘% d \ t \$% s \ t \$ 0.00’% (i, balance)

pay ()
5-17 random numbers. Familiarize yourself with the random number module and then solve the following problem: Generate a list of N elements with a random number n, where the values of N and n are: (1 <N <= 100), (0 <= n <= 2 ^ 31 -1). Then randomly take N (1 <= N <= 100) random numbers from this list, sort them, and then display this subset.

import random

def rand_sort_num ():
res = []
N = random.randint (1, 100)
while N> 0:
n = random.randint (0, 2 ** 31-1)
res.append (n)
N-= 1

res.sort ()
return res

print rand_sort_num ()
"Core Programming in Python" Chapter 5: Numbers

Related Keywords:
Related Article

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.