python return用法的例子
时间: 2023-12-01 18:02:35 浏览: 64
Python中return self的用法详解
5星 · 资源好评率100%
1. 返回一个数的平方:
```
def square(num):
return num*num
result = square(5)
print(result) # 输出 25
```
2. 返回一个列表中的最大值:
```
def max_number(numbers):
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
result = max_number([3, 5, 2, 8, 1])
print(result) # 输出 8
```
3. 返回一个字符串中每个单词的首字母大写:
```
def capitalize_words(sentence):
words = sentence.split()
capitalized_words = []
for word in words:
capitalized_words.append(word.capitalize())
return " ".join(capitalized_words)
result = capitalize_words("this is a sentence")
print(result) # 输出 "This Is A Sentence"
```
4. 返回一个字典中特定键对应的值:
```
def get_value(dict, key):
if key in dict:
return dict[key]
else:
return None
result = get_value({"name": "John", "age": 30}, "age")
print(result) # 输出 30
```
阅读全文