前言

如果你已经学过 Java 或 C++,那么学习 Python 会非常快。

因为变量、条件判断、循环、函数、类、异常这些基础概念你已经掌握了。学习 Python 时,你真正需要适应的是它的语法习惯和编程风格。

Python 和 Java/C++ 最大的不同主要有以下几点:

  • Python 不需要显式声明变量类型
  • Python 使用缩进表示代码块
  • Python 的内置数据结构非常强大
  • Python 代码通常更加简洁
  • Python 更适合快速开发、脚本编写、数据处理和人工智能相关应用

本文会从 Java/C++ 程序员的角度,带你快速掌握 Python 基础。


一、Python 和 Java/C++ 的核心区别

Python 是一种动态类型语言。

在 Java 或 C++ 中,变量通常需要先声明类型。

int x = 10;
String name = "Alice";

而 Python 中可以直接赋值。

x = 10
name = "Alice"

Python 会根据赋值内容自动判断变量类型。

x = 10
print(type(x))  # <class 'int'>

x = "hello"
print(type(x))  # <class 'str'>

也就是说,同一个变量名可以先指向整数,再指向字符串。

但是需要注意,Python 不是弱类型语言。它是动态类型语言,但依然是强类型语言。

x = 10
s = "hello"

# print(x + s)  # 报错,int 不能直接和 str 相加

如果想拼接,需要显式转换类型。

x = 10
s = "hello"

print(str(x) + s)

二、Python 基本语法

1. 输出

print("Hello Python")

2. 变量

name = "Alice"
age = 20
height = 1.68
is_student = True

Python 中的布尔值是:

True
False

注意首字母要大写,不是 Java/C++ 中的 true 和 false。

3. 空值

Python 中的空值是:

None

它类似于 Java 中的 null,也类似于 C++ 中的 nullptr。


三、缩进就是代码块

Python 不使用 {} 表示代码块,而是使用缩进。

age = 18

if age >= 18:
    print("成年人")
else:
    print("未成年人")

在 Java/C++ 中通常写成:

if (age >= 18) {
    cout << "成年人";
} else {
    cout << "未成年人";
}

Python 中推荐统一使用 4 个空格缩进。

缩进不一致会直接报错。

if True:
    print("hello")
    print("python")

下面这种写法会报错:

if True:
    print("hello")
  print("python")  # 缩进错误

四、条件判断

Python 的条件判断写法如下:

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 60:
    print("C")
else:
    print("D")

Python 中没有 else if,而是使用:

elif

逻辑运算符

Python 的逻辑运算符和 Java/C++ 不同。

Java/C++ 的 && 对应 Python 的 and

Java/C++ 的 || 对应 Python 的 or

Java/C++ 的 ! 对应 Python 的 not

示例:

age = 20
has_id = True

if age >= 18 and has_id:
    print("可以进入")

再看一个例子:

is_vip = False
has_ticket = True

if is_vip or has_ticket:
    print("可以入场")
else:
    print("不能入场")

使用 not:

is_empty = False

if not is_empty:
    print("不是空的")

五、循环

1. for 循环

Python 的 for 循环更像 Java 中的增强 for 循环。

for i in range(5):
    print(i)

输出结果:

0
1
2
3
4

range(5) 表示生成从 0 到 4 的数字。

也可以指定起点和终点。

for i in range(1, 6):
    print(i)

输出结果:

1
2
3
4
5

还可以指定步长。

for i in range(1, 10, 2):
    print(i)

输出结果:

1
3
5
7
9

2. while 循环

i = 0

while i < 5:
    print(i)
    i += 1

3. break 和 continue

break 用于提前结束循环。

for i in range(10):
    if i == 5:
        break
    print(i)

continue 用于跳过本轮循环。

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

六、字符串

Python 的字符串操作非常方便。

name = "Alice"
age = 20

print("My name is " + name)
print(f"My name is {name}, age is {age}")

推荐使用 f-string 格式化字符串。

score = 95
print(f"Your score is {score}")

常见字符串操作

s = "hello python"

print(s.upper())        # HELLO PYTHON
print(s.lower())        # hello python
print(s.capitalize())   # Hello python
print(s.replace("python", "java"))
print(s.split())        # ['hello', 'python']
print(len(s))           # 字符串长度

字符串索引和切片

s = "python"

print(s[0])     # p
print(s[-1])    # n
print(s[0:3])   # pyt
print(s[2:])    # thon
print(s[:4])    # pyth

切片格式:

字符串[起始位置:结束位置]

注意:结束位置不包含在结果中。


七、列表 list

Python 的 list 类似 Java 中的 ArrayList,也类似 C++ 中的 vector。

nums = [1, 2, 3, 4]

print(nums[0])   # 1
print(nums[-1])  # 4

常用操作

nums = [1, 2, 3, 4]

nums.append(5)      # 末尾添加
nums.insert(0, 99)  # 指定位置插入
nums.remove(3)      # 删除值为 3 的元素
last = nums.pop()   # 删除并返回最后一个元素

print(nums)
print(len(nums))

遍历列表

nums = [10, 20, 30]

for x in nums:
    print(x)

