Validation & verification · 验证与核对
Why validate input
- Validation checks that input is sensible before the program uses it.
- "Garbage in, garbage out" — bad data leads to wrong answers.
- The program decides to accept or reject the value.
为什么要验证输入
- 验证(validation)在程序使用输入之前,检查它是否合理。
- “垃圾进,垃圾出” —— 坏数据会导致错误的结果。
- 程序据此决定接受还是拒绝这个值。
The validation steps · 验证的步骤
Read the input, check · 校验 it, then accept or reject — bad data never gets used. · 读取输入,检查它,再接受或拒绝 —— 坏数据永远不会被使用。
Range check
- A range check makes sure a number is between a low and a high limit.
- Example: a month must be from 1 to 12.
范围检查
- 范围检查(range check)确保一个数字在下限和上限之间。
- 例如:月份必须是 1 到 12。
month = 13
if 1 <= month <= 12:
print("Accepted")
else:
print("Rejected")
Length check
- A length check makes sure text is not too short or too long.
len(text)gives the number of characters.
长度检查
- 长度检查(length check)确保文本不太短、也不太长。
len(text)给出字符的个数。
password = "abc"
if len(password) >= 8:
print("Accepted")
else:
print("Too short")
Presence check
- A presence check makes sure something was actually entered.
- An empty string
""means the user typed nothing.
存在性检查
- 存在性检查(presence check)确保确实输入了内容。
- 空字符串
""表示用户什么都没输入。
Verification: checking the copy
- Verification checks that data was copied or typed correctly.
- A double-entry check asks for the value twice and compares them.
- A visual check means a human reads it back on screen.
核对:检查抄写是否正确
- 核对(verification)检查数据是否被正确地抄写或录入。
- 双重录入检查(double-entry check)让你把值输入两次,再比较。
- 目视检查(visual check)是让人在屏幕上读回来核对。
In the exam: types of check
- Know these validation checks: range, length, type, presence, format, check digit.
在考试里:各种检查
- 记住这些验证检查:范围、长度、类型、存在性、格式、校验位。
IF Age >= 0 AND Age <= 120
THEN
OUTPUT "Valid"
ELSE
OUTPUT "Invalid"
ENDIF
Common mistakes
- Validation checks data is sensible (range, length, type); verification checks it was entered correctly.
- A range check needs both a lower and an upper limit.
常见错误
- 验证(validation)检查数据是否合理(范围、长度、类型);核对(verification)检查是否输入正确。
- 范围检查同时需要下限和上限。
Now you try
- Each function returns
Trueto accept orFalseto reject. - Press Check answer to test your code.
现在轮到你
- 每个函数返回
True表示接受,False表示拒绝。 - 按检查答案来测试你的代码。
Write valid_age(a) that returns True when a is a sensible age (0 to 120 inclusive), otherwise False. This is a range check. · 写一个 valid_age(a),当 a 是合理的年龄(0 到 120,含端点)时返回 True,否则返回 False。这是一个范围检查(range check)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write valid_password(p) that returns True when the password is at least 8 characters long. This is a length check. · 写一个 valid_password(p),当密码至少有 8 个字符时返回 True。这是一个长度检查(length check)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write is_present(s) that returns True when something was entered, and False for an empty string "". This is a presence check. · 写一个 is_present(s),当确实输入了内容时返回 True,空字符串 "" 时返回 False。这是一个存在性检查(presence check)。
Click Run to see the output here. · 点击“运行”查看此处输出。