Python零基础入门:环境搭建与基础语法详解
1. Python环境搭建与基础配置
对于零基础学习Python的第三天,我们需要先确保开发环境已经正确搭建。Python的安装过程虽然简单,但有几个关键点需要注意:
- 访问Python官网(https://www.python.org/downloads/)下载最新稳定版
- 安装时务必勾选"Add Python to PATH"选项
- 建议选择自定义安装路径,避免使用包含空格的目录名
安装完成后,打开命令提示符(cmd)或终端,输入 python --version 验证安装是否成功。如果看到类似"Python 3.12.0"的版本号输出,说明安装正确。
注意:Windows用户可能会遇到"python不是内部或外部命令"的错误,这通常是因为PATH环境变量未正确设置。解决方法是手动将Python安装目录(如C:\Python312)和Scripts目录(如C:\Python312\Scripts)添加到系统PATH中。
2. Python基础语法入门
2.1 变量与数据类型
Python是动态类型语言,变量声明时不需要指定类型。基础数据类型包括:
- 整数(int):如
age = 25 - 浮点数(float):如
price = 19.99 - 字符串(str):如
name = "Alice" - 布尔值(bool):
is_active = True
# 变量声明示例
counter = 100 # 整型
miles = 999.99 # 浮点型
name = "John Doe" # 字符串
is_valid = True # 布尔值
print(type(counter)) # 输出:<class 'int'>
print(type(miles)) # 输出:<class 'float'>
print(type(name)) # 输出:<class 'str'>
print(type(is_valid)) # 输出:<class 'bool'>
2.2 基本运算符
Python支持多种运算符:
- 算术运算符:
+,-,*,/,//(整除),%(取模),**(幂) - 比较运算符:
==,!=,>,<,>=,<= - 逻辑运算符:
and,or,not - 赋值运算符:
=,+=,-=,*=,/=
# 运算符示例
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a // b) # 3 (整除)
print(a % b) # 1 (取余)
print(a ** b) # 1000 (10的3次方)
print(a == b) # False
print(a != b) # True
print(a > b) # True
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
3. 控制流程语句
3.1 条件语句(if-elif-else)
Python使用缩进来表示代码块,条件语句的基本结构如下:
age = 18
if age < 13:
print("儿童")
elif age < 18:
print("青少年")
elif age < 60:
print("成年人")
else:
print("老年人")
3.2 循环语句
Python提供了两种主要的循环结构:
- while循环:
count = 0
while count < 5:
print(f"当前计数: {count}")
count += 1
- for循环(常用于遍历序列):
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 使用range()函数
for i in range(5): # 0到4
print(i)
for i in range(2, 6): # 2到5
print(i)
for i in range(0, 10, 2): # 0到9,步长为2
print(i)
4. 函数定义与使用
函数是组织代码的重要方式,Python中使用 def 关键字定义函数:
# 简单函数示例
def greet(name):
"""这是一个问候函数"""
return f"Hello, {name}!"
print(greet("Alice")) # 输出:Hello, Alice!
# 带默认参数的函数
def power(base, exponent=2):
"""计算幂,默认计算平方"""
return base ** exponent
print(power(3)) # 输出:9 (3的平方)
print(power(3, 3)) # 输出:27 (3的立方)
# 可变参数函数
def sum_all(*numbers):
"""计算任意数量数字的和"""
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # 输出:6
print(sum_all(1, 2, 3, 4, 5)) # 输出:15
5. 列表(List)基础操作
列表是Python中最常用的数据结构之一,可以存储任意类型的元素:
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
# 访问元素
print(fruits[0]) # 输出:apple
print(fruits[-1]) # 输出:cherry (负索引表示从后往前)
# 修改元素
fruits[1] = "blueberry"
print(fruits) # 输出:['apple', 'blueberry', 'cherry']
# 列表切片
print(numbers[1:3]) # 输出:[2, 3] (索引1到2)
print(numbers[:3]) # 输出:[1, 2, 3] (从开始到索引2)
print(numbers[2:]) # 输出:[3, 4, 5] (从索引2到结束)
print(numbers[::2]) # 输出:[1, 3, 5] (步长为2)
# 常用列表方法
fruits.append("orange") # 添加元素到末尾
fruits.insert(1, "mango") # 在指定位置插入元素
fruits.remove("apple") # 删除指定元素
popped = fruits.pop() # 移除并返回最后一个元素
fruits.sort() # 排序(原地修改)
sorted_fruits = sorted(fruits) # 返回新排序列表
# 列表长度
print(len(fruits)) # 输出当前列表长度
6. 字符串操作进阶
Python字符串是不可变序列,提供了丰富的操作方法:
text = "Python Programming"
# 常用字符串方法
print(text.lower()) # 转为小写
print(text.upper()) # 转为大写
print(text.title()) # 每个单词首字母大写
print(text.split()) # 分割为单词列表
print("-".join(["Python", "Programming"])) # 连接字符串
# 字符串格式化
name = "Alice"
age = 25
# f-string (Python 3.6+)
print(f"My name is {name} and I'm {age} years old.")
# format方法
print("My name is {} and I'm {} years old.".format(name, age))
# %格式化(旧式)
print("My name is %s and I'm %d years old." % (name, age))
# 字符串检查
print(text.startswith("Py")) # True
print(text.endswith("ing")) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True
# 字符串替换
print(text.replace("Python", "Java")) # Java Programming
7. 文件读写操作
Python使用内置的 open() 函数进行文件操作:
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write("Hello, Python!\n")
f.write("这是第二行\n")
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部内容
print(content)
# 回到文件开头
f.seek(0)
lines = f.readlines() # 读取所有行到列表
for line in lines:
print(line.strip()) # 去除每行两端的空白字符
# 逐行读取(推荐方式)
with open("example.txt", "r", encoding="utf-8") as f:
for line in f: # 文件对象是可迭代的
print(line.strip())
# 追加内容
with open("example.txt", "a", encoding="utf-8") as f:
f.write("这是追加的内容\n")
提示:使用
with语句可以确保文件在使用后自动关闭,这是处理文件的推荐方式。编码参数(encoding)通常设置为'utf-8'以避免中文乱码问题。
8. 异常处理基础
Python使用try-except块处理异常:
# 基本异常处理
try:
num = int(input("请输入一个整数: "))
result = 100 / num
print(f"结果是: {result}")
except ValueError:
print("输入的不是有效整数!")
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"发生未知错误: {e}")
else:
print("计算成功完成!")
finally:
print("这是finally块,无论是否发生异常都会执行")
# 自定义异常
class MyCustomError(Exception):
"""自定义异常类"""
pass
def check_age(age):
if age < 0:
raise MyCustomError("年龄不能为负数")
return age >= 18
try:
is_adult = check_age(-5)
except MyCustomError as e:
print(f"自定义错误: {e}")
9. 常用内置模块
Python标准库提供了丰富的内置模块,以下是一些常用模块的示例:
9.1 os模块 - 操作系统接口
import os
# 获取当前工作目录
print(os.getcwd())
# 列出目录内容
print(os.listdir('.'))
# 创建目录
os.makedirs('test_dir', exist_ok=True)
# 路径操作
file_path = os.path.join('test_dir', 'test.txt')
print(file_path) # 输出:test_dir/test.txt (Linux) 或 test_dir\test.txt (Windows)
# 检查文件/目录是否存在
print(os.path.exists(file_path))
9.2 datetime模块 - 日期时间处理
from datetime import datetime, date, timedelta
# 获取当前日期时间
now = datetime.now()
print(f"当前时间: {now}")
print(f"格式化输出: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# 创建特定日期
some_date = date(2023, 12, 25)
print(f"圣诞节: {some_date}")
# 日期运算
tomorrow = now + timedelta(days=1)
print(f"明天这个时候: {tomorrow}")
# 解析字符串为日期
date_str = "2023-08-15"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d").date()
print(f"解析后的日期: {parsed_date}")
9.3 random模块 - 随机数生成
import random
# 生成随机整数
print(random.randint(1, 100)) # 1到100之间的随机整数
# 生成随机浮点数
print(random.random()) # 0.0到1.0之间的随机浮点数
print(random.uniform(1.5, 4.5)) # 1.5到4.5之间的随机浮点数
# 从序列中随机选择
colors = ['red', 'green', 'blue', 'yellow']
print(random.choice(colors)) # 随机选择一个元素
print(random.sample(colors, 2)) # 随机选择2个不重复元素
# 打乱序列顺序
random.shuffle(colors)
print(colors) # 打乱后的列表
10. 项目实战:简易通讯录管理
结合第三天所学知识,我们可以实现一个简易的通讯录管理系统:
# 简易通讯录管理系统
contacts = []
def add_contact():
"""添加联系人"""
name = input("请输入姓名: ")
phone = input("请输入电话: ")
email = input("请输入邮箱: ")
contacts.append({"name": name, "phone": phone, "email": email})
print("联系人添加成功!")
def list_contacts():
"""列出所有联系人"""
if not contacts:
print("通讯录为空")
return
print("\n通讯录列表:")
for idx, contact in enumerate(contacts, 1):
print(f"{idx}. 姓名: {contact['name']}, 电话: {contact['phone']}, 邮箱: {contact['email']}")
def search_contact():
"""搜索联系人"""
keyword = input("请输入搜索关键词: ").lower()
results = []
for contact in contacts:
if (keyword in contact['name'].lower() or
keyword in contact['phone'] or
keyword in contact['email'].lower()):
results.append(contact)
if results:
print("\n找到以下联系人:")
for contact in results:
print(f"姓名: {contact['name']}, 电话: {contact['phone']}, 邮箱: {contact['email']}")
else:
print("未找到匹配的联系人")
def save_to_file():
"""保存通讯录到文件"""
with open("contacts.txt", "w", encoding="utf-8") as f:
for contact in contacts:
f.write(f"{contact['name']},{contact['phone']},{contact['email']}\n")
print("通讯录已保存到contacts.txt")
def load_from_file():
"""从文件加载通讯录"""
try:
with open("contacts.txt", "r", encoding="utf-8") as f:
for line in f:
name, phone, email = line.strip().split(',')
contacts.append({"name": name, "phone": phone, "email": email})
print("通讯录已从文件加载")
except FileNotFoundError:
print("未找到通讯录文件,将使用空通讯录")
def main():
"""主菜单"""
load_from_file()
while True:
print("\n=== 简易通讯录管理系统 ===")
print("1. 添加联系人")
print("2. 查看所有联系人")
print("3. 搜索联系人")
print("4. 保存通讯录")
print("0. 退出系统")
choice = input("请选择操作: ")
if choice == '1':
add_contact()
elif choice == '2':
list_contacts()
elif choice == '3':
search_contact()
elif choice == '4':
save_to_file()
elif choice == '0':
print("感谢使用通讯录管理系统,再见!")
break
else:
print("无效的选择,请重新输入")
if __name__ == "__main__":
main()
这个项目综合运用了变量、数据类型、控制流程、函数、列表、字符串操作、文件读写等知识点,是第三天学习内容的很好实践。你可以运行这个程序,体验如何添加、查看、搜索和保存联系人信息。
更多推荐



所有评论(0)