Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
Binary file added exercises/__pycache__/break_continue.cpython-312.pyc
Binary file not shown.
Binary file added exercises/__pycache__/data_types.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added exercises/__pycache__/for_loop.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file added exercises/__pycache__/hello_world.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file added exercises/__pycache__/if_else.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file added exercises/__pycache__/math_module.cpython-312.pyc
Binary file not shown.
Binary file added exercises/__pycache__/oop_basics.cpython-312.pyc
Binary file not shown.
Binary file added exercises/__pycache__/regex_match.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added exercises/__pycache__/while_loop.cpython-312.pyc
Binary file not shown.
6 changes: 6 additions & 0 deletions exercises/break_continue.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,10 @@ def skip_multiples_of_three(n):
- 从1到n中所有不是3的倍数的整数列表
"""
# 请在下方编写代码
list = []
for i in range(1, n + 1):
if i % 3 == 0:
continue
list.append(i)
return list
pass
5 changes: 5 additions & 0 deletions exercises/data_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ def get_data_types():
"""
# 请在下方编写代码
# 1. 创建一个整数变量,值为 42
a = 42
# 2. 创建一个浮点数变量,值为 3.14
b = 3.14
# 3. 创建一个字符串变量,值为 "Python编程"
c = "Python编程"
# 4. 创建一个布尔值变量,值为 True
d = True
# 5. 将这些变量作为元组返回
return (a, b, c, d)
pass
49 changes: 49 additions & 0 deletions exercises/dict_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,53 @@ def student_dict_operations(students_dict, operation, *args):
- 根据操作返回不同结果
"""
# 请在下方编写代码
if operation == "add":
# 添加操作:需要姓名和成绩两个参数
if len(args) == 2:
name, score = args
students_dict[name] = score
return students_dict
else:
print("错误: 'add' 操作需要姓名和成绩两个参数。")
return None # 参数数量不符

elif operation == "remove":
# 删除操作:需要姓名一个参数
if len(args) == 1:
name = args[0]
# 使用 pop 方法删除,如果键不存在也不会报错(返回 None)
students_dict.pop(name, None)
return students_dict
else:
print("错误: 'remove' 操作需要姓名一个参数。")
return None # 参数数量不符

elif operation == "update":
# 更新操作:需要姓名和新成绩两个参数
if len(args) == 2:
name, new_score = args
# 只有当学生存在时才更新
if name in students_dict:
students_dict[name] = new_score
else:
print(f"警告: 学生 '{name}' 不存在,无法更新。")
return students_dict
else:
print("错误: 'update' 操作需要姓名和新成绩两个参数。")
return None # 参数数量不符

elif operation == "get":
# 查询操作:需要姓名一个参数
if len(args) == 1:
name = args[0]
# 使用 get 方法获取成绩,如果键不存在则返回 None
return students_dict.get(name)
else:
print("错误: 'get' 操作需要姓名一个参数。")
return None # 参数数量不符

else:
# 无效的操作类型
print(f"错误: 未知的操作类型 '{operation}'。")
return None
pass
6 changes: 6 additions & 0 deletions exercises/file_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ def read_file(file_path):
"""
# 请在下方编写代码
# 使用open()函数打开文件并读取内容
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
return content
pass

def write_file(file_path, content):
Expand All @@ -34,4 +37,7 @@ def write_file(file_path, content):
"""
# 请在下方编写代码
# 使用with语句和open()函数写入内容到文件
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
return True
pass
4 changes: 4 additions & 0 deletions exercises/for_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ def sum_numbers(n):
- 从1到n的所有整数之和
"""
# 请在下方编写代码
sum = 0
for i in range(1, n+1):
sum+= i
return sum
pass
4 changes: 4 additions & 0 deletions exercises/function_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,8 @@ def calculate_area(length, width=None):
- 计算得到的面积
"""
# 请在下方编写代码
if width is None:
return length*length
else:
return length*width
pass
5 changes: 3 additions & 2 deletions exercises/hello_world.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
def print_hello_world():
"""
输出"Hello, World!"

