python基本函数程序示例
以下是一些基本的Python函数程序示例:
- 求两个数的和
def add(x, y):
return x + y
print(add(2, 3)) # 输出 5
- 判断一个数是否为偶数
def is_even(n):
if n % 2 == 0:
return True
else:
return False
print(is_even(4)) # 输出 True
print(is_even(5)) # 输出 False
- 计算一个列表中所有元素的平均值
def average(numbers):
total = sum(numbers)
return total / len(numbers)
print(average([1, 2, 3, 4, 5])) # 输出 3.0
- 将一个字符串中的所有单词首字母大写
def capitalize_words(string):
words = string.split()
for i in range(len(words)):
words[i] = words[i].capitalize()
return ' '.join(words)
print(capitalize_words('hello world')) # 输出 'Hello World'
- 判断一个字符串是否为回文字符串
def is_palindrome(string):
reversed_string = string[::-1]
if string == reversed_string:
return True
else:
return False
print(is_palindrome('racecar')) # 输出 True
print(is_palindrome('hello')) # 输出 False
``
原文地址: https://www.cveoy.top/t/topic/en20 著作权归作者所有。请勿转载和采集!