代码改变世界

实用指南:Python基础入门:60分钟快速掌握入门知识

2025-10-15 10:11  tlnshuju  阅读(31)  评论(0)    收藏  举报

专栏导读

  • 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
  • ️‍ 博客主页:请点击——> 一晌小贪欢的博客主页求关注
  • 该系列文章专栏:请点击——>Python办公自动化专栏求订阅
  • 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅
  • 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正
  • ❤️ 欢迎各位佬关注! ❤️

学习目标

在60分钟内,您将学会:

  • Python基础语法和数据类型
  • 控制结构(条件语句、循环)
  • 函数定义和使用
  • 文件操作和模块导入
  • 3个实战项目:计算器、文件管理器、简单爬虫

⏰ 时间安排

  • 0-15分钟:基础语法(变量、数据类型、运算符)
  • 15-30分钟:控制结构(if语句、for/while循环)
  • 30-40分钟:函数和模块
  • 40-60分钟:实战项目

第一部分:基础语法(0-15分钟)

1.1 Python简介

Python是一种简单易学的编程语言,语法清晰,功能强大。

1.2 变量和数据类型

变量定义
# 变量不需要声明类型,直接赋值
name = "张三"        # 字符串
age = 25            # 整数
height = 1.75       # 浮点数
is_student = True   # 布尔值
基本数据类型
# 1. 数字类型
integer_num = 42        # 整数
float_num = 3.14       # 浮点数
complex_num = 3 + 4j   # 复数
# 2. 字符串
text = "Hello, Python!"
multiline_text = """
这是一个
多行字符串
"""
# 3. 布尔值
is_true = True
is_false = False
# 4. 列表(可变)
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
# 5. 元组(不可变)
coordinates = (10, 20)
colors = ("红", "绿", "蓝")
# 6. 字典
person = {
"姓名": "李四",
"年龄": 30,
"城市": "北京"
}
# 7. 集合
unique_numbers = {1, 2, 3, 4, 5}
类型检查和转换
# 检查类型
print(type(name))      # <class 'str'>
  print(type(age))       # <class 'int'>
    # 类型转换
    str_num = "123"
    int_num = int(str_num)     # 字符串转整数
    float_num = float(str_num) # 字符串转浮点数
    str_age = str(age)         # 整数转字符串

1.3 运算符

算术运算符
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
比较运算符
x = 5
y = 10
print(x == y)   # 等于:False
print(x != y)   # 不等于:True
print(x < y)    # 小于:True
print(x > y)    # 大于:False
print(x <= y)   # 小于等于:True
print(x >= y)   # 大于等于:False
逻辑运算符
p = True
q = False
print(p and q)  # 与:False
print(p or q)   # 或:True
print(not p)    # 非:False

1.4 字符串操作

text = "Python编程"
# 字符串长度
print(len(text))        # 8
# 字符串拼接
greeting = "Hello, " + "World!"
formatted = f"我的名字是{name},今年{age}岁"
# 字符串方法
print(text.upper())     # 转大写
print(text.lower())     # 转小写
print(text.replace("Python", "Java"))  # 替换
# 字符串切片
print(text[0])          # 第一个字符:P
print(text[0:6])        # 前6个字符:Python
print(text[-2:])        # 最后2个字符:编程

第二部分:控制结构(15-30分钟)

2.1 条件语句

if语句基础
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
条件表达式(三元运算符)
age = 18
status = "成年人" if age >= 18 else "未成年人"
print(status)
复合条件
username = "admin"
password = "123456"
if username == "admin" and password == "123456":
print("登录成功")
else:
print("用户名或密码错误")

2.2 循环语句

for循环
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# 遍历范围
for i in range(5):          # 0到4
print(f"第{i+1}次循环")
for i in range(1, 6):       # 1到5
print(i)
for i in range(0, 10, 2):   # 0到9,步长为2
print(i)                # 输出:0, 2, 4, 6, 8
# 遍历字典
person = {"姓名": "王五", "年龄": 28, "职业": "程序员"}
for key, value in person.items():
print(f"{key}: {value}")
while循环
# 基础while循环
count = 0
while count < 5:
print(f"计数:{count}")
count += 1
# 用户输入循环
while True:
user_input = input("请输入命令(输入'quit'退出):")
if user_input == "quit":
break
print(f"您输入了:{user_input}")
循环控制
# break:跳出循环
for i in range(10):
if i == 5:
break
print(i)        # 输出:0, 1, 2, 3, 4
# continue:跳过当前迭代
for i in range(10):
if i % 2 == 0:  # 跳过偶数
continue
print(i)        # 输出:1, 3, 5, 7, 9

