Java和Python语法对照
Java和Python是两种不同的编程语言,它们的语法结构也有所不同。下面是Java和Python的一些语法对照:
- 变量声明和赋值:
Java:
int a = 5;
String s = "Hello";
Python:
a = 5
s = "Hello"
- 控制流语句:
Java:
if (condition) {
//执行语句
} else if (condition) {
//执行语句
} else {
//执行语句
}
for (int i = 0; i < 10; i++) {
//执行语句
}
while (condition) {
//执行语句
}
do {
//执行语句
} while (condition);
Python:
if condition:
#执行语句
elif condition:
#执行语句
else:
#执行语句
for i in range(10):
#执行语句
while condition:
#执行语句
while True:
#执行语句
if condition:
break
- 函数定义和调用:
Java:
public int add(int a, int b) {
return a + b;
}
int result = add(2, 3);
Python:
def add(a, b):
return a + b
result = add(2, 3)
- 类定义和对象创建:
Java:
class MyClass {
int value;
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
MyClass obj = new MyClass(10);
int value = obj.getValue();
Python:
class MyClass:
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
obj = MyClass(10)
value = obj.get_value()
需要注意的是,Java使用大括号表示代码块,而Python使用缩进。此外,Java的变量类型需要在声明时指定,而Python是动态类型语言,不需要声明变量类型。
原文地址: https://www.cveoy.top/t/topic/bKTr 著作权归作者所有。请勿转载和采集!