01 | Java工程师的Python第一课:语法对比速查

6 阅读7分钟

从Java到Python:一张表格搞定语法转换

摘要:作为一名Java工程师,学习Python的第一步是建立两种语言的对照认知。本文通过详细对比表格、实战案例和避坑指南,帮助你快速完成从Java到Python的思维转变,一天内就能写出地道的Python代码。


写在前面

如果你已经习惯了Java的严谨和类型安全,刚开始接触Python时可能会有些不适应。没有分号、没有大括号、没有类型声明……Python的代码看起来"太随意"了。

但实际上,Python的简洁背后有着一套完整的哲学——"简洁胜于复杂"。当你习惯了这种风格后,会发现自己能用更少的代码完成更多的事情。

这篇文章是为Java工程师准备的Python入门速查表,通过对比两种语言的语法差异,帮你快速建立Python的编程思维。


一、基础语法对比

先来看看最基本的语法差异,这是你每天都会用到的东西:

功能JavaPython说明
变量声明int x = 5;x = 5动态类型,无需声明
常量final int MAX = 100;MAX = 100约定大写,无强制
字符串String s = "hello";s = "hello"单引号/双引号通用
拼接"Hello " + namef"Hello {name}"f-string最简洁
除法/ 返回int/float/ 总是float, // 整除Python不同
幂运算**Python独有,优先级最高
函数public int add(int a, int b)def add(a, b):无需修饰符、类型
public class Person { }class Person:无需public
继承class Dog extends Animalclass Dog(Animal):圆括号而非extends
条件if (x > 5) { }if x > 5:无需括号,缩进必须
else ifelse if (x == 5)elif x == 5:Python用elif
for循环for (int i = 0; i < 5; i++)for i in range(5):Python无C风格for
while循环while (condition) {}while condition:两者基本一致
遍历for (Item i : items)for i in items:Python更简洁
nullnullNonePython用None
布尔true/falseTrue/False首字母大写
逻辑与&&andPython用英文单词
逻辑或||orPython用英文单词
逻辑非!xnot xPython用not关键字
注释// comment /* */# commentPython无块注释
三元运算符a > b ? a : ba if a > b else b顺序相反
switch匹配switch(x) { case 1: }match x: case 1:Python 3.10+
pass空语句{} 内可为空pass占位符必须
lambda(a, b) -> a + blambda a, b: a + b匿名函数
类型检查obj instanceof Stringisinstance(obj, str)函数调用形式
异常处理try {} catch {}try: except:顺序:try-except

⚠️ 最重要的差异:缩进即语义

Java用大括号 {} 来界定代码块,而Python用缩进。这不仅是风格问题,而是语法要求:

# Java
if (x > 5) {
    System.out.println("five");
}

# Python
if x > 5:
    print("five")  # 缩进必须一致,通常用4个空格

📌 for循环与range()函数详解

Python 没有传统 C 风格的 for 循环,而是使用 range() 函数配合 for

# 常见的 range() 用法

# Java: for (int i = 0; i < 5; i++)
for i in range(5):          # 0, 1, 2, 3, 4

# Java: for (int i = 1; i <= 10; i++)
for i in range(1, 11):      # 1, 2, 3, ..., 10

# Java: for (int i = 1; i < 10; i += 2)
for i in range(1, 10, 2):   # 1, 3, 5, 7, 9 (从1开始,间隔2)

# Java: for (int i = 10; i > 0; i--)
for i in range(10, 0, -1):  # 10, 9, 8, ..., 1 (倒序)
range() 参数说明示例输出
range(stop)从0开始,到stop(不包含)range(5)0,1,2,3,4
range(start, stop)从start开始,到stop(不包含)range(2, 5)2,3,4
range(start, stop, step)从start开始,步长为steprange(1, 10, 2)1,3,5,7,9

📌 while循环详解

Python 的 while 循环与 Java 类似,但没有 do-while 语法。

# Java: while循环
while (count < 5) {
    System.out.println(count);
    count++;
}

# Python: 完全一致
while count < 5:
    print(count)
    count += 1
⚠️ Python没有 do-while

如果需要至少执行一次的循环,用 while True + break

# Java: do-while
// do {
//     System.out.println(x);
//     x--;
// } while (x > 0);

# Python: 用 while True + break 实现
while True:
    print(x)
    x -= 1
    if x <= 0:
        break
while...else

Python 独有的语法:循环正常结束(未被 break)时执行 else 块:

count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("循环正常结束")  # 当 count >= 3 时执行

二、集合操作对比

集合操作是日常开发中用得最多的,看看Python有多简洁:

操作JavaPython说明
创建Listnew ArrayList<>()[]Python简洁
添加list.add(1)list.append(1)方法名不同
移除list.remove(0)list.pop(0)功能相似
获取list.get(0)list[0]Python用下标
长度list.size()len(list)Python内置函数
创建Mapnew HashMap<>(){}字典更简洁
访问map.get("key")map["key"]下标访问
遍历map.entrySet()map.items()Python更自然
Filter.filter(x -> x>1)[x for x in l if x>1]推导式最优雅
Map.map(x -> x*2)[x*2 for x in l]推导式最优雅

