AITC Wiki

Python 入门

Introduction to Python

Python 入门

English version: Introduction to Python

Python 编程动手入门:变量、数据类型、运算符、控制流、函数、类与文件读写。

概述

Python 是一种广泛用于数据科学和大数据分析的高级解释型编程语言。本讲涵盖编写 Python 程序所需的基础概念,从基本语法到面向对象编程。

Info

Python 采用动态类型 —— 变量的数据类型在运行时自动确定,且变量可以在执行过程中自由赋值为不同类型的值。

开发环境

常用的 Python 集成开发环境(IDE):

IDE说明
PyCharmJetBrains 开发的强大、功能丰富的 IDE,提供广泛的工具与特性。
JupyterLab社区驱动的灵活 Web 编辑器,最初作为 Jupyter Notebook 的下一代界面。
VS CodeMicrosoft 开发的轻量但强大的代码编辑器,高度可扩展。

变量与动态类型

变量是一个指向内存中存储值的名字。变量通过赋值语句(=)创建:

x = 42
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)

由于 Python 使用动态类型,创建变量时无需提前声明类型。类型根据所赋的值自动推断,且可以在执行过程中改变:

x = 42           # x 是整数
x = "First year" # 现在 x 是字符串

但不兼容的操作会在运行时报错:

x = 5
y = "text"
print(x + y)  # Error: unsupported operand type(s) for +: 'int' and 'str'

变量命名规则

  • 必须以字母或下划线 _ 开头
  • 区分大小写(spamSpamSPAM 是不同的变量)
  • 不能使用保留字作为标识符

合法名称: spameggsspam23_speed
非法名称: 23spam#signvar.12

保留字

False    class    return   is       finally
None     if       for      lambda   continue
True     def      from     while    nonlocal
and      del      global   not      with
as       elif     try      or       yield
assert   else     import   pass
break    except   in       raise

数据类型

Python 提供多种内置数据类型,总结如下:

