Files
Python-Notes/Note.md
2024-10-21 15:27:54 +08:00

247 lines
7.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Why Python
## 1. 语法简单
- Python
```python
print('Hello world')
```
- C++
```c
#include<iostream>
using namespace std;
int main(){
cout << "Hello world!" << endl;
return 0;
}
```
- Java
```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
## 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不需要在运行前编译成机器码代码可以直接由解释器**逐行翻译并执行**。
- 简单说就是写好的代码可以直接运行。比如一个代码文件test.py直接通过`python test.py`就能运行这段代码
**编译型语言**C++、Java在运行前需要将源代码编译成机器码或字节码**生成可执行文件用来执行**。
- 写好的代码不能直接运行要先变成可执行文件才能运行。比如一个文件test.java或test.cpp
- Java通过`javac test.java`生成一个test.class的字节码之后使用`java test.class`来执行这个字节码,才能运行代码
- C++:通过`g++ test.cpp`生成一个可执行文件test.exe (Windows系统)或test (Linux系统),之后执行这个文件来运行代码
**实际使用中的区别**
- Python相比Java和C++,通常**运行速度比较慢**,但是**好处是修改代码后可以立即看到变化**,不需要改一次编译一次。个别大型项目,编译一次需要几个小时。
- Python不需要显式的指定变量和函数的类型
- Python:
```python
a = '1' # a为str类型
b = '2' # b为str类型
b = 3 # b可以被直接修改为int类型
print(a+b) # 报错不同数据类型之间不能运算说明python是强类型的
# 函数定义也不需要声明返回值和参数的类型
def plus(a, b):
return a+b
```
- C++
```c
char a = '1'; // a为str类型
char b = '2'; // b为str类型
b = 3; // 报错b已经被声明为char就不能用int对他赋值
int b = 3; // 这样是可以的,因为重新声明了变量类型
cout << a+b; // 报错不同数据类型之间不能运算说明C++也是强类型的
// 函数定义必须声明返回值和参数的类型
int plus(int a, int b){
return a+b;
}
```
出现这个现象的原因是Python**逐行翻译并执行**,每一行的内容会依次生效,变量的内存空间是**实时分配的**。而C++等语言需要提前编译,编译的过程中为每一个变量**预先分配了内存**,而不同类型的变量在内存中占用的大小不一致,因此不能通过赋值修改变量类型。
# Python的基础数据类型
**注意:基础数据类型均为保留关键字,不要这些关键字作为变量名!**
```python
x = 1 # 合理
int = 1 # 不合理
```
## 1. **整数类型(`int`**
用于表示整数,正数、负数或零。
```python
x = 42
print(type(x)) # 输出: <class 'int'>
```
## 2. **浮点数类型(`float`**
用于表示带小数的数值。
```python
y = 3.14
print(type(y)) # 输出: <class 'float'>
```
## 3. **布尔类型(`bool`**
表示逻辑上的真 (`True`) 或假 (`False`) 值。
```python
is_true = True
print(type(is_true)) # 输出: <class 'bool'>
```
## 4. **列表类型(`list`**
有序、可变的元素集合,可以包含不同类型的元素。
```python
my_list = [1, 2, 3, "hello"]
print(type(my_list)) # 输出: <class 'list'>
# 访问元素
print(my_list[0]) # 输出: 1
print(my_list[-1]) # 输出: "hello"
print(my_list[0:2]) # 输出: [1, 2],要头不要尾
# 修改元素
my_list[0] = 'modified' # ['modified', 2, 3, "hello"]
# 添加元素
my_list.append('append') # ['modified', 2, 3, "hello", 'append']
my_list.insert(1, 'insert') # ['modified', 'insert', 2, 3, "hello", 4]
# 删除元素
my_list.remove('modified') # ['insert', 2, 3, "hello", 4]
my_list.pop(3) # ['insert', 2, 3, 4]
# 查找元素
my_list.index(2) # 输出1
my_list.index(9) # 直接抛异常
2 in my_list # 输出True
9 in my_list # 输出False
```
## 5. **字符串类型(`str`**
表示文本数据,**本质上是由字符组成的数组****所以数组相关的操作都能对字符串做**。
```python
name = "Python"
name = 'Python' # 单引号和双引号在python里都表示字符串没有任何区别
print(type(name)) # 输出: <class 'str'>
print(name[0]) # 输出: 'P'
print(name[-1]) # 输出: 'n'
```
## 6. **元组类型(`tuple`**
有序的不可变元素集合,类似于列表,但元组一旦创建就不能修改。
```python
my_tuple = (1, 2, 3)
print(type(my_tuple)) # 输出: <class 'tuple'>
```
## 7. **集合类型(`set`**
**无序、不重复**元素的集合。
```python
my_set = {'one', 'two', 'three', 'three', 'four'}
print(my_set) # 输出: {'one', 'two', 'three', 'four'} (集合会自动去重)
print(type(my_set)) # 输出: <class 'set'>
print(my_set[0]) # 直接报错:集合是无序的,不能按下标取值
print('two' in my_set) # 输出True。集合通常就是这么用的用来判断一个值在不在集合里。
```
## 8. **字典类型(`dict`**
键-值对的无序集合,且键不可重复。类似于哈希表。
```python
my_dict = {"name": "Alice", "age": 25}
print(type(my_dict)) # 输出: <class 'dict'>
```
## 9. **None 类型**
表示“无”或“空”的特殊类型。
```python
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.")
```