实战对比:

# Java: Stream操作
result = list.stream()
              .map(x -> x * 2)
              .filter(x -> x > 10)
              .collect(Collectors.toList());

# Python: 列表推导式(一行搞定!)
result = [x * 2 for x in list if x > 10]

三、关键概念映射

这些概念差异需要特别注意:

Java概念Python等价差异
public/private/protected___ 前缀约定Python无强制访问控制
{} 代码块缩进(必须)关键差异:缩进即语义
Checked Exceptiontry/except(都是可选)Python异常处理更灵活
@Override无需(自动覆盖)Python更简洁但可能出错
thisself(显式)Python的self必须显式写出
Static 方法@staticmethod需要装饰器标记
Getter/Setter@property 装饰器Python提供更优雅的方式
InterfaceABC(抽象基类)+ @abstractmethodPython鸭式类型更灵活
EnumenumPython可用Enum
Generics <T>无(鸭式类型)Python运行时不强制类型

四、常用函数对照

JavaPython说明
System.out.println()print()打印到标准输出
String.format()f"string".format()f-string最推荐
Integer.parseInt()int()类型转换
Math.max()max()Python内置函数
Arrays.sort()sorted()排序函数
Optional<T>x if x else NonePython无Optional
HashMap.getOrDefault()dict.get(key, default)获取带默认值
instanceofisinstance()类型检查
new Thread()threading.Thread()并发编程

五、Python的优势在哪里

当你习惯了Java的繁琐,会发现Python有很多让你爱不释手的地方:

1️⃣ 列表推导式 vs Stream

# Java: 多行链式调用
List<Integer> result = numbers.stream()
    .filter(x -> x > 0)
    .map(x -> x * 2)
    .collect(Collectors.toList());

# Python: 一行搞定
result = [x * 2 for x in numbers if x > 0]

2️⃣ 多值返回(无需包装类)

# Java: 需要定义Pair/Triple类
return new Pair<>(x, y);

# Python: 直接返回元组
return x, y  # 调用者 x, y = func()

3️⃣ 默认参数(无需重载)

# Java: 需要多个构造函数或方法重载
public User(String name) { this(name, 18); }
public User(String name, int age) { ... }

# Python: 一行搞定
def create_user(name, age=18):
    pass

4️⃣ 字典/集合字面量

# Python: 初始化超级简洁
users = {"张三": 25, "李四": 30}
ids = {1, 2, 3, 4}

5️⃣ f-string 字符串格式化

# Java: 多种方式都比较冗长
String msg = "User " + name + " is " + age + " years old";
// 或 String.format("User %s is %d years old", name, age);

# Python: f-string 一行搞定
message = f"User {name} is {age} years old"

六、常见坑点与避坑指南

以下这些坑,几乎每个Java转Python的人都会踩一遍:

❌ 坑1:缩进错误(不能混合空格和制表符)

# 错误!混合了制表符和空格
if x > 5:
  print("five")

# 正确:统一用4个空格
if x > 5:
    print("five")

❌ 坑2:忘记冒号

# 错误!缺少冒号
if x > 5
    print("five")

# 正确
if x > 5:
    print("five")

❌ 坑3:列表/字典初始化的引用问题

# 错误!所有行都指向同一个列表
matrix = [[0]*3]*3

# 正确:创建独立的行
matrix = [[0]*3 for _ in range(3)]

❌ 坑4:全局变量修改

x = 5

def modify():
    x = 10  # 这是赋值给局部变量,不修改全局x

modify()
print(x)  # 仍然是5!

# 正确做法
def modify_correct():
    global x
    x = 10

❌ 坑5:可变默认参数

# 危险!list会被重用
def add_item(item, list=[]):
    list.append(item)
    return list

add_item(1)  # [1]
add_item(2)  # [1, 2] 出乎意料!

# 正确做法
def add_item(item, list=None):
    if list is None:
        list = []
    list.append(item)
    return list


七、常见误区总结

误区正确做法解释
if x == True:if x:Python中True/False是特殊值
if len(list) > 0:if list:空list是False,非空是True
if x != None:if x is not None:is而非==检查None
传递可变对象默认参数用None替代默认参数在函数定义时初始化,会被重用
修改循环中的列表迭代副本for item in list[:]:
except: 不指定异常类型except Exception as e:不要捕获所有异常
混用空格和制表符统一用4个空格Python严格要求缩进一致

八、总结与下期预告

本篇回顾

本文通过对比表格、实战案例和避坑指南,帮助Java工程师快速建立Python编程思维:

  • ✅ 基础语法对比:缩进即语义、无需类型声明

  • ✅ 集合操作:列表推导式比Stream更简洁

  • ✅ 关键概念映射:理解Java到Python的思维转变

  • ✅ 常见坑点:可变默认参数、缩进错误、全局变量

本文首发于掘金,转载请注明出处。