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

7.1 KiB
Raw Blame History

Why Python

1. 语法简单

  • Python

    print('Hello world')
    
  • C++

    #include<iostream>
    using namespace std;
    int main(){
        cout << "Hello world!" << endl;
        return 0;
    }
    
  • Java

    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello, World!");
        }
    }
    

2. 通过缩进和冒号来划分代码块 而不是分号和大括号

  • Python:

    def division(a, b):
    	  if b == 0:
            print('ERROR!')
        else:
            print(a / b)
    
  • 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:

      a = '1'  # a为str类型
      b = '2'  # b为str类型
      b = 3  # b可以被直接修改为int类型
      
      print(a+b)  # 报错不同数据类型之间不能运算说明python是强类型的
      
      # 函数定义也不需要声明返回值和参数的类型
      def plus(a, b):
          return a+b
      
    • 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的基础数据类型

注意:基础数据类型均为保留关键字,不要这些关键字作为变量名!

x = 1  # 合理
int = 1  # 不合理

1. 整数类型(int

用于表示整数,正数、负数或零。

x = 42
print(type(x))  # 输出: <class 'int'>

2. 浮点数类型(float

用于表示带小数的数值。

y = 3.14
print(type(y))  # 输出: <class 'float'>

3. 布尔类型(bool

表示逻辑上的真 (True) 或假 (False) 值。

is_true = True
print(type(is_true))  # 输出: <class 'bool'>

4. 列表类型(list

有序、可变的元素集合,可以包含不同类型的元素。

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

表示文本数据,本质上是由字符组成的数组所以数组相关的操作都能对字符串做

name = "Python"
name = 'Python'  # 单引号和双引号在python里都表示字符串没有任何区别
print(type(name))  # 输出: <class 'str'>
print(name[0])  # 输出: 'P'
print(name[-1])  # 输出: 'n'

6. 元组类型(tuple

有序的不可变元素集合,类似于列表,但元组一旦创建就不能修改。

my_tuple = (1, 2, 3)
print(type(my_tuple))  # 输出: <class 'tuple'>

7. 集合类型(set

无序、不重复元素的集合。

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

键-值对的无序集合,且键不可重复。类似于哈希表。

my_dict = {"name": "Alice", "age": 25}
print(type(my_dict))  # 输出: <class 'dict'>

9. None 类型

表示“无”或“空”的特殊类型。

z = None
print(type(z))  # 输出: <class 'NoneType'> 类似null

条件控制语句

1. 任何版本都通用if语句

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语句

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.")