print("Hello,world")
用于学习print函数的基本使用
"""
pass
print("Hello, World!")
pass
46 changes: 43 additions & 3 deletions exercises/http_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

请补全下面的函数,实现发送HTTP请求并处理响应的功能。
"""

import requests
def get_website_content(url):
"""
发送GET请求获取网页内容
Expand All @@ -26,7 +26,23 @@ def get_website_content(url):
# 请在下方编写代码
# 使用requests.get()发送GET请求
# 返回包含状态码、内容和头部信息的字典
pass
try:
response = requests.get(url, timeout=10) # 添加超时设置
# response.raise_for_status() # 可选:如果状态码不是2xx,则抛出HTTPError异常

return {
'status_code': response.status_code,
'content': response.text, # 获取文本内容
'headers': dict(response.headers) # requests的headers是特殊类型,转为普通字典
}
except requests.exceptions.Timeout:
print(f"请求超时: {url}")
return {'status_code': None, 'content': '请求超时', 'headers': None}
except requests.exceptions.RequestException as e:
# 捕获所有requests相关的异常 (连接错误, HTTP错误等)
print(f"请求错误: {url}, 错误: {e}")
return {'status_code': None, 'content': str(e), 'headers': None}


def post_data(url, data):
"""
Expand All @@ -47,4 +63,28 @@ def post_data(url, data):
# 请在下方编写代码
# 使用requests.post()发送POST请求
# 返回包含状态码、响应JSON和成功标志的字典
pass
try:
response = requests.post(url, data=data, timeout=10) # 发送POST请求,数据在data参数中

response_json = None
try:
# 尝试解析响应体为JSON
response_json = response.json()
except requests.exceptions.JSONDecodeError:
# 如果响应不是有效的JSON格式
print(f"警告: 响应内容不是有效的JSON格式。 URL: {url}")

# 判断请求是否成功 (状态码在 200-299 之间)
success = 200 <= response.status_code < 300

return {
'status_code': response.status_code,
'response_json': response_json,
'success': success
}
except requests.exceptions.Timeout:
print(f"POST请求超时: {url}")
return {'status_code': None, 'response_json': None, 'success': False}
except requests.exceptions.RequestException as e:
print(f"POST请求错误: {url}, 错误: {e}")
return {'status_code': None, 'response_json': None, 'success': False}
10 changes: 10 additions & 0 deletions exercises/if_else.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,14 @@ def check_grade(score):
- 对应的等级:优秀、良好、中等、及格、不及格
"""
# 请在下方编写代码
if score>=90:
return "优秀"
elif score>=80:
return "良好"
elif score>=70:
return "中等"
elif score>=60:
return "及格"
else:
return "不及格"
pass
17 changes: 17 additions & 0 deletions exercises/list_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,21 @@ def student_list_operations(students, operation, *args):
- 操作后的学生列表
"""
# 请在下方编写代码
if operation == "add":
if args:
students.append(args[0])
elif operation == "remove":
if args:
students.remove(args[0])
elif operation == "update":
if len(args) == 2 and args[0] in students: # 确保提供了两个名字且旧名字在列表中
try:
index = students.index(args[0])
students[index] = args[1]
except ValueError:
# 虽然前面检查了 in students,但 index 仍然可能因为并发修改等原因失败(理论上)
# 或者如果允许重名学生,只更新第一个找到的
pass # 或者添加更详细的错误处理

return students
pass
2 changes: 2 additions & 0 deletions exercises/math_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ def calculate_square_root(number):
- 数字的平方根
"""
# 请在下方编写代码
import math
return math.sqrt(number)
pass
9 changes: 8 additions & 1 deletion exercises/oop_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ def __init__(self, name, age, grade):
- grade: 学生成绩
"""
# 请在下方编写代码,完成属性初始化
pass
self.name=name
self.age=age
self.grade=grade

def print_info(self):
"""
Expand All @@ -39,6 +41,7 @@ def print_info(self):
- 无返回值,直接打印信息
"""
# 请在下方编写代码,完成打印学生信息的功能
print(f"姓名: {self.name}, 年龄: {self.age}, 成绩: {self.grade}")
pass

