Update
This commit is contained in:
86
Note.md
86
Note.md
@@ -1,4 +1,4 @@
|
||||
# Python对比Java和C++
|
||||
# Why Python
|
||||
|
||||
## 1. 语法简单
|
||||
|
||||
@@ -26,7 +26,33 @@
|
||||
}
|
||||
```
|
||||
|
||||
## 2. 解释型语言 无需编译
|
||||
## 2. 通过缩进和冒号来划分代码块 而不是分号和大括号
|
||||
|
||||
- Python:
|
||||
```python
|
||||
def division(a, b):
|
||||
if b == 0:
|
||||
print('ERROR!')
|
||||
else:
|
||||
print(a / b)
|
||||
```
|
||||
|
||||
- C++:
|
||||
```c
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
void division(double a, double b) {
|
||||
if (b == 0) {
|
||||
cout << "ERROR!" << endl;
|
||||
} else {
|
||||
cout << a / b << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 3. 解释型语言 无需编译
|
||||
|
||||
**解释型语言**(Python)不需要在运行前编译成机器码,代码可以直接由解释器**逐行翻译并执行**。
|
||||
|
||||
@@ -42,7 +68,7 @@
|
||||
|
||||
- Python相比Java和C++,通常**运行速度比较慢**,但是**好处是修改代码后可以立即看到变化**,不需要改一次编译一次。个别大型项目,编译一次需要几个小时。
|
||||
|
||||
- Python不需要显式的指定变量的类型:
|
||||
- Python不需要显式的指定变量和函数的类型:
|
||||
|
||||
- Python:
|
||||
|
||||
@@ -52,6 +78,10 @@
|
||||
b = 3 # b可以被直接修改为int类型
|
||||
|
||||
print(a+b) # 报错:不同数据类型之间不能运算,说明python是强类型的
|
||||
|
||||
# 函数定义也不需要声明返回值和参数的类型
|
||||
def plus(a, b):
|
||||
return a+b
|
||||
```
|
||||
|
||||
- C++:
|
||||
@@ -61,7 +91,12 @@
|
||||
b = 3; // 报错:b已经被声明为char,就不能用int对他赋值
|
||||
|
||||
int b = 3; // 这样是可以的,因为重新声明了变量类型
|
||||
print(a+b) // 报错:不同数据类型之间不能运算,说明C++也是强类型的
|
||||
cout << a+b; // 报错:不同数据类型之间不能运算,说明C++也是强类型的
|
||||
|
||||
// 函数定义必须声明返回值和参数的类型
|
||||
int plus(int a, int b){
|
||||
return a+b;
|
||||
}
|
||||
```
|
||||
|
||||
出现这个现象的原因是Python**逐行翻译并执行**,每一行的内容会依次生效,变量的内存空间是**实时分配的**。而C++等语言需要提前编译,编译的过程中为每一个变量**预先分配了内存**,而不同类型的变量在内存中占用的大小不一致,因此不能通过赋值修改变量类型。
|
||||
@@ -166,3 +201,46 @@ print(type(my_dict)) # 输出: <class 'dict'>
|
||||
z = None
|
||||
print(type(z)) # 输出: <class 'NoneType'> 类似null
|
||||
```
|
||||
|
||||
# 条件控制语句
|
||||
|
||||
## 1. 任何版本都通用:if语句
|
||||
|
||||
```python
|
||||
def positive_or_negative(a, b):
|
||||
if a > 0:
|
||||
print("It's positive.")
|
||||
if a == 0:
|
||||
print("It's zero!")
|
||||
else:
|
||||
print("It's negative.")
|
||||
|
||||
# 下面是一段错误代码
|
||||
def describe_temperature(temp):
|
||||
if temp >= 30:
|
||||
print("It's a hot day!")
|
||||
if temp >= 20:
|
||||
print("It's a warm day.")
|
||||
if temp >= 10:
|
||||
print("It's a cool day.")
|
||||
else:
|
||||
print("It's a cold day.")
|
||||
```
|
||||
|
||||
## 2. Python 3.10+ 新特性:match-case语句
|
||||
|
||||
```python
|
||||
def fruit_description(fruit):
|
||||
match fruit:
|
||||
case "apple":
|
||||
print("This is a red or green fruit, usually sweet.")
|
||||
case "banana":
|
||||
print("This is a long, yellow fruit, and it is soft.")
|
||||
case "orange":
|
||||
print("This is a round orange fruit, and it is juicy")
|
||||
case "grape":
|
||||
print("This is a small fruit.")
|
||||
case _:
|
||||
print("I don't know this fruit.")
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user