Lazy loaded image
🐍Python 教程
一、Python 入门
Words 10979Read Time 28 min
2024-12-11
type
date
slug
category
icon
password

Build Python Develop Environment

Update software source

Linux software sources update

  1. sudo -i 获取root权限
  1. cp /etc/apt/sources.list /etc/apt/sources.list.old 备份软件源
  1. vim /etc/apt/sources.list 使用vim查看编辑管理源,输入 “i” 进入编辑模式
  1. 添加阿里云镜像管理源(其他镜像位置),ctrl+c /EsC中断编辑,:qa! 退出并去除所有修改,:wq 保存修改
  1. apt-get update 更改源
  1. apt-get upgrade 更新系统的软件和类库
 
 
VS Code Python Develop Environment
Q1. vs code add root path into python path, while ignoring sub-directory , therefore, you have to add subpath into python path when importing modules in the sub-directory
How To solve
方法1:
  1. if objective module included in current working directory, it can be imported by simply "from .. import ... ";
  1. if not, such as last level directory, you have add absolute path into sys.path using codes as follow。
Linux OS configurate python

install python3

virtual env configuration

Practice Sheet

Python Interview Questions
网上有网友搜集了 180 道 2019 年最新的 Python 面试题解析,让你最短时间内掌握核心知识点,一举通过Python 面试!
1.列出 5 个常用 Python 标准库?2.Python 内建数据类型有哪些?3.简述 with 方法打开处理文件帮我我们做了什么?4.列出 Python 中可变数据类型和不可变数据类型,为什么?5.Python 获取当前日期?6.统计字符串每个单词出现的次数7.用 python 删除文件和用 linux 命令删除文件方法8.写一段自定义异常代码9.举例说明异常模块中 try except else finally 的相关意义10.遇到 bug 如何处理

语言特性

1.谈谈对 Python 和其他语言的区别2.简述解释型和编译型编程语言3.Python 的解释器种类以及相关特点?4.说说你知道的Python3 和 Python2 之间的区别?5.Python3 和 Python2 中 int 和 long 区别?6.xrange 和 range 的区别?

编码规范

7.什么是 PEP8?8.了解 Python 之禅么?9.了解 docstring 么?10.了解类型注解么?11.例举你知道 Python 对象的命名规范,例如方法或者类等12.Python 中的注释有几种?13.如何优雅的给一个函数加注释?14.如何给变量加注释?15.Python 代码缩进中是否支持 Tab 键和空格混用。16.是否可以在一句 import 中导入多个库?17.在给 Py 文件命名的时候需要注意什么?18.例举几个规范 Python 代码风格的工具

数据类型

字符串

19.列举 Python 中的基本数据类型?20.如何区别可变数据类型和不可变数据类型21.将"hello world"转换为首字母大写"Hello World"22.如何检测字符串中只含有数字?23.将字符串"ilovechina"进行反转24.Python 中的字符串格式化方式你知道哪些?25.有一个字符串开头和末尾都有空格,比如“ adabdw ”,要求写一个函数把这个字符串的前后空格都去掉。26.获取字符串”123456“最后的两个字符。27.一个编码为 GBK 的字符串 S,要将其转成 UTF-8 编码的字符串,应如何操作?28. (1)s="info:xiaoZhang 33 shandong",用正则切分字符串输出['info', 'xiaoZhang', '33', 'shandong'](2) a = "你好 中国 ",去除多余空格只留一个空格。29. (1)怎样将字符串转换为小写 (2)单引号、双引号、三引号的区别?

列表

30.已知 AList = [1,2,3,1,2],对 AList 列表元素去重,写出具体过程。31.如何实现 "1,2,3" 变成 ["1","2","3"]32.给定两个 list,A 和 B,找出相同元素和不同元素33.[[1,2],[3,4],[5,6]]一行代码展开该列表,得出[1,2,3,4,5,6]34.合并列表[1,5,7,9]和[2,2,6,8]35.如何打乱一个列表的元素?

