创建函数odd_or_even输入参数num_a,num_b利用for循环获取区间每一个元素,利用if-else语句判断指定区间[num_a,num_b]内的奇数偶数若为奇数返回odd_1,若为偶数,则返回even_1,输出返回格式均为“奇数:[odd_1]”,偶数:[even_1]"调用函数odd_or_even,传入指定参数2,100输出结果
时间: 2023-06-14 19:06:02 浏览: 164
以下是函数odd_or_even的代码实现:
```python
def odd_or_even(num_a, num_b):
odd = []
even = []
for i in range(num_a, num_b+1):
if i%2 == 0:
even.append(i)
else:
odd.append(i)
return "奇数: " + str(odd) + ", 偶数: " + str(even)
print(odd_or_even(2, 100))
```
输出结果为:
```
奇数: [2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99], 偶数: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
```
其中,奇数和偶数的集合分别被存储在名为`odd`和`even`的列表中,最后通过`return`语句返回字符串形式的输出结果。
阅读全文