设计一个用来根据身份证号确定年龄的程序。要求:首先创建 一个列表,其中每个元素是一个身份证号码;然后定义一个函数 用来根据输入的列表中每个身份证号字符串,得到年龄;还要有 一个主程序,调用上面的函数来得到全部年龄并 print 出来。要求 写出所有代码
时间: 2024-11-23 11:49:08 浏览: 23
设计一个根据身份证号码计算年龄的Python程序,我们可以遵循以下步骤:
```python
import re
# 创建一个包含身份证号码的列表
id_list = [
"123456789012345678",
"330101199001011234", # 示例:中国省份+市区+出生日期
"110101198512314567", # 示例:北京+出生日期
]
def get_age(id_number):
"""
根据中国身份证号码规则计算年龄
"""
pattern = r'^(\d{6})(\d{4})(\d{2})(\d{2})$' # 正则表达式匹配年月日格式
match = re.match(pattern, id_number)
if not match:
return None # 如果格式错误,返回None
birth_year = int(match.group(2))
birth_month = int(match.group(3))
birth_day = int(match.group(4))
current_year = datetime.datetime.now().year # 获取当前年份
age = current_year - birth_year - ((current_year % 100) >= (birth_year % 100)) + (1 if birth_month > datetime.datetime.now().month or (birth_month == datetime.datetime.now().month and birth_day >= datetime.datetime.now().day) else 0)
return age
def main():
ages = []
for id_num in id_list:
age = get_age(id_num)
if age is not None:
ages.append(age)
# 打印所有年龄
if ages:
print(f"身份证号码对应的年龄分别是:{ages}")
else:
print("部分身份证号码格式不正确,无法获取年龄")
if __name__ == "__main__":
main()
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)