字典

36.字典操作中 del 和 pop 有什么区别37.按照字典的内的年龄排序
notion image
38.请合并下面两个字典 a = {"A":1,"B":2},b = {"C":3,"D":4}39.如何使用生成式的方式生成一个字典,写一段功能代码。40.如何把元组("a","b")和元组(1,2),变为字典{"a":1,"b":2}

综合

41.Python 常用的数据结构的类型及其特性?
notion image
42.如何交换字典 {"A":1,"B":2}的键和值?43.Python 里面如何实现 tuple 和 list 的转换?44.我们知道对于列表可以使用切片操作进行部分元素的选择,那么如何对生成器类型的对象实现相同的功能呢?45.请将[i for i in range(3)]改成生成器46.a="hello"和 b="你好"编码成 bytes 类型47.下面的代码输出结果是什么?
notion image
48.下面的代码输出的结果是什么?
notion image

操作类题目

49.Python 交换两个变量的值50.在读文件操作的时候会使用 read、readline 或者 readlines,简述它们各自的作用51.json 序列化时,可以处理的数据类型有哪些?如何定制支持 datetime 类型?52.json 序列化时,默认遇到中文会转换成 unicode,如果想要保留中文怎么办?53.有两个磁盘文件 A 和 B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列),输出到一个新文件 C 中。54.如果当前的日期为 20190530,要求写一个函数输出 N 天后的日期,(比如 N 为 2,则输出 20190601)。55.写一个函数,接收整数参数 n,返回一个函数,函数的功能是把函数的参数和 n 相乘并把结果返回。56.下面代码会存在什么问题,如何改进?
notion image
57.一行代码输出 1-100 之间的所有偶数。58.with 语句的作用,写一段代码?59.python 字典和 json 字符串相互转化方法60.请写一个 Python 逻辑,计算一个文件中的大写字母数量61. 请写一段 Python连接 Mongo 数据库,然后的查询代码。62.说一说 Redis 的基本类型。63. 请写一段 Python连接 Redis 数据库的代码。64. 请写一段 Python 连接 MySQL 数据库的代码。65.了解 Redis 的事务么?66.了解数据库的三范式么?67.了解分布式锁么?68.用 Python 实现一个 Reids 的分布式锁的功能。69.写一段 Python 使用 Mongo 数据库创建索引的代码。

高级特性

70.函数装饰器有什么作用?请列举说明?71.Python 垃圾回收机制?72.魔法函数 __call__怎么使用?73.如何判断一个对象是函数还是方法?74.@classmethod 和@staticmethod 用法和区别75.Python 中的接口如何实现?76.Python 中的反射了解么?77.metaclass 作用?以及应用场景?78.hasattr() getattr() setattr()的用法79.请列举你知道的 Python 的魔法方法及用途。80.如何知道一个 Python 对象的类型?81.Python 的传参是传值还是传址?82.Python 中的元类(metaclass)使用举例83.简述 any()和 all()方法84.filter 方法求出列表所有奇数并构造新列表,a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]85.什么是猴子补丁?86.在 Python 中是如何管理内存的?87.当退出 Python 时是否释放所有内存分配?

正则表达式

88.使用正则表达式匹配出<html><h1>百度一下,你就知道</html>中的地址 a="张明 98 分",用 re.sub,将 98 替换为 10089.正则表达式匹配中(.*)和(.*?)匹配区别?90.写一段匹配邮箱的正则表达式

其他内容

