当前位置:首页 » 《休闲阅读》 » 正文

python 100道新手练习题附答案(建议收藏食用)!

11 人参与  2024年11月15日 08:01  分类 : 《休闲阅读》  评论

点击全文阅读


基础语法

1. 打印 “Hello, World!”

print("Hello, World!")

2. 定义一个变量并打印其值

message = "Hello, Python!"print(message)

3. 定义两个整数变量并计算它们的和

a = 5b = 3sum = a + bprint(sum)

4. 使用条件语句判断一个数是否为正数

num = 10if num > 0:print("Positive")else:print("Not Positive")

5. 使用循环打印从1到10的所有数字

for i in range(1, 11):print(i)

6. 使用while循环打印从1到10的所有数字

i = 1while i <= 10:print(i)i += 1

7. 计算一个列表中所有元素的总和

numbers = [1, 2, 3, 4, 5]total = sum(numbers)print(total)

8. 判断一个字符串是否是回文

def is_palindrome(s):return s == s[::-1]s = "madam"print(is_palindrome(s))

9. 将一个字符串中的所有字母转换为大写

s = "hello, world!"print(s.upper())

10. 检查一个字符串是否包含特定子串

s = "hello, world!"if "world" in s:print("Substring found")else:print("Substring not found")

数据结构

11. 创建一个列表并添加元素

my_list = []my_list.append(1)my_list.append(2)my_list.append(3)print(my_list)

12. 创建一个字典并添加键值对

my_dict = {}my_dict['name'] = 'Alice'my_dict['age'] = 30print(my_dict)

13. 遍历一个列表并打印每个元素

my_list = [1, 2, 3, 4, 5]for item in my_list:print(item)

14. 遍历一个字典并打印每个键值对

my_dict = {'name': 'Alice', 'age': 30}for key, value in my_dict.items(): print(f"{key}: {value}")

15. 对一个列表进行排序

my_list = [3, 1, 4, 1, 5, 9]my_list.sort()print(my_list)

16. 查找列表中的最大值和最小值

my_list = [3, 1, 4, 1, 5, 9]print(max(my_list))print(min(my_list))

17. 删除列表中的特定元素

my_list = [1, 2, 3, 4, 5]my_list.remove(3)print(my_list)

18. 合并两个列表

list1 = [1, 2, 3]list2 = [4, 5, 6]combined_list = list1 + list2print(combined_list)

19. 创建一个集合并添加元素

my_set = set()my_set.add(1)my_set.add(2)my_set.add(3)print(my_set)

20. 创建一个元组并访问其元素

my_tuple = (1, 2, 3)print(my_tuple[0])print(my_tuple[1])print(my_tuple[2])

文件操作

21. 读取一个文本文件并打印内容

with open('file.txt', 'r') as file:content = file.read()print(content)

22. 写入一个文本文件

with open('file.txt', 'w') as file:file.write('Hello, World!')

23. 追加内容到一个文本文件

with open('file.txt', 'a') as file:file.write('\nAppending new line.')

24. 逐行读取一个文本文件并打印每行

with open('file.txt', 'r') as file:for line in file:print(line.strip())

25. 复制一个文件的内容到另一个文件

with open('source.txt', 'r') as source_file:    with open('destination.txt', 'w') as dest_file:        dest_file.write(source_file.read())

26. 统计一个文本文件中的单词数量

with open('file.txt', 'r') as file:content = file.read()words = content.split()print(len(words))

27. 替换一个文本文件中的特定单词

with open('file.txt', 'r') as file:content = file.read()new_content = content.replace('old_word', 'new_word')with open('file.txt', 'w') as file:file.write(new_content)

28. 读取CSV文件并打印每一行

import csvwith open('data.csv', 'r') as csvfile:reader = csv.reader(csvfile)for row in reader:print(row)

29. 写入CSV文件

