1. 题目🔍
本题要求实现一个函数,可输出姓名、出生日期、性别、国籍和电话,并根据出生日期算出岁数(需要判断是否足岁)。函数可以对输入中的错误信息进行捕获。
1.1 函数接口定义
def student(name,*birth,**information)
1.2 裁判测试程序样例
name = input()
birth = input()
student(name,birth,sex='Female', nation='China', phone='123456789')
1.3 输入样例1
zhangsan
1999 2 3
1.4 输出样例1
name:zhangsan
birth:1999-2-3
age is 20
sex:Female
nation:China
phone:123456789
1.5 输入样例2
zhangsan
1999-2-3
1.6 输出样例2
name:zhangsan
The interval in the input ‘birth’ is a space
2. 题解✨
2.1 知识储备
函数参数前的单星号*args
表示:将参数以元组的形式导入
函数参数前的双星号**kwargs
表示:将参数以字典的形式导入
2.2 代码
from datetime import date
def student(name, *birth, **information):
string = birth[0] # 将出生日期转化为字符串
if ' ' not in string: # 这里仅判断出生日期不以空格为间隔的情况
print('name:{}'.format(name))
print("The interval in the input 'birth' is a space")
else:
ls = string.split() # 将字符串转化为列表
year = ls[0] # 切片储存
month = ls[1]
day = ls[2]
today = date.today() # 获取今天的日期
age = today.year - int(year) - ((today.month, today.day) < (int(month), int(day))) # ⚠️重要!!!计算年龄
print('name:{}'.format(name))
print('{}-{}-{}'.format(year, month, day))
print('age is', age)
for k, v in information.items():
print('{}:{}'.format(k, v))
name = input()
birth = input()
student(name, birth, sex='Female', nation='China', phone='123456789')
相关内容