Python 函数应用题:字符串处理、列表平均值、整数因子
Python 函数应用题:字符串处理、列表平均值、整数因子
本文提供3道Python函数应用题,帮助你巩固函数的运用。
1. 字符串首字母大写
编写一个函数,接收一个字符串作为参数,返回该字符串中每个单词的首字母大写后的字符串。
示例:
def capitalize_words(s):
words = s.split()
return ' '.join([word.capitalize() for word in words])
print(capitalize_words('hello world')) # 'Hello World'
print(capitalize_words('good morning')) # 'Good Morning'
2. 列表元素平均值
编写一个函数,接收一个整数列表作为参数,返回列表中所有元素的平均值。
示例:
def average(nums):
return sum(nums) / len(nums)
print(average([1, 2, 3, 4, 5])) # 3.0
print(average([10, 20, 30])) # 20.0
3. 整数因子查找
编写一个函数,接收一个整数作为参数,返回该整数的所有因子。
示例:
def factors(n):
return [i for i in range(1, n+1) if n % i == 0]
print(factors(12)) # [1, 2, 3, 4, 6, 12]
print(factors(25)) # [1, 5, 25]
通过以上3道练习,你将能够更加熟练地运用Python函数来解决实际问题。
原文地址: https://www.cveoy.top/t/topic/oiLY 著作权归作者所有。请勿转载和采集!