
本文介绍如何在Python中接收员工基本信息、将10位数字电话号码自动格式化为标准(xxx)xxx-xxxx形式,并以列表结构安全存储;同时提供基于索引的安全查询逻辑,避免越界访问风险。
本文介绍如何在python中接收员工基本信息、将10位数字电话号码自动格式化为标准`(xxx)xxx-xxxx`形式,并以列表结构安全存储;同时提供基于索引的安全查询逻辑,避免越界访问风险。
在实际教学或开发实践中,教师常要求学生移除不规范、冗余或存在安全隐患的代码(如未验证输入、硬编码逻辑、越界访问等)。上述被要求删除的原始代码虽实现了基础功能,但存在多个关键问题:循环体与for语句未正确缩进导致逻辑失效;仅录入1名员工却预留了索引1–5的查询分支,极易引发IndexError;未对用户输入做类型与范围校验;且employeePhone直接转为int可能因输入非数字而崩溃。
以下是优化后的完整实现,兼顾功能性、健壮性与可读性:
employee = []
print('Enter information for employee #1.')
employeeName = input("Enter employee's name:\n").strip()
employeeSSN = input("Enter employee's SSN:\n").strip()
employeePhoneInput = input("Enter employee's 10-digit phone number (e.g., 1234567890):\n").strip()
# 电话号码格式化:严格校验10位纯数字
if employeePhoneInput.isdigit() and len(employeePhoneInput) == 10:
Phone = f"({employeePhoneInput[:3]}){employeePhoneInput[3:6]}-{employeePhoneInput[6:]}"
else:
print("Warning: Invalid phone format. Using placeholder.")
Phone = "(000)000-0000"
employeeEmail = input("Enter employee's email:\n").strip()
employeeSalary = input("Enter employee's salary:\n").strip()
employee.append([employeeName, employeeSSN, Phone, employeeEmail, employeeSalary])
# 安全索引查询(支持0退出,且仅响应有效索引)
try:
index = int(input('Enter a value 1-5 to print corresponding employee information, or 0 to exit: '))
if index == 0:
print('Goodbye!')
elif 1 <= index <= len(employee):
# 注意:索引从1开始显示,但列表从0开始,故取 employee[index-1]
print(f"Employee #{index} Info:", employee[index-1])
else:
print(f"Invalid selection. Only 1 employee exists. Please enter 1 or 0.")
except ValueError:
print("Error: Please enter a valid integer.")关键改进说明:
✅ 输入健壮性:使用.isdigit()和长度校验替代强制int()转换,防止非数字输入崩溃;邮箱、姓名、薪资均用.strip()清除首尾空格。
✅ 格式化清晰安全:采用f-string替代format(),更直观;电话分段逻辑明确,失败时提供合理默认值而非中断程序。
✅ 索引访问安全:动态检查len(employee)而非硬编码5个分支;通过index-1映射用户友好索引到真实列表下标;try-except捕获非法整数输入。
✅ 教学友好设计:注释明确标注易错点(如缩进、索引偏移),便于学生理解修正逻辑。
⚠️ 注意:真实项目中应进一步扩展为多员工录入(如while循环+终止条件)、数据持久化(如写入CSV/JSON)及字段验证(如邮箱正则匹配、SSN格式校验)。本例聚焦核心教学目标——规范输入处理 + 安全数据结构访问。

