import csv``with open('data.csv', 'w', newline='') as csvfile:writer = csv.writer(csvfile)writer.writerow(['Name', 'Age'])writer.writerow(['Alice', 30])writer.writerow(['Bob', 25])

30. 读取JSON文件并打印内容

import jsonwith open('data.json', 'r') as f:data = json.load(f)print(data)

函数与模块

31. 定义一个函数并调用它

def greet(name):print(f"Hello, {name}!")greet("Alice")

32. 定义一个带返回值的函数

def add(a, b):  return a + bresult = add(3, 5)print(result)

33. 定义一个带默认参数的函数

def greet(name="World"):print(f"Hello, {name}!")greet()  # 输出: Hello, World!greet("Alice")  # 输出: Hello, Alice!

34. 定义一个带可变参数的函数

def sum_all(*args):return sum(args)result = sum_all(1, 2, 3, 4, 5)print(result)

35. 定义一个带关键字参数的函数

def display_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")display_info(name="Alice", age=30)

36. 导入标准库模块并使用

import mathresult = math.sqrt(16)print(result)

37. 导入自定义模块并使用

假设有一个 mymodule.py 文件:# mymodule.pydef hello():print("Hello from mymodule!")在主程序中导入并使用:import mymodulemymodule.hello()

38. 从模块中导入特定函数

from math import sqrtresult = sqrt(16)print(result)

39. 使用 sys 模块获取命令行参数

import sysfor arg in sys.argv:print(arg)

40. 使用 os 模块获取当前工作目录

import oscurrent_dir = os.getcwd()print(current_dir)

面向对象编程

41. 定义一个类并创建对象

class Person:def __init__(self, name, age):self.name = nameself.age = agedef greet(self):print(f"Hello, my name is {self.name} and I am {self.age} years old.")person = Person("Alice", 30)person.greet()

42. 定义一个类并继承另一个类

class Animal:def speak(self):passclass Dog(Animal):def speak(self):        print("Woof!")class Cat(Animal):def speak(self):print("Meow!")dog = Dog()cat = Cat()dog.speak()  # 输出: Woof!cat.speak()  # 输出: Meow!

43. 定义一个类并使用类变量

class Circle:    pi = 3.14159def __init__(self, radius):self.radius = radius    def area(self):        return Circle.pi * (self.radius ** 2)circle = Circle(5)print(circle.area())

44. 定义一个类并使用实例方法

class Rectangle:    def __init__(self, width, height):self.width = width        self.height = height    def area(self):        return self.width * self.heightrectangle = Rectangle(5, 10)print(rectangle.area())

45. 定义一个类并使用静态方法

class MathUtils:@staticmethoddef add(a, b):return a + bresult = MathUtils.add(3, 5)print(result)

46. 定义一个类并使用类方法

class Person:    count = 0    def __init__(self, name):self.name = namePerson.count += 1    @classmethod    def get_count(cls):return cls.countperson1 = Person("Alice")person2 = Person("Bob")print(Person.get_count())  # 输出: 2

47. 定义一个类并使用私有属性

class BankAccount:def __init__(self, balance):self.__balance = balancedef deposit(self, amount):self.__balance += amountdef withdraw(self, amount):if amount <= self.__balance:self.__balance -= amountelse:print("Insufficient funds")def get_balance(self):return self.__balanceaccount = BankAccount(1000)account.deposit(500)account.withdraw(200)print(account.get_balance())  # 输出: 1300

48. 定义一个类并使用属性装饰器

class Temperature:def __init__(self, celsius):self.celsius = celsius@propertydef fahrenheit(self):return (self.celsius * 9/5) + 32temp = Temperature(25)print(temp.fahrenheit)  # 输出: 77.0

49. 定义一个类并使用属性设置器

class Temperature:def __init__(self, celsius):      self._celsius = celsius@propertydef celsius(self):return self._celsius@celsius.setterdef celsius(self, value):self._celsius = value@propertydef fahrenheit(self):return (self._celsius * 9/5) + 32temp = Temperature(25)print(temp.fahrenheit)  # 输出: 77.0temp.celsius = 30print(temp.fahrenheit)  # 输出: 86.0

