1. Objects 对象

Everything could be an object! 万物皆对象! 比如:500

graph TD
    A[OBJECT]:::redCircle
    B[VALUE]:::lightBlueRect -->|500| A
    C[DATA TYPE]:::lightBlueRect -->|integer| A
    D[LOCATION]:::lightBlueRect -->|140176731168400| A

    classDef redCircle fill:#ff5252, color:white, stroke:black, stroke-width:2px, shape:circle
    classDef lightBlueRect fill:#4fc3f7, color:black, stroke:black, stroke-width:1px, rx:5px, ry:5px

2. Numeric Data Types 数值数据类型

int vs float

int整数:

  • Whole numbers without fractional part 没有小数部分的整数
  • Examples: 5, 4, 3, 6
  • Exact representation 精确表示

float浮点数:

  • Decimal fractions 十进制小数
  • Examples: .25, .10, .05, .01
  • Approximation only 近似表示

Determining Data Types 确定数据类型

>>> type(3)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type(3.0)
<class 'float'>
>>> myInt = 32
>>> type(myInt)
<class 'int'>

Why Two Number Types? 为什么需要两种数字类型?

  • Counts can’t be fractional 计数不能是分数
  • Integers are exact and efficient 整数精确且高效
  • Floats are only approximations 浮点数只是近似值

Float Precision Issue 浮点数精度问题

Why floats are approximate? 为什么浮点是近似的?

  • Computers use binary representation 计算机使用二进制表示
  • Some decimals have infinite binary representations 某些十进制数有无限的二进制表示

Example示例: 0.1 in binary 0.1的二进制表示

0.1 * 2 = 0.2 → 0
0.2 * 2 = 0.4 → 0
0.4 * 2 = 0.8 → 0
0.8 * 2 = 1.6 → 1
0.6 * 2 = 1.2 → 1
0.2 * 2 = 0.4 → 0  # Repeats forever 无限循环

Result: 0.0001100110011... (infinite) 无限循环

Number Systems 数字系统

  • Octal八进制0o or 0O prefix
  • Hexadecimal十六进制0x or 0X prefix
  • Binary二进制0b or 0B prefix

Integer Characteristics int整数特性

  • No size limitation 无大小限制
  • Can express very large numbers precisely 可以精确表示非常大的数字
  • Example: 100! (158-digit integer) 100的阶乘(158位整数)

Float Characteristics 浮点数特性

  • Full accuracy cannot be guaranteed 不能保证完全准确
  • Only 17 significant digits retained 只保留17位有效数字
  • Range范围: 1.7*10^-308 to 1.7*10^308

Boolean布尔类型

  • Only two values: True or False
  • In math operations: True = 1False = 0
  • Empty collections are False 空集合为False

3. Type Conversions & Rounding 类型转换和舍入

Mixed-type Expressions 混合类型表达式

x1 = 5 * 2        # int * int → int
x2 = 5.0 * 2.0    # float * float → float  
x3 = 5.0 * 2      # float * int → float

Explicit Type Conversion 显式类型转换

int():

>>> int(3.9)      # Truncates, not rounds 截断,不四舍五入
3
>>> int('32')     # String to int 字符串转整数
32
>>> int('1010', 2) # Binary to decimal 二进制转十进制
10

float():

>>> float(3)      # int to float 整数转浮点数
3.0
>>> float('3.14') # String to float 字符串转浮点数
3.14

bool():

>>> bool(0)       # False
False
>>> bool(1)       # True
True
>>> bool('')      # Empty string → False 空字符串为False
False

round():

>>> round(3.14159, 2)  # Round to 2 decimal places 保留2位小数
3.14

Character Functions 字符函数

ord():

>>> ord("A")
65
>>> ord('a')
97

chr():

>>> chr(97)     # Get character from code 从代码获取字符
'a'
>>> chr(65)
'A'

Solutions for Floating-point Precision 浮点数精度解决方案

  1. Use round() 使用round函数
  2. Use decimal module 使用decimal模块
  3. Limit decimal places in output 限制输出小数位数

4. eval()函数的安全问题

Dangers of eval() eval()的危险性

正如eval()函数中提到

本质是将字符串作为Python表达式求值

所以:

  • Code injection attacks 代码注入攻击
  • Malicious users can execute dangerous code 恶意用户可执行危险代码

Safer Alternatives 更安全的替代方案

# Instead of eval 替代eval
>>> int("32")     # Safe for integers 整数安全
32
>>> float("32")   # Safe for floats 浮点数安全
32.0

Limitations限制:

  • Doesn’t support simultaneous input 不支持同时输入多个值
  • Use appropriate conversion functions instead 使用适当的转换函数替代

5. Built-in Numeric Operators 内置数值运算符

Arithmetic Operators 算术运算符

Priority优先级 (Highest to lowest 从高到低):

  1. ** Exponentiation 幂运算
  2. *///% Multiplication, division, etc. 乘除等
  3. +- Addition, subtraction 加减

