类型:Roadmap
适合人群:Python 初学者、语法巩固者、面试准备者、个人练习仓库整理者
目标:通过 140+ 个基础程序,系统覆盖 Python 输入输出、运算、条件判断、循环、函数、数据结构、字符串、文件处理、面向对象与常见面试题。
建议按阶段刷题,每个程序都至少完成 3 步:
推荐仓库结构:
textpython-basic-programs/ ├── 01_input_output/ ├── 02_math_operations/ ├── 03_conditions/ ├── 04_loops/ ├── 05_numbers/ ├── 06_strings/ ├── 07_lists_tuples/ ├── 08_dict_sets/ ├── 09_functions/ ├── 10_files/ ├── 11_oop/ ├── 12_mini_projects/ └── README.md
| 阶段 | 主题 | 目标 |
|---|---|---|
| Phase 1 | 输入输出与变量 | 熟悉 print()、input()、变量、类型转换 |
| Phase 2 | 数学与单位换算 | 掌握基础算术、公式实现、随机数 |
| Phase 3 | 条件判断 | 熟练使用 if / elif / else |
| Phase 4 | 循环基础 | 掌握 for、while、range() |
| Phase 5 | 数字类经典题 | 练习质数、阶乘、斐波那契、水仙花数等 |
| Phase 6 | 字符串处理 | 掌握切片、查找、替换、统计、回文判断 |
| Phase 7 | 列表、元组、集合 | 掌握常见序列操作 |
| Phase 8 | 字典与数据统计 | 熟悉键值对、频次统计、分组 |
| Phase 9 | 函数与递归 | 学会封装逻辑、拆分问题 |
| Phase 10 | 文件、异常、模块 | 处理真实输入输出与错误 |
| Phase 11 | 面向对象基础 | 理解类、对象、属性、方法 |
| Phase 12 | 综合小项目 | 将基础语法串联成完整程序 |
print() 输出input() 获取用户输入int()、float()、str() 类型转换Hello Pythonpythonname = input("Enter your name: ")
print(f"Hello, {name}! Welcome to Python.")pythonnum1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
total = num1 + num2
print(f"{num1} + {num2} = {total}")math 模块random 模块pythonimport random
number = random.randint(1, 100)
print(f"Random number: {number}")pythonkilometers = float(input("Enter distance in kilometers: "))
miles = kilometers * 0.621371
print(f"{kilometers} kilometers is equal to {miles} miles")pythonimport calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
print(calendar.month(year, month))ifif / elseif / elif / elsepythonnum = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")pythonyear = int(input("Enter a year: "))
if year % 400 == 0:
print(f"{year} is a leap year")
elif year % 100 == 0:
print(f"{year} is not a leap year")
elif year % 4 == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")for 循环while 循环break 和 continuewhile 实现倒计时pythonnum = int(input("Display multiplication table of: "))
for i in range(1, 11):
print(f"{num} X {i} = {num * i}")pythontotal = 0
n = int(input("Enter n: "))
for i in range(1, n + 1):
total += i
print(f"Sum from 1 to {n} is {total}")pythonnum = int(input("Enter a number: "))
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")pythonnum = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}")pythonnterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print(n1)
else:
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1pythontext = input("Enter a string: ")
if text == text[::-1]:
print("Palindrome")
else:
print("Not palindrome")pythontext = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"Number of vowels: {count}")pythonnumbers = [10, 20, 5, 8, 30]
print("Max:", max(numbers))
print("Min:", min(numbers))
print("Sum:", sum(numbers))pythonnumbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)pythontext = input("Enter text: ")
freq = {}
for char in text:
freq[char] = freq.get(char, 0) + 1
print(freq)pythonstudent = {
"name": "Alice",
"age": 18,
"score": 95
}
for key, value in student.items():
print(key, value)pythondef is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print("Prime")
else:
print("Not prime")pythondef factorial(n):
if n < 0:
return None
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))try-except 处理除零错误try-except 处理文件不存在错误finally 关闭资源os 模块查看当前目录datetime 输出当前日期时间math 模块计算平方根random 模块实现随机抽奖pythontry:
num1 = float(input("Enter dividend: "))
num2 = float(input("Enter divisor: "))
result = num1 / num2
print(result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid numbers.")pythonwith open("notes.txt", "w", encoding="utf-8") as file:
file.write("Hello Python\n")
file.write("File handling practice\n")pythonwith open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)__init__Student 类Student 添加姓名和年龄属性Student 添加自我介绍方法Rectangle 类计算面积Circle 类计算面积和周长Calculator 类实现加减乘除BankAccount 类实现存款和取款Book 类保存书籍信息Employee 类计算工资pythonclass Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name}, I am {self.age} years old.")
student = Student("Alice", 18)
student.introduce()pythonclass Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(10, 5)
print(rect.area())pythonimport random
target = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if guess < target:
print("Too low")
elif guess > target:
print("Too high")
else:
print(f"Correct! You guessed it in {attempts} attempts.")
breakprint() 输出文本input() 获取输入int() 转整数float() 转浮点数str() 转字符串pythonname = "Python"
version = 3.12
print(f"{name} version is {version}")pythonif condition:
pass
elif another_condition:
pass
else:
pass适合题型:
pythonfor i in range(1, 11):
print(i)pythoncount = 1
while count <= 10:
print(count)
count += 1适合题型:
python# Triangle area
area = 0.5 * base * height
# Celsius to Fahrenheit
fahrenheit = celsius * 9 / 5 + 32
# Simple interest
interest = principal * rate * time / 100
# Compound interest
amount = principal * (1 + rate / 100) ** timepythontext = " Hello Python "
print(text.lower())
print(text.upper())
print(text.strip())
print(text.replace("Python", "World"))
print(text[::-1])pythonnumbers = [3, 1, 4, 1, 5]
numbers.append(9)
numbers.remove(1)
print(len(numbers))
print(sum(numbers))
print(max(numbers))
print(min(numbers))
print(sorted(numbers))完成 140+ 练习后,建议重点复盘以下问题:
input() 返回的是什么类型?int() 和 float() 类型转换失败会发生什么?/、//、%、** 分别是什么意思?get() 方法有什么好处?try-except 可以解决什么问题?with open() 相比手动 close() 有什么优势?__init__ 方法什么时候执行?markdown# Python Basic Programs
This repository contains 140+ basic Python programs for beginners.
## Topics
- Input and Output
- Arithmetic Operations
- Conditional Statements
- Loops
- Number Programs
- String Programs
- List, Tuple and Set Programs
- Dictionary Programs
- Functions and Recursion
- File Handling
- Object-Oriented Programming
- Mini Projects
## Progress
- [ ] Phase 1: Input and Output
- [ ] Phase 2: Math and Conversion
- [ ] Phase 3: Conditions
- [ ] Phase 4: Loops
- [ ] Phase 5: Number Programs
- [ ] Phase 6: Strings
- [ ] Phase 7: Lists and Tuples
- [ ] Phase 8: Dictionaries and Sets
- [ ] Phase 9: Functions
- [ ] Phase 10: Files and Exceptions
- [ ] Phase 11: OOP
- [ ] Phase 12: Mini Projects当你完成这份路线图后,应该能够:

关注公众号回复「资源」获取全部下载链接