带下标遍历:

nums = [10, 20, 30]

for i, x in enumerate(nums):
    print(i, x)

列表切片

nums = [10, 20, 30, 40, 50]

print(nums[1:4])    # [20, 30, 40]
print(nums[:3])     # [10, 20, 30]
print(nums[2:])     # [30, 40, 50]
print(nums[::-1])   # 反转列表

排序

nums = [3, 1, 4, 2]

nums.sort()
print(nums)

降序排序:

nums.sort(reverse=True)
print(nums)

如果不想改变原列表,可以使用 sorted()。

nums = [3, 1, 4, 2]

new_nums = sorted(nums)

print(nums)
print(new_nums)

八、元组 tuple

元组类似于不可修改的列表。

point = (3, 4)

print(point[0])
print(point[1])

元组不能修改。

point = (3, 4)

# point[0] = 10  # 报错

元组常用于函数返回多个值。

def get_point():
    return 3, 4

x, y = get_point()

print(x)
print(y)

九、字典 dict

Python 的 dict 类似 Java 中的 HashMap,也类似 C++ 中的 unordered_map。

student = {
    "name": "Alice",
    "age": 20,
    "score": 95
}

print(student["name"])
print(student["age"])

修改和新增

student["age"] = 21
student["city"] = "Beijing"

print(student)

安全获取

print(student.get("name"))          # Alice
print(student.get("height"))        # None
print(student.get("height", 0))     # 0

使用 get() 的好处是,如果 key 不存在,不会直接报错。

遍历字典

遍历 key:

for key in student:
    print(key)

遍历 value:

for value in student.values():
    print(value)

遍历 key-value:

for key, value in student.items():
    print(key, value)

判断 key 是否存在:

if "name" in student:
    print("has name")

十、集合 set

Python 的 set 类似 Java 中的 HashSet,也类似 C++ 中的 unordered_set。

s = {1, 2, 3, 3, 3}

print(s)  # {1, 2, 3}

集合会自动去重。

常用操作

s = {1, 2, 3}

s.add(4)
s.remove(2)

print(s)
print(3 in s)

集合运算

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)  # 并集
print(a & b)  # 交集
print(a - b)  # 差集

十一、函数

Python 使用 def 定义函数。

def add(a, b):
    return a + b

result = add(3, 5)
print(result)

默认参数

def greet(name, message="Hello"):
    print(f"{message}, {name}")

greet("Alice")
greet("Bob", "Hi")

关键字参数

def greet(name, message="Hello"):
    print(f"{message}, {name}")

greet(name="Alice", message="Good morning")

返回多个值

def calculate(a, b):
    return a + b, a * b

sum_result, product = calculate(3, 4)

print(sum_result)
print(product)

十二、类型标注

Python 可以写类型提示。

def add(a: int, b: int) -> int:
    return a + b

类型标注可以提高代码可读性,也方便 IDE 提示和静态检查。

但是需要注意,Python 的类型标注默认不会在运行时强制检查。

def add(a: int, b: int) -> int:
    return a + b

print(add("hello", "world"))

这段代码仍然可以运行,输出结果是:

helloworld

十三、列表推导式

列表推导式是 Python 中非常常用的写法。

普通写法:

nums = [1, 2, 3, 4, 5]
squares = []

for x in nums:
    squares.append(x * x)

print(squares)

Pythonic 写法:

nums = [1, 2, 3, 4, 5]

squares = [x * x for x in nums]

print(squares)

带条件的写法:

nums = [1, 2, 3, 4, 5]

evens = [x for x in nums if x % 2 == 0]

print(evens)

字典推导式:

nums = [1, 2, 3]

square_map = {x: x * x for x in nums}

print(square_map)

十四、lambda 表达式

Python 中的 lambda 类似匿名函数。

add = lambda a, b: a + b

print(add(3, 5))

它常用于排序。

students = [
    {"name": "Alice", "score": 90},
    {"name": "Bob", "score": 75},
    {"name": "Charlie", "score": 85}
]

students.sort(key=lambda x: x["score"])

print(students)

按分数降序排序:

students.sort(key=lambda x: x["score"], reverse=True)

十五、类和对象

Python 也支持面向对象编程。

class 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.")


s = Student("Alice", 20)
s.introduce()

这里的 self 类似 Java/C++ 中的 this,但是 Python 中必须显式写出来。

继承

class Person:
    def __init__(self, name):
        self.name = name

    def say_hi(self):
        print(f"Hi, I am {self.name}")


class Student(Person):
    def __init__(self, name, score):
        super().__init__(name)
        self.score = score

    def show_score(self):
        print(f"{self.name}'s score is {self.score}")


s = Student("Alice", 95)
s.say_hi()
s.show_score()

十六、异常处理

Python 使用 try-except 处理异常。

try:
    x = int(input("Enter a number: "))
    print(10 / x)
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("Done")

主动抛出异常:

raise ValueError("Invalid value")

十七、文件操作

读取文件

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

print(content)

逐行读取

with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

写文件

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
    f.write("python\n")

追加写入

with open("output.txt", "a", encoding="utf-8") as f:
    f.write("new line\n")