91.解释一下 python 中 pass 语句的作用?
92.简述你对 input()函数的理解
93.python 中的 is 和==
94.Python 中的作用域
95.三元运算写法和应用场景?
96.了解 enumerate 么?
97.列举 5 个 Python 中的标准模块
98.如何在函数中设置一个全局变量
99.pathlib 的用法举例
100.Python 中的异常处理,写一个简单的应用场景
101.Python 中递归的最大次数,那如何突破呢?
102.什么是面向对象的 mro
103.isinstance 作用以及应用场景?
104.什么是断言?应用场景?
105.lambda 表达式格式以及应用场景?
106.新式类和旧式类的区别
107.dir()是干什么用的?
108.一个包里有三个模块,demo1.py, demo2.py, demo3.py,但使用 from tools import *导入模块时,如何保证只有 demo1、demo3 被导入了。
109.列举 5 个 Python 中的异常类型以及其含义
110.copy 和 deepcopy 的区别是什么?111.代码中经常遇到的*args, **kwargs 含义及用法。112.Python 中会有函数或成员变量包含单下划线前缀和结尾,和双下划线前缀结尾,区别是什么?
113.w、a+、wb 文件写入模式的区别
114.举例 sort 和 sorted 的区别
115.什么是负索引?
116.pprint 模块是干什么的?
117.解释一下 Python 中的赋值运算符
118.解释一下 Python 中的逻辑运算符
119.讲讲 Python 中的位运算符
120.在 Python 中如何使用多进制数字?
121.怎样声明多个变量并赋值?

算法和数据结构

122.已知:
notion image
(1) 从 AList 和 BSet 中 查找 4,最坏时间复杂度那个大?(2) 从 AList 和 BSet 中 插入 4,最坏时间复杂度那个大?123.用 Python 实现一个二分查找的函数124.python 单例模式的实现方法125.使用 Python 实现一个斐波那契数列126.找出列表中的重复数字127.找出列表中的单个数字128.写一个冒泡排序129.写一个快速排序130.写一个拓扑排序131.python 实现一个二进制计算132.有一组“+”和“-”符号,要求将“+”排到左边,“-”排到右边,写出具体的实现方法。133.单链表反转134.交叉链表求交点135.用队列实现栈136.找出数据流的中位数137.二叉搜索树中第 K 小的元素

爬虫相关

138.在 requests 模块中,requests.content 和 requests.text 什么区别139.简要写一下 lxml 模块的使用方法框架140.说一说 scrapy 的工作流程141.scrapy 的去重原理142.scrapy 中间件有几种类,你用过哪些中间件143.你写爬虫的时候都遇到过什么?反爬虫措施,你是怎么解决的?144.为什么会用到代理?145.代理失效了怎么处理?146.列出你知道 header 的内容以及信息147.说一说打开浏览器访问 百度一下,你就知道 获取到结果,整个流程。148.爬取速度过快出现了验证码怎么处理149.scrapy 和 scrapy-redis 有什么区别?为什么选择 redis 数据库?150.分布式爬虫主要解决什么问题151.写爬虫是用多进程好?还是多线程好? 为什么?152.解析网页的解析器使用最多的是哪几个153.需要登录的网页,如何解决同时限制 ip,cookie,session(其中有一些是动态生成的)在不使用动态爬取的情况下?154.验证码的解决(简单的:对图像做处理后可以得到的,困难的:验证码是点击,拖动等动态进行的?)155.使用最多的数据库(mysql,mongodb,redis 等),对他的理解?

网络编程

156.TCP 和 UDP 的区别?157.简要介绍三次握手和四次挥手158.什么是粘包? socket 中造成粘包的原因是什么? 哪些情况会发生粘包现象?

并发

159.举例说明 conccurent.future 的中线程池的用法160.说一说多线程,多进程和协程的区别。161.简述 GIL162.进程之间如何通信163.IO 多路复用的作用?164.select、poll、epoll 模型的区别?165.什么是并发和并行?166.一个线程 1 让线程 2 去调用一个函数怎么实现?167.解释什么是异步非阻塞?168.threading.local 的作用?

Git 面试题

169.说说你知道的 git 命令170.git 如何查看某次提交修改的内容
Python CheetSheet

FAQs

Help System

python中的help()类似unix中的man指令,熟悉后会对我们的编程带来很大帮助

1. Introduction to Python