数据类型类别说明可变性
int数值整数(如 5-3不可变
float数值浮点数(如 3.14-0.5不可变
complex数值复数(如 3+4j不可变
str文本Unicode 字符序列(如 "hello"不可变
bool布尔布尔值:TrueFalse不可变
list序列有序、可变集合(如 [1, "a", True]可变
tuple序列有序、不可变集合(如 (1, "a", True)不可变
range序列不可变的数字序列(如 range(5)不可变
dict映射无序键值对(如 {"name": "Alice"}可变
set集合无序不重复元素集合(如 {1, 2, 3}可变
NoneType空值表示无值(None不可变

数值类型

# 整数
age = 25
print(age)  # Output: 25
 
# 浮点数
price = 19.99
print(price)  # Output: 19.99
 
# 复数
z = 3 + 4j
print(z.real)  # Output: 3.0
print(z.imag)  # Output: 4.0

布尔类型

is_empty = False
print(5 > 3)       # Output: True
print(5 < 3)       # Output: False
print(not is_empty)  # Output: True

文本类型

greeting = "Hello, Python!"
print(greeting[0:5])  # Output: Hello
print(len(greeting))  # Output: 13

序列类型

# 列表(可变)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']
 
# 元组(不可变)
colors = ("red", "green", "blue")
print(colors[1])  # Output: green
# colors[1] = "yellow"  # Error: tuples are immutable
 
# 范围
numbers = list(range(1, 10, 2))
print(numbers)  # Output: [1, 3, 5, 7, 9]
 
numbers = range(5)  # 0, 1, 2, 3, 4; start = 0; step = 1
print(list(numbers))  # Output: [0, 1, 2, 3, 4]

映射类型

# 字典(dict)
person = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
print(person["name"])  # Output: Alice
person["email"] = "alice@example.com"  # 添加新键值对

集合类型

# 集合(可变,元素唯一)
unique_numbers = {1, 2, 2, 3}
print(unique_numbers)  # Output: {1, 2, 3}(重复被移除)
 
unique_numbers.add(40)
print(unique_numbers)  # Output: {1, 2, 3, 40}

Warning

集合是无序集合。通过索引访问元素(如 my_set[0])会引发 TypeError

NoneType

result = None
print(result)  # Output: None

类型检查与转换

a = 2
print(type(a))   # <class 'int'>
a = float(a)     # 2.0
a = str(a)       # '2'

运算符

算术运算符

运算符运算
+加法
-减法
*乘法
/除法
**幂运算
%取余(模)
//整除
a = 10
b = 3
print("Sum:", a + b)          # 13
print("Difference:", a - b)   # 7
print("Product:", a * b)      # 30
print("Quotient:", a / b)     # 3.333...
print("Modulus:", a % b)      # 1
print("Exponent:", a ** b)    # 1000
print("Floor division:", a // b)  # 3

math 模块

import math
print(math.sqrt(25))   # 5.0
print(math.sqrt(4))    # 2.0
print(math.pow(4, 2))  # 16.0
 
x = [1.12, 2, 3]
print(math.fsum(x))    # 6.12(浮点数高精度求和)
print(sum(x))          # 6.12(Python 内置函数)

比较运算符

用于条件判断和 if 语句:

运算符含义
==等于
!=不等于
>大于
<小于
>=大于等于
<=小于等于

逻辑运算符

用于组合多个条件:

运算符含义
and两边都为真时才为真
or至少一边为真即为真
not取反布尔值

控制流

If 语句

Python 中的代码块通过缩进(4 个空格或一个制表符)定义。冒号 : 用于开始一个代码块。

num = float(input("Enter a number: "))
if num > 0:
    print("Positive!")
elif num < 0:
    print("Negative!")
else:
    print("Zero!")

组合条件

num = 15
if 10 <= num <= 20:
    print("In range!")
else:
    print("Out of range!")
 
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "1234":
    print("Login successful!")
else:
    print("Invalid credentials.")

For 循环

# 打印 1 到 5
for i in range(1, 6):
    print(i)
 
# 累加列表中的所有数字
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
    total += num
print("Sum:", total)  # 15

While 循环

# 从 5 倒数到 1
count = 5
while count > 0:
    print(count)
    count -= 1

Continue 与 Break

# 使用 continue 跳过偶数
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # 输出 1, 3, 5, 7, 9
 
# 使用 break 满足条件时立即退出循环
for num in range(1, 100):
    if num % 7 == 0:
        print("First multiple of 7:", num)  # 7
        break

嵌套循环

# 乘法表(1 到 3)
for i in range(1, 2):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")
    print("------")

集合:列表与集合

列表操作与切片

# 列表推导式
squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]
 
# 切片
my_list = [0, 1, 2, 3, 4]
print(my_list[1:4])   # [1, 2, 3](索引 1 到 3)
print(my_list[::-1])  # [4, 3, 2, 1, 0](反转)

集合操作

my_set = {1, 'Hello', 2, 2}  # {1, 'Hello', 2}(唯一元素)
 
# 转换为列表以支持索引访问
my_list = list(my_set)
print(my_list[0])  # 输出不定(顺序不保证)
 
# 遍历集合
for item in my_set:
    print(item)
 
# 检查成员关系
if 'Hello' in my_set:
    print("Found 'Hello'!")
 
# 移除并返回任意元素
element = my_set.pop()
print(element)

函数与类

函数

用户自定义函数是由程序员定义的代码块,有助于将大型程序分解为更易于管理的逻辑单元。

# 两数相加函数
def add(x, y):
    return x + y
 
result = add(5, 3)
print("5 + 3 =", result)  # 8
 
# 带默认参数的函数
def greet(name="Guest"):
    print("Hello,", name)
 
greet("Alice")  # Hello, Alice
greet()         # Hello, Guest

类是 Python 中面向对象编程(OOP)的基础构建块。

class Dog:
    def __init__(self, name, age):
        self.name = name  # 构造函数初始化实例属性
        self.age = age
 
    def bark(self):
        print(f"{self.name} says woof!")
 
# 创建对象/实例
my_dog = Dog('XiaoHuang', 2)
print('my dog name is', my_dog.name)   # my dog name is XiaoHuang
print('my dog age is', my_dog.age)     # my dog age is 2
my_dog.bark()  # Output: XiaoHuang says woof!

文件读写

写入与读取文件

# 写入文件
with open("file.txt", "w") as f:
    f.write("Hello, Python!")
 
# 读取文件
with open("file.txt", "r") as f:
    content = f.read()  # "Hello, Python!"
print(type(content), content)

用户输入

nam = input('what is your name?')
print('Welcome', nam)  # Welcome <你的输入>

字符串格式化

# f-strings(Python 3.6+)
name = "Alice"
print(f"Hello, {name}!")  # Hello, Alice!
num = 2
print(f'Hello,{name}! num={num}#')
 
# .format() 方法
print("Value: {}".format(10))  # Value: 10
 
# 简单拼接
print('value:', name, '!', 'key:', num)  # value: Alice ! key: 2

注释

# 单行注释
 
"""
多行注释
使用三引号(也用于文档字符串)。
"""

Tip

在大多数 IDE 中,可以选中代码行后按 Ctrl + / 快速切换注释。

迷你项目:猜数字游戏

一个结合了变量、循环、条件判断和用户输入的完整示例:

import random
 
secret_number = random.randint(1, 5)
attempts = 3
 
while attempts > 0:
    guess = int(input("Guess a number (1-5): "))
    if guess == secret_number:
        print("You won!")
        break
    else:
        attempts -= 1
        print(f"Wrong! {attempts} attempts left.")
else:
    print(f"Game over! The number was {secret_number}.")

要点总结

主题关键内容
变量动态类型、= 赋值、命名规则
数据类型数值、文本、布尔、序列、映射、集合、NoneType
运算符算术、比较、逻辑;math 模块
控制流if/elif/elseforwhilecontinuebreak
集合列表(可变有序)、集合(唯一无序)、元组(不可变)
函数def、参数、默认值、返回值
class__init__、方法、实例
文件读写open()with 语句、read()write()

相关概念

来源资料