网站首页 > 文章精选 正文
Python 是一种简单易学且功能强大的编程语言,适合初学者入门学习,不论是就业还是做副业赚钱或者是提高自己办公效率都是不错的选择。
1. 安装 Python
- 下载 Python :前往 Python 官方网站Welcome to Python.org,获取最新版本的 Python 以供下载。
- 安装 Python:按照安装向导完成安装,确保勾选“Add Python to PATH”选项。
- 验证安装:打开命令行(Windows 上是 cmd,Mac/Linux 上是 Terminal),输入 python --version,查看是否显示 Python 版本。
2. 选择开发工具
- IDLE:Python 自带的简易开发环境,适合初学者。
- VS Code:轻量级且功能强大的代码编辑器,支持 Python 插件。
- PyCharm:专业的 Python IDE,适合中高级开发者。
- Jupyter Notebook:适合数据分析和交互式编程。
3. 基础知识
- 变量与数据类型
# 整数
num_int = 10
# 浮点数
num_float = 3.14
# 字符串
str_example = "Hello, Python!"
# 布尔值
bool_example = True
print("整数:", num_int)
print("浮点数:", num_float)
print("字符串:", str_example)
print("布尔值:", bool_example)
- 列表
list_example = [1, 2, 3, "four", 5.0]
print("列表:", list_example)
- 元组
tuple_example = (1, 2, 3, "four", 5.0)
print("元组:", tuple_example)
- 字典
dict_example = {"name": "Alice", "age": 25, "city": "New York"}
print("字典:", dict_example)
- 条件语句
age = 18
if age >= 18:
print("你已成年")
else:
print("你未成年")
- 循环语句
# for 循环
for i in range(5):
print(i)
# while 循环
count = 0
while count < 5:
print(count)
count += 1
- 函数
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print("函数结果:", result)
- 类与对象
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} 正在汪汪叫!")
my_dog = Dog("Buddy", 3)
my_dog.bark()
以下是一个小示例
import random
# 猜数字小游戏函数
def guess_number_game():
# 生成 1 到 100 之间的随机整数
secret_number = random.randint(1, 100)
attempts = 0
print("欢迎来到猜数字小游戏!我已经想好了一个 1 到 100 之间的整数,你可以开始猜啦。")
while True:
try:
# 获取用户输入
user_guess = int(input("请输入你猜的数字: "))
attempts += 1
if user_guess < secret_number:
print("猜的数字太小了,再试试!")
elif user_guess > secret_number:
print("猜的数字太大了,再试试!")
else:
print(f"恭喜你,猜对了!你一共用了 {attempts} 次尝试。")
break
except ValueError:
print("输入无效,请输入一个整数。")
# 调用猜数字小游戏函数
guess_number_game()
4. 文件操作与异常处理
- 读取一个文本文件的内容并打印
try:
with open('test.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到。")
- 向一个文本文件写入内容
try:
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("这是写入的内容。")
except Exception as e:
print(f"写入文件时出错: {e}")
- 向一个文本文件追加内容
try:
with open('output.txt', 'a', encoding='utf-8') as file:
file.write("\n这是追加的内容。")
except Exception as e:
print(f"追加文件时出错: {e}")
- 处理除零错误和类型错误
try:
a = 10
b = 0
result = a / b
except ZeroDivisionError:
print("除数不能为零。")
except TypeError:
print("类型错误。")
- 自定义异常类
class MyError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
try:
raise MyError("这是一个自定义异常。")
except MyError as e:
print(e)
- 简单的日志系统
import os
class Logger:
def __init__(self, log_file):
self.log_file = log_file
def log(self, message):
try:
if not os.path.exists(self.log_file):
with open(self.log_file, 'w', encoding='utf-8') as file:
file.write(f"{message}\n")
else:
with open(self.log_file, 'a', encoding='utf-8') as file:
file.write(f"{message}\n")
except Exception as e:
print(f"写入日志时出错: {e}")
logger = Logger('app.log')
logger.log("程序启动")
logger.log("执行操作...")
logger.log("程序结束")
5. 标准库
- datetime 模块
# 获取当前日期和时间,并进行日期计算
import datetime
now = datetime.datetime.now()
print(f"当前日期和时间: {now}")
tomorrow = now + datetime.timedelta(days=1)
print(f"明天的日期和时间: {tomorrow}")
- random 模块
# 生成随机数和随机选择元素
import random
# 生成 1 到 10 之间的随机整数
random_num = random.randint(1, 10)
print(f"随机整数: {random_num}")
# 从列表中随机选择一个元素
fruits = ["apple", "banana", "cherry"]
random_fruit = random.choice(fruits)
print(f"随机选择的水果: {random_fruit}")
- json 模块
import json
data = {"name": "Frank", "age": 35}
# 将 Python 字典转换为 JSON 字符串
json_str = json.dumps(data)
print(f"JSON 字符串: {json_str}")
# 将 JSON 字符串保存到文件
with open('data.json', 'w', encoding='utf-8') as file:
json.dump(data, file)
# 从文件中读取 JSON 字符串并转换为 Python 字典
with open('data.json', 'r', encoding='utf-8') as file:
loaded_data = json.load(file)
print(f"加载的 Python 字典: {loaded_data}")
- os 模块
import os
# 查看当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")
# 创建文件夹
new_folder = "test_folder"
if not os.path.exists(new_folder):
os.mkdir(new_folder)
print(f"创建文件夹: {new_folder}")
# 删除文件
file_to_delete = "test.txt"
if os.path.exists(file_to_delete):
os.remove(file_to_delete)
print(f"删除文件: {file_to_delete}")
待办事项管理系统
import json
def load_tasks():
try:
with open('tasks.json', 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
return []
def save_tasks(tasks):
with open('tasks.json', 'w', encoding='utf-8') as file:
json.dump(tasks, file)
def add_task(tasks, task):
tasks.append(task)
save_tasks(tasks)
print(f"添加任务: {task}")
def remove_task(tasks, task):
if task in tasks:
tasks.remove(task)
save_tasks(tasks)
print(f"删除任务: {task}")
else:
print(f"任务 {task} 不存在。")
def show_tasks(tasks):
if tasks:
print("待办事项列表:")
for index, task in enumerate(tasks, start=1):
print(f"{index}. {task}")
else:
print("待办事项列表为空。")
tasks = load_tasks()
while True:
print("\n1. 添加任务")
print("2. 删除任务")
print("3. 显示任务列表")
print("4. 退出")
choice = input("请输入你的选择: ")
if choice == '1':
task = input("请输入要添加的任务: ")
add_task(tasks, task)
elif choice == '2':
task = input("请输入要删除的任务: ")
remove_task(tasks, task)
elif choice == '3':
show_tasks(tasks)
elif choice == '4':
break
else:
print("无效的选择,请重新输入。")
猜你喜欢
- 2025-05-08 携手爱驰智能汽车,浪潮AIStation提速个性化驾驶AI助手开发
- 2025-05-08 Python语言怎么和土木工程专业结合使用
- 2025-05-08 人生苦短,我要在VSCode里面用Python
- 2025-05-08 教你编写第一个Python程序(python编程第一步)
- 2025-05-08 刚接触python编译器和Pycharm的区别是什么?
- 2025-05-08 python开发工具PyCharm最新版本新增功能介绍
- 2025-05-08 Python工具之Jupyter的扩展插件(jupyter插件推荐)
- 2025-05-08 使用VScode的几点感受,对比Pycharm、Jupyter优劣势
- 2025-05-08 手把手教你在VSCode下如何使用Jupyter
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)