Origin
改进ABC,开发新的解释程序,开源python源代码,名字取自Monty python's flying circus
改进ABC,开发新的解释程序,开源python源代码,名字取自Monty python's flying circus
将其他语言翻译成机器语言的工具从,称为编译器
编译器根据翻译的方式分为编译型编译器和解释型编译器,解释型编译器又称为解释器,解释器是按逐行的方式解释,而编译器是编译形成可执行的程序,速度较快。
 
  • 编译型语言:程序在执行之前需要一个专门的编译过程,把程序编译成为机器语言的文件,运行时不需要重新翻译,直接使用编译的结果就行了。程序执行效率高,依赖编译器,跨平台性差些。如 C、C++
  • 解释型语言:解释型语言编写的程序不进行预先编译,以文本方式存储程序代码,会将代码一句一句直接运行。在发布程序时,看起来省了道编译工序,但是在运行程序的时候,必须先解释再运行
    • notion image
Objective of Python
Computer Programming for Everybody
  • 一门简单直观的语言并与主要竞争者一样强大
  • 开源,以便任何人都可以为它做贡献
  • 代码像纯英语那样容易理解
  • 适用于短期开发的日常任务
Philosophy of Python
Python 开发者的哲学是:用一种方法,最好是只有一种方法来做一件事
如果面临多种选择,Python 开发者一般会拒绝花俏的语法,而选择明确没有或者很少有歧义的语法
Features
  1. 完全面向对象语言(面向对象是一种思维方式,谁能来做就让他来做)函数、模块、数字、字符串都是对象,在 Python 中一切皆对象,要解决复杂的问题,就可以找多个不同的对象,各司其职,共同实现,最终完成需求
  1. 强大的标准库
  1. 大量的第三方模块(科学计算,人工智能,机器学习,web开封,数据库接口,图形系统)
Development environment built
python 开发环境搭建
01 环境配置与运行 - 少数派
不论是学习哪一门编程语言,在入门之初,没有什么比让程序真正的运行跑起来更令人鼓舞的了。相比之下,程序报错或者压根就没运行起来所带来的挫败感却是能让人一言不合就实现「从入门到放弃」的跨越。 让我们的程序跑起来的第一步不是写下一句能让程序运行的代码,而是 环境配置 。纵观所有的编程语言课程、资料甚至是教材,无一例外第一课就是要教会读者或使用者如何将环境搭建起来。 这就好比是要学做菜,就算你食材甄选面面俱到、柴米油盐酱醋茶一样不落下,但如果你连最基本的锅、铲和刀等这些基本的厨具都没有,又何来烹饪这一说? 所以,搭建环境就好比做菜时的厨具,建立在厨具的基础上你才能开展你的曼妙「创造」。 本节主要涉及 Windows 和 macOS 的安装和配置内容。Linux 平台的安装过程这里就不过多涉及,如果你已经能熟练使用 Linux,那就说明你肯定会自己安装 Python 了。 点击进入到官网的 下载页面 后选择对应的 Python 版本就可进行下载。 这里需要注意,虽然现在 Python 已经出到 3.8 版本了,可是有的第三方库 仍只是支持低版本的 Python ,虽然用来基础学习没有什么问题,但是如果以后调用不支持第三方库可能会报错,所以这里需要自己权衡一下。 所以目前我使用的是 Python 的 3.7.x 版本。选择进入到相应版本的下载页后,直接拉到页面最下方,选择相应的系统安装包下载(Windows 选择 executable installer,macOS 选择 installer )。 下载好对应的安装包之后,就可以进一步安装了。 1.1.1 Windows 平台的安装 Windows 用户需要注意的是,在安装过程中, 一定要把 Add Python to Path
01 环境配置与运行 - 少数派

2. Basic Knowledge Structure

Prerequistes

Running Enviroment

Python 源程序就是一个特殊格式的文本文件,可以使用任意文本编辑软件做 Python 的开发
  • 解释器 —— python / python3 python / python3 文件名.py
  • 交互式 —— ipython /python shell (用 exit()退出 python 的 shell)
  • 集成开发环境 —— PyCharm