2.3 列表推导式

# 传统方法
squares = []
for i in range(10):
squares.append(i ** 2)
# 列表推导式(更简洁)
squares = [i ** 2 for i in range(10)]
# 带条件的列表推导式
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

第三部分:函数和模块(30-40分钟)

3.1 函数定义和调用

基础函数
def greet(name):
"""问候函数"""
return f"你好,{name}!"
# 调用函数
message = greet("小明")
print(message)
参数类型
# 默认参数
def introduce(name, age=18, city="北京"):
return f"我叫{name},今年{age}岁,来自{city}"
print(introduce("张三"))                    # 使用默认值
print(introduce("李四", 25))                # 部分使用默认值
print(introduce("王五", 30, "上海"))         # 全部指定
# 可变参数
def calculate_sum(*numbers):
"""计算任意数量数字的和"""
return sum(numbers)
print(calculate_sum(1, 2, 3))           # 6
print(calculate_sum(1, 2, 3, 4, 5))     # 15
# 关键字参数
def create_profile(**kwargs):
"""创建用户档案"""
profile = {}
for key, value in kwargs.items():
profile[key] = value
return profile
user = create_profile(name="赵六", age=22, hobby="编程")
print(user)
返回值
def divide(a, b):
"""除法运算,返回商和余数"""
if b == 0:
return None, "除数不能为零"
return a // b, a % b
quotient, remainder = divide(10, 3)
print(f"商:{quotient},余数:{remainder}")

3.2 作用域和闭包

# 全局变量和局部变量
global_var = "我是全局变量"
def test_scope():
local_var = "我是局部变量"
print(global_var)   # 可以访问全局变量
print(local_var)    # 可以访问局部变量
test_scope()
# print(local_var)    # 错误:无法访问局部变量
# 闭包
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
add_10 = outer_function(10)
print(add_10(5))    # 15

3.3 模块和包

导入模块
# 导入整个模块
import math
print(math.pi)          # 3.141592653589793
print(math.sqrt(16))    # 4.0
# 导入特定函数
from math import pi, sqrt
print(pi)
print(sqrt(25))
# 导入并重命名
import datetime as dt
now = dt.datetime.now()
print(now)
# 导入所有(不推荐)
from math import *
常用内置模块
# random模块
import random
print(random.randint(1, 10))        # 随机整数
print(random.choice(["A", "B", "C"]))  # 随机选择
# datetime模块
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(f"现在:{now}")
print(f"明天:{tomorrow}")
# os模块
import os
print(os.getcwd())          # 当前工作目录
# os.mkdir("新文件夹")       # 创建文件夹

第四部分:实战项目(40-60分钟)

项目1:简单计算器(10分钟)

def calculator():
"""简单计算器"""
print("=== 简单计算器 ===")
print("支持的操作:+, -, *, /, quit")
while True:
try:
operation = input("请输入操作(如:5 + 3)或输入'quit'退出:")
if operation.lower() == 'quit':
print("再见!")
break
# 解析输入
parts = operation.split()
if len(parts) != 3:
print("格式错误,请使用:数字 运算符 数字")
continue
num1 = float(parts[0])
operator = parts[1]
num2 = float(parts[2])
# 计算结果
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("错误:除数不能为零")
continue
result = num1 / num2
else:
print("不支持的运算符")
continue
print(f"结果:{num1} {operator} {num2} = {result}")
except ValueError:
print("输入错误,请输入有效的数字")
except Exception as e:
print(f"发生错误:{e}")
# 运行计算器
# calculator()

项目2:文件管理器(10分钟)

