常用编程语言基础语法对比
kecho

本文将对 Java、Go、Python 等编程语言的基础语法进行对比。

导入包

Java
Go
Python
1
2
3
package com.example.main;
import com.example.myapp.MyClass;
import com.example.main.TestClass;
1
2
3
4
5
6
7
package main
import (
"fmt"
"foo/bar" // 导入本地包
myBar "foo/bar" // 别名
"github.com/username/myproject/foo" // 导入三方包
)
1
2
3
4
5
import module_name_1
import module_name_2 as alias
from module_name_3 import class_name, func_name
from module_name_4 import * # 导入所有内容
module = __import__('module_name_5') # 动态导入

控制结构

Java
Go
Python

if 结构

1
2
3
4
5
6
7
if ( condition1 ) {
// ...
} else if ( condition2 ) {
// ...
} else {
// ...
}

switch 结构,多行语句不需要花括号但需要手动写 break;

1
2
3
4
5
6
7
8
9
10
11
switch ( val ) {
case val1:
// ...
// ...
break;
case val2:
// ...
break;
default:
// ...
}

循环结构

1
2
3
4
5
6
7
8
9
10
11
for ( int i = 0; i < 10; i++ ) {
count++;
}

while ( condition ) {
// ...
}

do {
// ...
} while ( condition );

不需要小括号

if 结构

1
2
3
4
5
6
7
if condition1 {
// ...
} else if condition2 {
// ...
} else {
// ...
}

switch 结构,多行语句不需要花括号且不需要手动写 break;

1
2
3
4
5
6
7
8
9
switch val {
case val1:
// ...
// ...
case val2:
// ...
default:
// ...
}

循环结构,没有 while 关键字但有 for - range 结构

1
2
3
4
5
6
7
8
9
10
11
for i := 0; i < 10; i++ {
// ...
}

for condition {
// ...
}

for pos, char := range myStr {
// ...
}

需要冒号,不需要花括号,小括号可省略,

if 结构

1
2
3
4
5
6
7
8
if condition1:
# ...
elif condition2:
# ...
elif condition3:
# ...
else:
# ...

没有 switch 结构,可以使用 and 或 or 来组合多个条件

1
2
3
4
if condition1 or condition2:
# ...
else:
# ...

循环结构

1
2
3
4
5
6
7
8
for i in range(10):
# ...

for letter in 'Python':
print("当前字母: %s" % letter)

while condition:
# ...