Division Types除法类型:

  • Float Division (/): Result is float 结果是浮点数
  • Integer Division (//): Result is integer (floor division) 结果是整数(向下取整)

Modulo Operator (%) 取模运算符:

# Divisibility 可整除性
a % 4 == 0 and a % 100 != 0  # Leap year condition 闰年条件
 
# Even/Odd 奇偶性
a % 2 == 0  # Even number 偶数
 
# Range checking 范围检查
a % 7  # Results: 0,1,2,3,4,5,6

Multiple Use of Operators 运算符的多重用途

+ Operator:

>>> 'abcd' + '1234'        # String concatenation 字符串连接
'abcd1234'
>>> [1,2] + [3,4]          # List concatenation 列表连接  
[1,2,3,4]
>>> True + 3               # Boolean arithmetic 布尔运算(True=1)
4

Relational Operators 关系运算符

><==<=>=!= Multiple comparisons 多重比较:

3 < 4 < 5        # Equivalent to: 3 < 4 and 4 < 5

Logical Operators 逻辑运算符

Python中不使用! && ||,而是使用not and or

Priority优先级not > and > or

not True and False   # Evaluates as: (not True) and False

5.1 Exercise: Leap Year 练习:闰年判断

Task任务: Determine if your birth year is a leap year 判断出生年份是否为闰年

Condition条件:

  • Divisible by 4 but not by 100 能被4整除但不能被100整除
  • OR divisible by 400 或能被400整除

Formula公式(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

6. Numeric Operator Functions 数值运算符函数

Built-in Functions 内置函数

  • abs(): Absolute value 绝对值
  • pow(x, y): x to the power y x的y次幂
  • min()max()sum(): Minimum, maximum, sum 最小值、最大值、求和
  • divmod(num1, num2): Returns quotient and remainder 返回商和余数

7. Math Library 数学库

Importing Libraries 导入库

Three ways三种方式:

import math                    # Access: math.sqrt()
from math import *            # Access: sqrt()  
from math import sqrt, sin    # Access: sqrt(), sin()

Quadratic Equation Example 二次方程示例

# quadratic.py
import math
 
def main():
    print("This program finds the real solutions to a quadratic")
    a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
    
    discRoot = math.sqrt(b * b - 4 * a * c)
    root1 = (-b + discRoot) / (2 * a)
    root2 = (-b - discRoot) / (2 * a)
    
    print("The solutions are:", root1, root2)

Note: Crashes if no real roots (negative discriminant) 如果没有实根(负判别式)会崩溃

Math Library Functions 数学库函数

  • math.sin(x): Sine of x radians x弧度的正弦值

  • math.asin(x): Arc sine of x, in radians x的反正弦值(弧度)

  • math.radians(degrees): Convert degrees to radians 角度转弧度

7.1 Exercises 练习:数学

Distance Between Two Points 两点间距离

Formula公式distance = sqrt((x2-x1)^2 + (y2-y1)^2)

Area of a Circular Segment 弓形面积计算

Input输入: Lengths of chord AB and sagitta CD 弦长AB和矢高CD
Process处理: Use trigonometric functions 使用三角函数
Output输出: Area rounded to 2 decimal places 面积保留2位小数

8. Random Library 随机库

Random Walk Example 随机游走示例

Brownian Motion布朗运动: Stock price changes 股票价格变化

Simple Random Walk简单随机游走:

  • Heads: step forward 正面:前进一步

  • Tails: step backward 反面:后退一步

2D Random Walk二维随机游走:

  • Random angle generation 随机角度生成

  • Coordinate updates 坐标更新

9. Time Library 时间库

Timing Program Execution 程序计时

from time import process_time
 
start = process_time()
# Your code here 你的代码
end = process_time()
 
print(round(end-start, 2), "s consumed.")

time() vs process_time():

  • time(): Returns clock time 返回时钟时间

  • process_time(): Returns CPU time (excludes sleep) 返回CPU时间(不包括睡眠时间)

10. Accumulating Results: Factorial 累加结果:阶乘

Factorial Definition 阶乘定义

n! = n × (n-1) × (n-2) × ... × 1
Example: 6! = 6 × 5 × 4 × 3 × 2 × 1 = 720

Accumulator Pattern 累加器模式

def main():
    n = eval(input("Please enter a whole number: "))
    fact = 1
    for factor in range(n, 1, -1):  # Count down 递减计数
        fact = fact * factor
    print("The factorial of", n, "is", fact)

Range Function range函数

range()函数

>>> list(range(10))         # [0, 1, 2, ..., 9]
>>> list(range(5, 10))      # [5, 6, 7, 8, 9]  
>>> list(range(5, 10, 2))   # [5, 7, 9]
>>> list(range(10, 1, -1))  # [10, 9, 8, ..., 2]
>>> list(range(10, 1))      # []

11. NumPy Financial Library NumPy金融库

Installation安装

pip install numpy_financial

Future Value未来值计算

import numpy_financial as npf
 
# fv(rate, nper, pmt, pv, when='end')
future_value = npf.fv(rate=0.02, nper=5, pmt=-1000, pv=0)
# Output: 5308.12

Loan Installment贷款分期

import numpy_financial as npf
 
# pmt(rate, nper, pv, fv=0, when='end')
payment = npf.pmt(rate=0.05/12, nper=60, pv=-10000)
# Calculate monthly payment 计算月付款

Formatting operator 格式化操作符

"%d%7.2f" % (year, future_value)  # Integer and float formatting 整数和浮点数格式化
格式符格式格式符格式
%c单个字符%s字符串
%d或%i十进制整型%f或%F浮点型
%e或%E浮点型的科学计数法%%输出一个单一的%
辅助符号作用
m.nm是显示的最小总宽度,n是小数点后的位数(如果有的话)
0位数显示不够m时,前面用0填充,而不是默认的空格

12. Summary 总结

Key Concepts关键概念

  • Numbers数字intfloatboolean

  • Numeric Operators数值运算符: Arithmetic, relational, logical 算术、关系、逻辑

  • Type Conversions类型转换int()float()bool()round()

  • Math Library数学库import mathmath.sqrt(), etc.

  • Accumulator Pattern累加器模式: Building results incrementally 逐步构建结果

Libraries Covered涉及的库

  • math: Mathematical functions 数学函数

  • random: Random number generation 随机数生成

  • time: Program timing 程序计时

  • numpy_financial: Financial calculations 金融计算

下一章