with 会自动关闭文件,类似 Java 中的 try-with-resources。


十八、模块和包

导入模块

import math

print(math.sqrt(16))

只导入某个函数

from math import sqrt

print(sqrt(16))

起别名

import numpy as np

自定义模块

假设我们有一个 utils.py 文件:

def add(a, b):
    return a + b

在另一个文件中使用:

from utils import add

print(add(3, 5))

十九、Python 主函数写法

Python 程序中常见的主函数写法如下:

def main():
    print("Program starts")


if __name__ == "__main__":
    main()

这表示:只有当前文件被直接运行时,才执行 main()。

如果这个文件被其他文件导入,main() 不会自动执行。


二十、Java/C++ 程序员容易踩的坑

1. 赋值不是拷贝

a = [1, 2, 3]
b = a

b.append(4)

print(a)  # [1, 2, 3, 4]

这里 a 和 b 指向的是同一个列表。

如果想复制列表,可以写:

b = a.copy()

或者:

b = a[:]

2. 可变默认参数陷阱

不要这样写:

def add_item(x, arr=[]):
    arr.append(x)
    return arr

应该这样写:

def add_item(x, arr=None):
    if arr is None:
        arr = []
    arr.append(x)
    return arr

3. is 和 == 不一样

a == b  # 判断值是否相等
a is b  # 判断是否是同一个对象

通常比较值用 ==。

判断是否为 None 时,用 is。

if x is None:
    print("x is None")

4. 整数除法

print(5 / 2)   # 2.5
print(5 // 2)  # 2
print(5 % 2)   # 1

/ 是普通除法,// 是整除。


二十一、完整小案例:学生成绩管理

下面这个例子综合使用了类、函数、列表、循环、条件判断和类型标注。

class Student:
    def __init__(self, name: str, score: int):
        self.name = name
        self.score = score

    def is_passed(self) -> bool:
        return self.score >= 60


def print_students(students):
    for student in students:
        status = "passed" if student.is_passed() else "failed"
        print(f"{student.name}: {student.score}, {status}")


def average_score(students):
    if not students:
        return 0

    total = 0
    for student in students:
        total += student.score

    return total / len(students)


def main():
    students = [
        Student("Alice", 90),
        Student("Bob", 55),
        Student("Charlie", 78)
    ]

    print_students(students)

    avg = average_score(students)
    print(f"Average score: {avg:.2f}")


if __name__ == "__main__":
    main()

运行结果:

Alice: 90, passed
Bob: 55, failed
Charlie: 78, passed
Average score: 74.33

二十二、练习题

练习 1:统计列表中的偶数个数

要求:

def count_even(nums):
    pass

示例:

print(count_even([1, 2, 3, 4, 5, 6]))  # 3

参考答案:

def count_even(nums):
    count = 0

    for x in nums:
        if x % 2 == 0:
            count += 1

    return count

更 Pythonic 的写法:

def count_even(nums):
    return len([x for x in nums if x % 2 == 0])

练习 2:统计单词出现次数

text = "java python c++ python java python"

目标输出:

{
    "java": 2,
    "python": 3,
    "c++": 1
}

参考答案:

def word_count(text):
    words = text.split()
    result = {}

    for word in words:
        result[word] = result.get(word, 0) + 1

    return result


text = "java python c++ python java python"
print(word_count(text))

练习 3:找最高分学生

students = [
    {"name": "Alice", "score": 90},
    {"name": "Bob", "score": 75},
    {"name": "Charlie", "score": 95}
]

参考答案:

def get_top_student(students):
    return max(students, key=lambda x: x["score"])


top = get_top_student(students)
print(top["name"], top["score"])

练习 4:实现一个 BankAccount 类

要求:

account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
print(account.balance)  # 1300

参考答案:

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        if amount > self.balance:
            raise ValueError("not enough balance")
        self.balance -= amount


account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)

print(account.balance)

练习 5:读取文件并统计行数

要求:

def count_lines(filename):
    pass

参考答案:

def count_lines(filename):
    count = 0

    with open(filename, "r", encoding="utf-8") as f:
        for line in f:
            count += 1

    return count

二十三、Python 入门路线建议

如果你已经会 Java 或 C++,可以按照下面这个顺序学习 Python。

第一天:变量、条件判断、循环、字符串、列表、字典

第二天:函数、类型标注、列表推导式、lambda

第三天:类、继承、异常处理、文件操作

第四天:刷一些基础算法题,熟悉 Python 容器

第五天:做一个小项目,比如通讯录、记账本、待办事项工具、简单爬虫等


总结

对于有 Java/C++ 基础的人来说,Python 的入门难度并不高。

你真正需要适应的是:

  • 不需要显式声明类型
  • 用缩进代替大括号
  • 多使用 list、dict、set 等内置容器
  • 多使用 Python 自带库
  • 代码尽量写得简洁、清晰、可读

掌握以下内容,就可以开始写大多数 Python 基础程序:

变量
if / elif / else
for / while
list / tuple / dict / set
函数 def
类 class
异常 try / except
文件 open
模块 import
列表推导式
lambda
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