1. 编写函数,参数为语文分数、英语分数、高数分数、python分数,计算平均分,返回所有分数和平均分。要求设置位置参数和默认值参数,按位置传递方式和按关键字参数传递方式分别调用。
时间: 2024-12-17 21:46:11 浏览: 2
你可以编写一个Python函数,使用**不定长参数**(*args)和**命名参数**(**kwargs)**来满足这个需求。这里是一个示例:
```python
def calculate_average(*scores, language_score=0, math_score=0, english_score=0, python_score=0):
"""
计算总分及平均分
:param scores: 任意数量的学生各科成绩,顺序应对应语文、英语、数学、Python
:param language_score: 语文分数,默认0
:param math_score: 数学分数,默认0
:param english_score: 英语分数,默认0
:param python_score: Python分数,默认0
:return: 总分和平均分
"""
# 如果只通过位置参数传递,先处理固定位置参数
if not scores and len({language_score, math_score, english_score, python_score}) == 4:
total = language_score + math_score + english_score + python_score
else:
total = sum(scores) + language_score + math_score + english_score + python_score
average = total / (len(scores) + 4)
return total, average
# 按位置参数调用
average_pos = calculate_average(85, 90, 95, 100)
print("按位置参数调用:", average_pos)
# 按关键字参数调用
average_kw = calculate_average(language_score=70, math_score=80, python_score=90)
print("按关键字参数调用:", average_kw)
```
在这个函数里,我们既允许用户按照指定的参数顺序传入(比如`calculate_average(85, 90, 95, 100)`),也支持通过名字传参(如`calculate_average(language_score=70, math_score=80, python_score=90)`)。这样既能适应位置传递又能兼容关键字传递。
阅读全文