写出文档中要求的所有python代码
时间: 2024-12-16 08:14:47 浏览: 3
以下是根据文档要求编写的Python代码:
### 1. 条件语句与循环语句
```python
# 找出2000至2400(包括在内),可以被 7整除,但不是 5的倍数的数字
numbers = [num for num in range(2000, 2401) if num % 7 == 0 and num % 5 != 0]
print(' '.join(map(str, numbers)))
```
### 2. 条件语句与多重循环语句
#### 使用for循环
```python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [num for num in range(101, 201) if is_prime(num)]
print(f"素数个数: {len(primes)}")
print("素数列表:", primes)
```
#### 使用while循环
```python
def is_prime_while(n):
if n <= 1:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
primes_while = []
num = 101
while num < 201:
if is_prime_while(num):
primes_while.append(num)
num += 1
print(f"素数个数: {len(primes_while)}")
print("素数列表:", primes_while)
```
### 3. 列表生成表达式
#### 使用循环语句
```python
python = ['Jack', 'Rose', 'Peter', 'Mary', 'Alice', 'Richard']
matlab = ['Cherry', 'Luna', 'Peter', 'Oliva', 'Richard', 'Mary']
common_students = []
for student in python:
if student in matlab:
common_students.append(student)
print(common_students)
```
#### 使用列表生成式
```python
common_students_listcomp = [student for student in python if student in matlab]
print(common_students_listcomp)
```
### 4. txt文件操作
```python
with open('practice_4.txt', 'w') as file:
for i in range(10):
file.write(f"{i ** 3}\n")
with open('practice_4.txt', 'r') as file:
content = file.read()
print(f"写入的字符数: {len(content)}")
with open('practice_4.txt', 'r') as file:
file.seek(22)
current_line = file.readline().strip()
print(f"当前指针所在行的信息: {current_line}")
print(f"当前文件指针位置: {file.tell()}")
```
### 5. csv文件操作
```python
import csv
data = [
['学号', '姓名', '年龄', '性别'],
['20220101', 'Jack', '18', 'male'],
['20220102', 'Rose', '17', 'female'],
['20220103', 'Peter', '18', 'male'],
['20220104', 'Mary', '16', 'female'],
['20220105', 'Alice', '19', 'female'],
['20220106', 'Richard', '18', 'male']
]
with open('practice_5.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
```
### 附加题:猜数游戏
```python
import random
n = random.randint(0, 999)
attempts = 0
print("猜一个0-999之间的整数,输入-2查看答案。")
while True:
guess = int(input("请输入你的猜测: "))
attempts += 1
if guess == -2:
print(f"你放弃了,正确答案是: {n}")
break
elif guess == n:
print(f"恭喜你,猜对了!你一共猜了 {attempts} 次。")
break
elif guess < n:
print("太小了,再试一次。")
else:
print("太大了,再试一次。")
```
以上代码实现了文档中要求的所有任务。希望对你有帮助!
阅读全文