50. 定义一个类并使用特殊方法(如 __str__ 和 __repr__)

class Point:def __init__(self, x, y):self.x = xself.y = ydef __str__(self):return f"Point({self.x}, {self.y})"def __repr__(self):return f"Point(x={self.x}, y={self.y})"point = Point(3, 4)print(point)  # 输出: Point(3, 4)print(repr(point))  # 输出: Point(x=3, y=4)

异常处理

51. 捕获并处理异常

try:result = 10 / 0except ZeroDivisionError:print("Cannot divide by zero")

52. 捕获多个异常

try:result = 10 / 0except (ZeroDivisionError, TypeError):print("An error occurred")

53. 获取异常信息

try:result = 10 / 0except ZeroDivisionError as e:print(f"Error: {e}")54. 使用 finally 块55. try:56. result = 10 / 257. except ZeroDivisionError:58. print("Cannot divide by zero")59. finally:60. print("This will always execute")

55. 抛出异常

def divide(a, b):if b == 0:raise ValueError("Cannot divide by zero")return a / btry:result = divide(10, 0)except ValueError as e:print(e)

数学与科学计算

56. 计算一个数的平方根

import mathresult = math.sqrt(16)print(result)

57. 计算一个数的幂

result = pow(2, 3)print(result)

58. 计算圆的面积

import mathdef circle_area(radius):return math.pi * (radius ** 2)area = circle_area(5)``print(area)

59. 计算阶乘

import mathresult = math.factorial(5)print(result)

60. 计算组合数

import mathresult = math.comb(5, 2)print(result)

字符串操作

61. 字符串拼接

first_name = "John"last_name = "Doe"full_name = first_name + " " + last_nameprint(full_name)

62. 字符串格式化

name = "Alice"age = 30message = f"Name: {name}, Age: {age}"print(message)

63. 字符串分割

text = "apple,banana,orange"fruits = text.split(',')print(fruits)

64. 字符串连接

fruits = ['apple', 'banana', 'orange']text = ','.join(fruits)print(text)

65. 字符串替换

text = "Hello, World!"new_text = text.replace("World", "Python")print(new_text)

66. 字符串查找子串

text = "Hello, World!"index = text.find("World")print(index)

67. 字符串大小写转换

text = "Hello, World!"upper_text = text.upper()lower_text = text.lower()print(upper_text)print(lower_text)

68. 字符串去空格

text = "   Hello, World!   "trimmed_text = text.strip()print(trimmed_text)

69. 字符串切片

text = "Hello, World!"substring = text[7:12]print(substring)

70. 字符串长度

text = "Hello, World!"length = len(text)print(length)

正则表达式

71. 匹配电子邮件地址

import retext = "Contact us at support@example.com or feedback@example.org"``emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)print(emails)

72. 匹配电话号码

