以下是 Python 90个基础练习代码,涵盖了从基本语法到数据结构、算法等方面的内容,帮助你全面巩固 Python 基础。
1. 基础打印和输入输出
# 1. 打印 "Hello, World!"
print("Hello, World!")
# 2. 接收用户输入并输出
name = input("Enter your name: ")
print(f"Hello, {name}!")
# 3. 打印九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}*{i}={i*j}", end=" ")
print()
2. 变量和数据类型
# 4. 数据类型转换
a = 5
b = float(a)
print(type(b)) # <class 'float'>
# 5. 判断变量的数据类型
x = "hello"
if isinstance(x, str):
print("x is a string")
else:
print("x is not a string")
# 6. 交换两个变量的值
x, y = 10, 20
x, y = y, x
print(f"x={x}, y={y}")
3. 条件语句
# 7. 判断一个数是正数、负数还是零
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
# 8. 判断一个年份是否是闰年
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
4. 循环结构
# 9. 打印1到10的整数
for i in range(1, 11):
print(i)
# 10. 求1到100的和
sum = 0
for i in range(1, 101):
sum += i
print(f"Sum of 1 to 100 is {sum}")
# 11. 输出100以内的所有偶数
for i in range(2, 101, 2):
print(i, end=" ")
print()
# 12. 计算数字的阶乘
n = int(input("Enter a number to find its factorial: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {n} is {factorial}")
5. 列表操作
# 13. 创建一个列表并输出其中的元素
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
# 14. 求列表中所有元素的和
numbers = [1, 2, 3, 4, 5]
sum_list = sum(numbers)
print(f"Sum of list: {sum_list}")
# 15. 列表的排序
unsorted_list = [5, 3, 8, 1, 2]
unsorted_list.sort()
print(f"Sorted list: {unsorted_list}")
6. 字符串操作
# 16. 反转字符串
string = "Hello, World!"
reversed_string = string[::-1]
print(f"Reversed string: {reversed_string}")
# 17. 判断字符串是否为回文
s = input("Enter a string: ")
if s == s[::-1]:
print("It is a palindrome")
else:
print("It is not a palindrome")
# 18. 字符串替换
sentence = "I love Python"
new_sentence = sentence.replace("Python", "programming")
print(new_sentence)
7. 字典操作
# 19. 创建字典并访问元素
person = {'name': 'John', 'age': 25}
print(person['name'])
# 20. 添加、修改和删除字典项
person['age'] = 26 # 修改
person['city'] = 'New York' # 添加
del person['city'] # 删除
print(person)
# 21. 字典合并
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)
8. 函数定义与调用
# 22. 定义一个求和函数
def add(x, y):
return x + y
print(add(5, 7)) # 输出12
# 23. 计算圆的面积
import math
def circle_area(radius):
return math.pi * radius * radius
print(f"Area of circle: {circle_area(5)}")
# 24. 判断一个数是否为素数
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
print(is_prime(7)) # True
print(is_prime(10)) # False
9. 集合操作
# 25. 创建集合并添加元素
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
# 26. 求两个集合的交集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2) # 输出{3}
# 27. 集合的差集
print(set1 - set2) # 输出{1, 2}
10. 元组操作
# 28. 创建元组
my_tuple = (1, 2, 3, 4)
print(my_tuple)
# 29. 访问元组元素
print(my_tuple[1])
# 30. 元组拼接
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result)
11. 列表推导式
# 31. 创建一个平方数列表
squares = [x**2 for x in range(1, 11)]
print(squares)
# 32. 提取列表中的偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
12. 异常处理
# 33. 捕获异常
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# 34. 自定义异常处理
class MyError(Exception):
pass
try:
raise MyError("Something went wrong!")
except MyError as e:
print(e)
13. 文件操作
# 35. 写入文件
with open("test.txt", "w") as file:
file.write("Hello, Python!")
# 36. 读取文件
with open("test.txt", "r") as file:
content = file.read()
print(content)
14. 日期和时间操作
# 37. 获取当前日期和时间
import datetime
now = datetime.datetime.now()
print(now)
# 38. 日期格式化
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
15. 排序和搜索
# 39. 排序一个列表
nums = [3, 1, 4, 1, 5, 9]
nums.sort()
print(nums)
# 40. 二分查找
import bisect
nums = [1, 3, 5, 7, 9]
position = bisect.bisect_left(nums, 5)
print(f"Position of 5: {position}")
16. 递归
# 41. 斐波那契数列
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10)) # 输出55
17. 装饰器
# 42. 创建一个简单的装饰器
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
18. 生成器
# 43. 创建一个生成器
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
gen = count_up_to(5)
for number in gen:
print(number)
``
`
19. 类与对象
# 44. 定义一个简单的类
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says Woof!"
dog1 = Dog("Buddy")
print(dog1.speak())
20. 静态方法和类方法
# 45. 静态方法
class MyClass:
@staticmethod
def greet():
print("Hello, static method!")
MyClass.greet()
这只是 Python 基础练习代码的一个开端,涵盖了很多常见的编程任务和概念。你可以通过这些练习逐步提升自己的 Python 编程能力。如果你需要进一步的扩展或特定主题的练习代码,可以随时告诉我!
发表回复