Python 核心编程 习题答案31


第 1 章:Python 基础

1.1 以下代码片段的输出是什么?
```python
print(1 + 2)
print(1 + 2.5)
print(1 + '2')
```
答案:
3
3.5
TypeError: unsupported operand type(s) for +: 'int' and 'str'

1.2 编写一个 Python 程序,计算两个数字的平均值。
```python
# 编写代码
```
答案:
```python
def mean(a, b):
return (a + b) / 2
```

第 2 章:数据结构

2.1 创建一个包含以下元素的列表:'apple', 'banana', 'cherry'。
```python
# 编写代码
```
答案:
```python
fruits = ['apple', 'banana', 'cherry']
```

2.2 将以下元组转换为列表:('apple', 'banana', 'cherry')。
```python
# 编写代码
```
答案:
```python
fruits = list(('apple', 'banana', 'cherry'))
```

第 3 章:流程控制

3.1 编写一个 Python 程序,使用 for 循环遍历列表 [1, 2, 3, 4, 5],并打印每个元素。
```python
# 编写代码
```
答案:
```python
for i in [1, 2, 3, 4, 5]:
print(i)
```

3.2 编写一个 Python 程序,使用 while 循环计算 1 到 100 的和。
```python
# 编写代码
```
答案:
```python
sum = 0
i = 1
while i

2024-12-03


上一篇:Python 与 PHP 混合编程:无缝集成和优势探索

下一篇:Python 核心编程习题答案