import retext = "Call us at 123-456-7890 or 987-654-3210"phone_numbers = re.findall(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', text)print(phone_numbers)

73. 匹配日期

import retext = "Meeting on 2023-10-05 and 2023-10-10"dates = re.findall(r'\b\d{4}-\d{2}-\d{2}\b', text)print(dates)

74. 替换字符串中的匹配项

import retext = "The quick brown fox jumps over the lazy dog"new_text = re.sub(r'fox', 'cat', text)print(new_text)

75. 检查字符串是否符合某种模式

import retext = "123-456-7890"pattern = r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'if re.match(pattern, text):print("Match found")else:print("No match")

文件和目录操作

76. 创建目录

import osos.makedirs('new_directory', exist_ok=True)

77. 删除目录

import shutilshutil.rmtree('directory_to_delete')

78. 列出目录内容

import osfor item in os.listdir('path/to/directory'):print(item)

79. 复制文件

import shutilshutil.copy('source_file.txt', 'destination_file.txt')

80. 移动文件

import shutilshutil.move('source_file.txt', 'destination_directory/')

81. 重命名文件

import osos.rename('old_name.txt', 'new_name.txt')

82. 检查文件是否存在

import osif os.path.exists('file.txt'):print('File exists.')

83. 获取文件大小

import osfile_size = os.path.getsize('file.txt')print(f'File size: {file_size} bytes')

84. 获取文件修改时间

import osmod_time = os.path.getmtime('file.txt')print(f'Modified time: {mod_time}')

85. 递归遍历目录

import osfor root, dirs, files in os.walk('path/to/directory'):for name in files:print(os.path.join(root, name))

86. 查找文件

import osfor root, dirs, files in os.walk('path/to/directory'):if 'target_file.txt' in files:print(os.path.join(root, 'target_file.txt'))

87. 压缩文件

import zipfilewith zipfile.ZipFile('archive.zip', 'w') as zipf:zipf.write('file.txt')

88. 解压缩文件

import zipfilewith zipfile.ZipFile('archive.zip', 'r') as zipf:zipf.extractall('extracted_directory')

89. 读取CSV文件

import csvwith open('data.csv', 'r') as csvfile:reader = csv.reader(csvfile)for row in reader:print(row)

90. 写入CSV文件

import csvwith open('data.csv', 'w', newline='') as csvfile:writer = csv.writer(csvfile)writer.writerow(['Name', 'Age'])writer.writerow(['Alice', 30])writer.writerow(['Bob', 25])

网络请求

91. 发送GET请求

import requestsresponse = requests.get('https://api.example.com/data')print(response.text)

92. 发送POST请求

import requestspayload = {'key': 'value'}response = requests.post('https://api.example.com/submit', data=payload)print(response.text)

93. 发送带有头部的请求

import requests``headers = {'Content-Type': 'application/json'}response = requests.get('https://api.example.com/data', headers=headers)print(response.text)

94. 下载文件

import requestsurl = 'https://example.com/file.zip'response = requests.get(url)with open('downloaded_file.zip', 'wb') as f:f.write(response.content)

95. 上传文件

import requestsfiles = {'file': open('file.txt', 'rb')}response = requests.post('https://api.example.com/upload', files=files)print(response.text)

96. 处理JSON响应

import requestsresponse = requests.get('https://api.example.com/data')data = response.json()print(data)

97. 处理XML响应

import requestsimport xml.etree.ElementTree as ETresponse = requests.get('https://api.example.com/data.xml')root = ET.fromstring(response.text)for child in root:print(child.tag, child.attrib)

98. 设置超时

import requestsresponse = requests.get('https://api.example.com/data', timeout=5)print(response.text)

99. 处理HTTP错误

import requeststry:response = requests.get('https://api.example.com/data')response.raise_for_status()except requests.exceptions.HTTPError as errh:print("Http Error:", errh)except requests.exceptions.ConnectionError as errc:print("Error Connecting:", errc)except requests.exceptions.Timeout as errt:print("Timeout Error:", errt)except requests.exceptions.RequestException as err:print("OOps: Something Else", err)

100. 使用会话

import requestssession = requests.Session()session.auth = ('username', 'password')response = session.get('https://api.example.com/data')print(response.text)

关于Python技能储备!

如果你是准备学习Python或者正在学习(想通过Python兼职),下面这些你应该能用得上:
【点击这里】领取!
包括:激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!
Python所有方向的学习路线图,清楚各个方向要学什么东西
100多节Python课程视频,涵盖必备基础、爬虫和数据分析
100多个Python实战案例,学习不再是只会理论
华为出品独家Python漫画教程,手机也能学习
历年互联网企业Python面试真题,复习时非常方便
****

在这里插入图片描述

在这里插入图片描述

以上就是本次分享的全部内容。我们下期见~

End


点击全文阅读


本文链接:http://zhangshiyu.com/post/186329.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1