一、基础数据类型与运算
1.整数运算
python
a = int(input("输入第一个整数:"))
b = int(input("输入第二个整数:"))
print(f"和:{a + b}, 差:{a - b}, 积:{a * b}, 商:{a // b}, 余数:{a % b}")
2.温度转换
python
c = float(input("摄氏温度:"))
f = c * 9/5 + 32
print(f"华氏温度:{f:.2f}")
3.圆的面积和周长
python
import math
r = float(input("半径:"))
print(f"面积:{math.pi * r2:.2f}, 周长:{2 * math.pi * r:.2f}")
4.奇偶判断
python
num = int(input("输入整数:"))
print("偶数" if num % 2 == 0 else "奇数")
5.数字反转
python
num = input("输入三位数:")
print(num[::-1])
---
二、字符串操作
6.字符串长度
python
s = input("输入字符串:")
print("长度:", len(s))
7.大小写转换
python
s = input("输入字符串:")
print("大写:", s.upper())
print("小写:", s.lower())
8.字符串拼接
python
s1 = input("字符串1:")
s2 = input("字符串2:")
print("拼接结果:", s1 + s2)
9.字符串切片
python
s = input("输入字符串:")
print("前三个字符:", s[:3])
print("后三个字符:", s[-3:])
10.统计字符
python
s = input("输入字符串:")
print(f"字母:{sum(c.isalpha() for c in s)}")
print(f"数字:{sum(c.isdigit() for c in s)}")
print(f"空格:{sum(c.isspace() for c in s)}")
---
三、列表操作
11.列表求和
python
nums = list(map(int, input("输入数字列表(空格分隔):").split()))
print("和:", sum(nums))
12.列表最大值
python
nums = list(map(int, input("输入列表:").split()))
print("最大值:", max(nums))
13.列表去重
python
nums = list(map(int, input("输入列表:").split()))
unique = []
for num in nums:
if num not in unique:
unique.append(num)
print("去重结果:", unique)
14.列表排序
python
nums = list(map(int, input("输入列表:").split()))
print("升序:", sorted(nums))
print("降序:", sorted(nums, reverse=True))
15.列表合并
python
list1 = list(map(int, input("列表1:").split()))
list2 = list(map(int, input("列表2:").split()))
print("合并结果:", list1 + list2)
---
四、元组操作
16.元组创建
python
t = (1, 2, 3, 4, 5)
print(t)
17.元组索引
python
t = ("a", "b", "c", "d")
print("第二个元素:", t[1], ",第四个元素:", t[3])
18.元组拼接
python
t1 = (1, 2)
t2 = (3, 4)
print("合并后:", t1 + t2)
19.元组转列表
python
t = (10, 20, 30)
print(list(t))
20.元组解包交换
python
x, y = 5, 10
x, y = y, x
print("交换后:", x, y)
---
五、字典操作
21.字典创建
python
d = {"name": "Alice", "age": 25}
print(d)
22.字典取值
python
d = {"a": 1, "b": 2, "c": 3}
print("键b的值:", d["b"])
23.字典更新
python
d = {"x": 10, "y": 20}
d["z"] = 30
print(d)
24.字典遍历
python
d = {"A": 1, "B": 2, "C": 3}
for k, v in d.items():
print(f"{k}: {v}")
25.字典键排序
python
d = {"b": 2, "a": 1, "c": 3}
print("按键排序:", dict(sorted(d.items())))
---
六、集合操作
26.集合创建
python
s = {1, 2, 3, 4, 5}
print(s)
27.列表去重
python
lst = [1, 2, 2, 3, 3, 3]
print(set(lst))
28.集合运算
python
A = {1, 2, 3}
B = {3, 4, 5}
print("并集:", A | B)
print("交集:", A & B)
print("差集A-B:", A - B)
29.集合添加
python
s = {10, 20, 30}
s.add(40)
print(s)
30.集合删除
python
s = {"a", "b", "c"}
s.remove("b")
print(s)
---
七、条件判断与循环
31.成绩等级
python
score = int(input("分数:"))
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
32.闰年判断
python
year = int(input("年份:"))
print("闰年" if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else "平年")
33.猜数字游戏
python
import random
target = random.randint(1, 100)
while True:
guess = int(input("猜数字:"))
if guess == target:
print("猜对了!")
break
print("大了" if guess > target else "小了")
34.乘法表
python
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}×{i}={i*j}", end="\t")
print()
35.斐波那契数列
python
a, b = 1, 1
fib = [a, b]
for _ in range(8):
a, b = b, a + b
fib.append(b)
print(fib)
---
八、函数与模块
36.函数定义
python
def add(a, b):
return a + b
37.默认参数
python
def greet(name="User"):
print(f"Hello, {name}!")
38.可变参数
python
def sum_all(*args):
return sum(args)
39.递归阶乘
python
def factorial(n):
return 1 if n <= 1 else n * factorial(n-1)
40.模块导入
python
import math
print(math.sqrt(16))
print(math.log10(100))
---
九、文件操作
41.文件写入
python
with open("data.txt", "w") as f:
f.write("Hello, Python!")
42.文件读取
python
with open("data.txt", "r") as f:
print(f.read())
43.文件追加
python
with open("data.txt", "a") as f:
f.write("\nThis is a new line.")
44.CSV读取
python
import csv
total = count = 0
with open("scores.csv") as f:
for row in csv.reader(f):
total += int(row[1])
count += 1
print("平均分:", total / count)
45.JSON处理
python
import json
data = {"name": "Bob", "age": 30}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json") as f:
print(json.load(f))
---
十、面向对象编程
46.类定义
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Name: {self.name}, Age: {self.age}")
47.继承
python
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
48.方法重写
python
class Student(Person):
def introduce(self):
print(f"Name: {self.name}, Age: {self.age}, ID: {self.student_id}")
49.构造函数
python
# 已在第46题实现 __init__
50.多态
python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
---
以上代码覆盖了Python基础语法、数据类型、函数、文件操作和面向对象编程的核心知识点。