python自定义函数简单题目
时间: 2025-05-06 20:31:45 浏览: 23
### 关于Python自定义函数的简单练习题
#### 函数:计算两个数之和
创建一个简单的函数来接收两个参数并返回它们的和。
```python
def add_numbers(a, b):
"""Return the sum of two numbers."""
result = a + b
return result
```
调用此函数可以如下所示:
```python
print(add_numbers(5, 3)) # 输出应为8
```
#### 函数:判断字符串长度
编写一个接受字符串作为输入,并检查其长度是否超过指定数量字符的功能。如果超过了,则返回`True`; 否则返回`False`.
```python
def check_string_length(s, limit=10):
"""Check if string length exceeds given limit."""
if isinstance(s, str)[^3]:
return len(s) > limit
else:
raise ValueError("Input must be a string.")
```
测试该功能的例子有:
```python
print(check_string_length("hello")) # 应输出 False
print(check_string_length("supercalifragilisticexpialidocious", 20)) # 应输出 True
try:
print(check_string_length(123))
except Exception as e:
print(e) # 应抛出错误提示信息
```
#### 函数:温度单位转换器
实现一个能够把摄氏度转成华氏度的小工具,这同样适用于展示如何利用自定义函数来进行数据处理[^2].
```python
def celsius_to_fahrenheit(celsius):
"""Convert temperature from Celsius to Fahrenheit."""
fahrenheit = (celsius * 9/5) + 32
return round(fahrenheit, 2)
temperature_celsius = 25
converted_temperature = celsius_to_fahrenheit(temperature_celsius)
print(f"{temperature_celsius}°C is equal to {converted_temperature}°F")
```
这些例子旨在帮助初学者更好地理解和掌握Python中自定义函数的基础概念及其应用方式。
阅读全文
相关推荐