def is_passing(self):
Expand All @@ -52,6 +55,7 @@ def is_passing(self):
- 布尔值,表示是否通过考试
"""
# 请在下方编写代码,完成判断功能
return self.grade >= 60
pass


Expand All @@ -66,4 +70,7 @@ def create_student_example():
# 创建一个Student对象,设置姓名为"张三",年龄为18,成绩为85
# 调用print_info()方法打印学生信息
# 返回创建的Student对象
student1=Student("张三", 18, 85)
student1.print_info()
return student1
pass
7 changes: 7 additions & 0 deletions exercises/regex_match.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ def find_emails(text):
"""
# 实现你的代码: 使用正则表达式查找所有邮箱地址
# 邮箱格式通常为: [email protected]
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
return re.findall(email_pattern, text)
pass


Expand All @@ -36,6 +38,9 @@ def is_valid_phone_number(phone):
bool: 如果是有效的手机号码则返回True,否则返回False
"""
# 实现你的代码: 验证手机号码是否合法
phone_pattern = r'^1[3-9]\d{9}$'
# 使用 re.fullmatch 确保整个字符串都匹配模式
return bool(re.fullmatch(phone_pattern, phone))
pass


Expand All @@ -51,4 +56,6 @@ def extract_urls(text):
"""
# 实现你的代码: 使用正则表达式提取所有URL
# 需要考虑http://和https://开头的URL
url_pattern = r'https?://[^\s]+'
return re.findall(url_pattern, text)
pass
13 changes: 13 additions & 0 deletions exercises/set_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,17 @@ def student_set_operations(set1, set2, operation):
- 集合操作的结果
"""
# 请在下方编写代码
if operation == "union":
# 计算并集:包含 set1 和 set2 中所有不重复的元素
return set1.union(set2) # 或者使用 set1 | set2
elif operation == "intersection":
# 计算交集:同时存在于 set1 和 set2 中的元素
return set1.intersection(set2) # 或者使用 set1 & set2
elif operation == "difference":
# 计算差集:存在于 set1 但不存在于 set2 中的元素
return set1.difference(set2) # 或者使用 set1 - set2
else:
# 无效的操作类型
print(f"错误: 未知的操作类型 '{operation}'。支持的操作有 'union', 'intersection', 'difference'。")
return None
pass
2 changes: 2 additions & 0 deletions exercises/string_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ def format_student_info(name, age):
- 格式化后的学生信息字符串
"""
# 请在下方编写代码
formatted_string = f"学生姓名: {name}, 年龄: {age}"
return formatted_string
pass
13 changes: 13 additions & 0 deletions exercises/string_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ def extract_keywords(text):
"""
# 请在下方编写代码
# 使用split()方法分割字符串,返回关键词列表
key=text.split()
return key
pass

def parse_csv_line(csv_line):
Expand All @@ -33,6 +35,8 @@ def parse_csv_line(csv_line):
"""
# 请在下方编写代码
# 使用split()方法分割CSV行,返回字段列表
fields=csv_line.split(',')
return fields
pass

def extract_name_and_domain(email):
Expand All @@ -47,4 +51,13 @@ def extract_name_and_domain(email):
"""
# 请在下方编写代码
# 使用split()方法分割电子邮件地址,返回用户名和域名的元组
parts=email.split('@')
if len(parts) == 2:
username = parts[0]
domain = parts[1]
return (username, domain)
else:
# 处理无效邮件格式的情况(可选)
print(f"警告: 无效的邮件格式 '{email}'")
return (None, None)
pass
6 changes: 6 additions & 0 deletions exercises/while_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,10 @@ def find_first_even(numbers):
- 列表中的第一个偶数,如果没有偶数则返回None
"""
# 请在下方编写代码
i= 0
while i < len(numbers):
if numbers[i] % 2 == 0:
return numbers[i]
i += 1
return None
pass
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# filepath: c:\Users\34176\Desktop\Python-Training-Camp-Basic\requirements.txt
pytest==7.3.1
requests==2.31.0
responses==0.24.1
responses==0.24.1
Binary file added tests/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.