import os
from datetime import datetime
def file_manager():
"""简单文件管理器"""
print("=== 文件管理器 ===")
while True:
print("\n可用命令:")
print("1. ls - 列出当前目录文件")
print("2. cd <目录名> - 切换目录")
  print("3. mkdir <目录名> - 创建目录")
    print("4. create <文件名> - 创建文件")
      print("5. read <文件名> - 读取文件")
        print("6. write <文件名> - 写入文件")
          print("7. pwd - 显示当前路径")
          print("8. quit - 退出")
          command = input("\n请输入命令:").strip().split()
          if not command:
          continue
          cmd = command[0].lower()
          try:
          if cmd == 'quit':
          print("再见!")
          break
          elif cmd == 'ls':
          list_directory()
          elif cmd == 'cd' and len(command) > 1:
          change_directory(command[1])
          elif cmd == 'mkdir' and len(command) > 1:
          create_directory(command[1])
          elif cmd == 'create' and len(command) > 1:
          create_file(command[1])
          elif cmd == 'read' and len(command) > 1:
          read_file(command[1])
          elif cmd == 'write' and len(command) > 1:
          write_file(command[1])
          elif cmd == 'pwd':
          print(f"当前路径:{os.getcwd()}")
          else:
          print("无效命令或缺少参数")
          except Exception as e:
          print(f"错误:{e}")
          def list_directory():
          """列出当前目录内容"""
          items = os.listdir('.')
          if not items:
          print("目录为空")
          return
          print("\n目录内容:")
          for item in sorted(items):
          if os.path.isdir(item):
          print(f" {item}/")
          else:
          size = os.path.getsize(item)
          print(f" {item} ({size} bytes)")
          def change_directory(path):
          """切换目录"""
          os.chdir(path)
          print(f"已切换到:{os.getcwd()}")
          def create_directory(name):
          """创建目录"""
          os.makedirs(name, exist_ok=True)
          print(f"目录 '{name}' 创建成功")
          def create_file(filename):
          """创建文件"""
          with open(filename, 'w', encoding='utf-8') as f:
          f.write(f"# 文件创建于 {datetime.now()}\n")
          print(f"文件 '{filename}' 创建成功")
          def read_file(filename):
          """读取文件"""
          with open(filename, 'r', encoding='utf-8') as f:
          content = f.read()
          print(f"\n--- {filename} 内容 ---")
          print(content)
          print("--- 文件结束 ---")
          def write_file(filename):
          """写入文件"""
          print("请输入文件内容(输入'EOF'结束):")
          lines = []
          while True:
          line = input()
          if line == 'EOF':
          break
          lines.append(line)
          with open(filename, 'w', encoding='utf-8') as f:
          f.write('\n'.join(lines))
          print(f"内容已写入 '{filename}'")
          # 运行文件管理器
          # file_manager()

项目3:简单网页信息提取器(10分钟)