Lessons 01: Introduction
Comments ("#")
  • Provide context
  • help other people read
  • Ignore a line of code
Print (Print())
  • Tell a computer to talk
  • No difference for double quote "" and single quote ('')
Errors
SyntaxError
NameError
Variables
  • offer a method of storing data for reuse
  • Variables can’t have spaces or symbols in their names other than an underscore (_).
Calculations
  • Python converts all ints to floats before performing division,In older versions of Python (2.7 and earlier) this conversion did not happen, and integer division would always round down to the nearest integer.
  • Order of operations
  • Modulo/concatenation/plus
Multi-line Strings (""" or ''')
Quizs-Recipts
 
Lessons 02: Introduction to Functions
Definition:
A function is a collection of several lines of code,By calling a function, we can call all of these lines of code at once, without having to repeat ourselves.
Bnefits:
  • Easy to understand
  • repeated code is generally more error prone
Key Points:
  • White Spcase(indent)
  • Multiple parameters (Default Parameters)
  • Mutiple Returns Values (lines of codes don't work after return )
  • Scope
  • Defining_function beforeahead calling function
Function_name
Correlation
Lessons 14: classes and oop(objecti-oriented program)
Quizzs
 
Import variables or function in the module
  1. 一个文件中 使用 import 导入这个模块
  1. 导入之后,就可以使用 模块名.变量 / 模块名.函数 的方式,使用这个模块中定义的变量或者函数
 
Anonymous Functions
Lambda
lambda x: x ** 2
 
 
Lessons 03: Control Flow
Definition:
Includes gateways, known as conditional statements, to tell the computer when it should execute certain blocs of code.
Key Points:
  • boolean variable and expressions
  • Relational Operators (== ≤ ≥)
  • Boolean Operators (and or not)
  • if — elif —else (promise single satisfied condition)
  • Try and Except Statements
First, the statement under try will be executed. If at some point an exception is raised during this execution, such as a NameError or a ValueError and that exception matches the keyword in the except statement, then the try statement will terminate and the except statement will execute.
Project01 -Sal's Shipping
  • project02--Game of chance
Lessons 04: Creating a List in Python
Definition:
A list is an ordered set of objects in Python, combine multiple data types in one list.
Benifits:
 
Key points:
  • heights = [61,space70, 67, 64]
  • zip takes two (or more) lists as inputs and returns an object that contains a list of pairs.
  • List modifying operation
  • Range()
Project 01—Gradebook
Lessons 05: Modifying python lists
Definition:
How to work with existing lists of data
Benifits:
 
Key points:
  • Get the length of a list len()
  • Select subsets of a list (called slicing) **[ ] **[-1] **[:]
  • Count the number of times that an element appears in a list letters.count('i')
  • Sort a list of items **.sort() sorted(**)
 
ADD
list.append(data)
list1.extend(list2)
liat1.insert(index,data)
 
MODIFY
list[index] = data
 
DEL
del list[index] 建议采用下面的方法
list.remove[data] Delete specified element of first appearance in the list
list.pop() delete the final one element
list.pop(index) delete element at specific location
list.clear delete the whole of list
 
Aggeregate function
list.count(data)
len(list)
 
Sort
list.sort(reverse = true) descending sort
list.reverse() reverse the order
sorted()
 
Project 01 Len's Slice
Project 02 — List user-defined aggregate functions
Lessons 06: Tuples
Definition:
tuples is immutable
Benifits:
  1. 让列表的数据不可更改
  1. 用元组一次返回多个数据
Key points:
  • Can't add and remove item from tuples or change the order of tuples
  • Unpacking tuples
  • tuples vs list
Not to change the order of data
more or less data inside them
 
list(tuple)
tuple(list)
 
Project 01—
 
Project 02—
 
Lessons 07: Loops
Definition:
using, or iterating through, every item in a list, A loop is a way of repeating a set of code many times.
Benifits:
  • Loops that let us move through each item in a list, called for loops
  • Loops that keep going until we tell them to stop, called while loops
  • Loops that create new lists, called list comprehensions
 
Key points:
  • temporary variable can be named whatever we want and does not need to be defined beforehand.
    • Using Range in Loops - don't care what's in the list/ Infinite Loop/ break /continue
      • list comprehension:
        Project 01 — Carly's Clippers
        Project 02 —
        Lessons 08: Introudction to String
        Definition:
         
        Benifits:
        slice strings,
        select specific characters from strings,
        search strings for characters,
        iterate through strings, and use strings in conditional statements.
        Key points:
        • a slice of string
        notion image
         
        notion image
        notion image
        notion image
        notion image
        notion image
         
        notion image
        • Concatenating String (+)
        • mutability - Strings are Immutable
        • Escape Characters
        • Iterating through Strings (manipulate and analyze strings)
          • String and conditions
             
            Project 01—
             
            Project 02—
             
            Lessons 09: String Method
            Definition:
             
            Benifits:
            • great for sanitizing user input and standardizing the formatting of your strings.(reformat them slightly to fit the conventions of the organization’s database.)
            • generate outputs with variable values
            Key points:
            • py string_name.string_method(arguments) len() which is called with a string as it’s argument
            • string[index], string.index()
            • *.upper(), *.lower(), *.title()
            • string_name.split(delimiter)
              • 'delimiter'.join(list_you_want_to_join)
              • string_name.strip()
                • string_name.replace(character_being_replaced, new_character)
                • 'smooth'.find('t') return index
                  • .find() takes a string as an argument and searching the string it was run on for that string. It then returns the first index value where that string is located.
                • "My favorite song is {} by {}.".format(song, artist) + "My favorite song is {song} by {artist}.".format(song=song, artist=artist)
                  • Note: You have to make sure that your variabe appeared as arguments in the same order that you wanted them to aapper in the string, which just added unnecessary complications when writing, but in the second method, By including keywords in the string and in the arguments, you can remove that ambiguity.
                 
                Project 01— Print cooreponding info
                 
                Project 02—Thread Shed
                Project 03—Challenges
                Lessons 11: Introduction to Dictionary
                Definition:
                A dictionary is an unordered set of key: value pairs.
                 
                1. A dictionary begins and ends with curly braces ({ and }).
                1. Each item consists of a key (i.e., “oatmeal”) and a value (i.e., 3)
                1. Each key: value pair (i.e., "oatmeal": 3 or "avocado toast": 6) is separated by a comma (,)
                1. It’s considered good practice to insert a space () after each comma, but your code will still run without the space.
                 
                Difference between dictionary and list
                List: a collection of oredered objetcs
                Dictionary: a collection of unordered objects
                 
                Benifits:
                • Use a key to get a value from a dictionary
                • Check for existence of keys
                • Find the length of a dictionary
                • Iterate through keys and values in dictionaries
                • Describe related information of an object using a bunch of key-value pair In a complex scenario
                • put many dict in a list, iterating each of elemen for the same operation
                Key points:
                • list or dictionary can not be key
                  • string,number, tuple (immutable)
                • Hash the key to determine how to store the dictionary's data in memory key : immutable data type value : any type of data
                • Inspect
                  •  
                • Add a key (overwrite) /multiple keys **.update()
                  • Del
                    • List Comprehensions to Dictionaries
                       
                      Lessons 12: Using Dictionaries
                      Key points:
                      • Try/Except to Get a Key
                        • Safely Get a Key for safe input **.get()
                          • Delete a key **.pop( )
                            • Get All Keys **.keys( )
                              • Get all values
                                • Get All Items
                                  Project 01 — Scrabble
                                  Project 02—
                                   
                                  Lessons 13: FILES
                                  Definition:
                                  Computers use file systems to store and retrieve data
                                  Benifits:
                                   
                                  Key points:

                                  Txt

                                  • Reading a File
                                    • Writing a File
                                      • With
                                        • The with keyword invokes something called a context manager for the file that we’re calling open() on.This context manager takes care of opening the file when we call open() and then closing the file after we leave the indented block.
                                          Leaving a file connection open unnecessarily can affect performance or impact other programs on your computer that might be trying to access that file.

                                      CSV

                                      • CSV files are just plain text files!(comma sperated values)
                                        •  
                                      • Write a CSV file csv.DictWriter()
                                          1. open a new CSV file in write-mode by passing the 'w' argument
                                          1. define the fields we’re going to be using into a variable called fields
                                          1. instantiate our CSV writer object and pass two arguments.(the file handler object, list of fields)
                                          1. First we want the headers, so we call .writeheader() on the writer object
                                          1. call output_writer.writerow() with the item dictionaries which writes each line to the CSV file.
                                      • Reading json.load ()
                                        • Writing a JSON File json.dump()
                                          Project 01 — Hacking The Fender
                                          Project 02—
                                           
                                          Lessons 14: classes and oop(objecti-oriented program)
                                          Definition:
                                           
                                          Benifits:
                                           
                                          Key points:
                                          • self.valuename - 实例的变量,和Class的变量,全局变量,局部变量相对应; self.gunction()- 实例的函数,与其他全局函数相对应
                                          • **
                                          • **
                                          Project 01—
                                           
                                          Project 02—
                                           
                                          Summary
                                          Data Types
                                          Python 中数据类型可以分为 数字型 和 非数字型
                                          • 在 Python 中,所有 非数字型变量 都支持以下特点:
                                              1. 都是一个 序列 sequence,也可以理解为 容器
                                              1. 取值 []
                                              1. 遍历 for in
                                              1. 计算长度最大/最小值比较删除
                                              1. 链接 + 和 重复 *
                                              1. 切片
                                          • 数字型
                                            • 整型 (int)
                                            • 浮点型(float
                                            • 布尔型(bool
                                              • 真 True 非 0 数 —— 非零即真
                                              • 假 False 0
                                            • 复数型 (complex)
                                              • 主要用于科学计算,例如:平面场问题、波动问题、电感电容等问题
                                          • 非数字型
                                            • 字符串
                                            • 列表
                                            • 元组
                                            • 字典
                                          Python 中数据类型可以分为 可变不可变类型
                                          不可变类型,内存中的数据不允许被修改:
                                          • 数字类型 int, bool, float, complex, long(2.x)
                                          • 字符串 str
                                          • 元组 tuple
                                          可变类型,内存中的数据可以被修改:
                                          • 列表 list
                                          • 字典 dict
                                          如果给一个可变类型的变量,赋值了一个新的数据,引用会修改 * 变量 不再 对之前的数据引用 * 变量 改为 对新赋值的数据引用
                                          Variable Types
                                          全局变量和局部变量
                                          局部变量
                                          局部变量 是在 函数内部 定义的变量,只能在函数内部使用 函数执行结束后,函数内部的局部变量,会被系统回收 不同的函数,可以定义相同的名字的局部变量,但是 彼此之间 不会产生影响
                                          全局变量
                                          函数外部定义得变量,函数内部出现变量时,判断得步骤
                                          1. 首先 查找 函数内部 是否存在 指定名称 的局部变量,如果有,直接使用
                                          1. 如果没有,查找 函数外部 是否存在 指定名称 的全局变量,如果有,直接使用
                                          1. 如果还没有,程序报错!
                                          函数不能直接修改 全局变量的引用
                                          在函数内部修改全局变量的值
                                           
                                          全局变量定义的位置
                                          为了保证所有的函数都能够正确使用到全局变量,应该 将全局变量定义在其他函数的上方
                                          Function Types
                                           
                                          Magic Command
                                          上一篇
                                          模板设计模式:让你的代码结构更清晰
                                          下一篇
                                          Guide to Linux System

                                          Comments
                                          Loading...