Python函数的可变参数传递(*args与**kwargs)


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')


相关内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值