import urllib.request
import re
from urllib.parse import urljoin, urlparse
def simple_web_scraper():
"""简单网页信息提取器"""
print("=== 简单网页信息提取器 ===")
while True:
print("\n功能选项:")
print("1. 提取网页标题")
print("2. 提取所有链接")
print("3. 提取图片链接")
print("4. 统计词频")
print("5. quit - 退出")
choice = input("请选择功能(1-5):").strip()
if choice == '5' or choice.lower() == 'quit':
print("再见!")
break
if choice in ['1', '2', '3', '4']:
url = input("请输入网页URL:").strip()
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
try:
html_content = fetch_webpage(url)
if choice == '1':
extract_title(html_content)
elif choice == '2':
extract_links(html_content, url)
elif choice == '3':
extract_images(html_content, url)
elif choice == '4':
count_words(html_content)
except Exception as e:
print(f"错误:{e}")
else:
print("无效选择")
def fetch_webpage(url):
"""获取网页内容"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=10) as response:
content = response.read().decode('utf-8', errors='ignore')
return content
def extract_title(html):
"""提取网页标题"""
title_match = re.search(r'<title>(.*?)</title>', html, re.IGNORECASE | re.DOTALL)
if title_match:
title = title_match.group(1).strip()
print(f"网页标题:{title}")
else:
print("未找到网页标题")
def extract_links(html, base_url):
"""提取所有链接"""
link_pattern = r'<a[^>]+href=["\']([^"\']+)["\'][^>]*>(.*?)</a>'
links = re.findall(link_pattern, html, re.IGNORECASE | re.DOTALL)
if links:
print(f"\n找到 {len(links)} 个链接:")
for i, (url, text) in enumerate(links[:10], 1):  # 只显示前10个
# 处理相对链接
full_url = urljoin(base_url, url)
text = re.sub(r'<[^>]+>', '', text).strip()  # 移除HTML标签
  print(f"{i}. {text[:50]}... -> {full_url}")
  if len(links) > 10:
  print(f"... 还有 {len(links) - 10} 个链接")
  else:
  print("未找到链接")
  def extract_images(html, base_url):
  """提取图片链接"""
  img_pattern = r'<img[^>]+src=["\']([^"\']+)["\'][^>]*>'
    images = re.findall(img_pattern, html, re.IGNORECASE)
    if images:
    print(f"\n找到 {len(images)} 个图片:")
    for i, img_url in enumerate(images[:10], 1):  # 只显示前10个
    full_url = urljoin(base_url, img_url)
    print(f"{i}. {full_url}")
    if len(images) > 10:
    print(f"... 还有 {len(images) - 10} 个图片")
    else:
    print("未找到图片")
    def count_words(html):
    """统计词频"""
    # 移除HTML标签
    text = re.sub(r'<[^>]+>', ' ', html)
      # 移除特殊字符,只保留字母和数字
      text = re.sub(r'[^\w\s]', ' ', text)
      # 转换为小写并分割单词
      words = text.lower().split()
      # 统计词频
      word_count = {}
      for word in words:
      if len(word) > 2:  # 只统计长度大于2的单词
      word_count[word] = word_count.get(word, 0) + 1
      # 排序并显示前10个高频词
      if word_count:
      sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
      print(f"\n词频统计(前10个):")
      for i, (word, count) in enumerate(sorted_words[:10], 1):
      print(f"{i}. {word}: {count}次")
      else:
      print("未找到有效单词")
      # 运行网页信息提取器
      # simple_web_scraper()

学习总结

核心概念回顾

  1. 变量和数据类型:字符串、数字、列表、字典等
  2. 控制结构:if/elif/else、for/while循环
  3. 函数:定义、参数、返回值、作用域
  4. 模块:导入和使用标准库
  5. 异常处理:try/except语句

最佳实践

  1. 代码风格:使用有意义的变量名,添加注释
  2. 错误处理:使用try/except处理可能的错误
  3. 函数设计:保持函数简单,单一职责
  4. 代码复用:将重复的代码封装成函数

下一步学习建议

  1. 面向对象编程:类和对象
  2. 文件和数据处理:CSV、JSON、数据库
  3. 网络编程:requests库、API调用
  4. 数据科学:pandas、numpy、matplotlib
  5. Web开发:Flask、Django框架

练习建议

  1. 每天编写小程序练习语法
  2. 阅读其他人的代码学习技巧
  3. 参与开源项目贡献代码
  4. 解决实际问题,如数据处理、自动化任务

快速参考

常用语法速查

# 变量赋值
name = "值"
# 条件语句
if condition:
# 代码块
elif other_condition:
# 代码块
else:
# 代码块
# 循环
for item in iterable:
# 代码块
while condition:
# 代码块
# 函数定义
def function_name(parameters):
# 代码块
return value
# 异常处理
try:
# 可能出错的代码
except Exception as e:
# 错误处理

常用内置函数

len()       # 获取长度
type()      # 获取类型
str()       # 转换为字符串
int()       # 转换为整数
float()     # 转换为浮点数
list()      # 转换为列表
dict()      # 转换为字典
range()     # 生成数字序列
enumerate() # 枚举索引和值
zip()       # 并行迭代

恭喜您完成了Python零基础入门教程!现在您已经掌握了Python的核心语法和基本应用。继续练习和探索,您将成为一名优秀的Python程序员!✨

结尾

  • 希望对初学者有帮助;致力于办公自动化的小小程序员一枚
  • 希望能得到大家的【❤️一个免费关注❤️】感谢!
  • 求个 关注 +❤️ 喜欢 ❤️ + 收藏
  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏
  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏
  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