· Python basics
Python is a powerful and highly efficient language. It has cross-platform characteristics. Easy to learn. Open and scalable.
· python features
- Python is powerful… and fast;
- plays well with others;
- runs everywhere;
- is friendly & easy to learn;
- is Open.
· python application scope
- game development
- website development
- data analysis
- deep learning
program output
Operating systems and programs
Our computers will all be equipped with an operating system, and we will install some software on the operating system (such as QQ, WeChat, etc.).
We all say verbally that we have opened such-and-such software. The meaning here is actually that I am running a certain program.
Programs run on the operating system, and the programs that run are called processes .
We can treat the running process as an isolated individual, a black box, that is, you don't know what is going on inside.
Even if you wrote this program, you may not necessarily know what it is doing, which step it has reached, and which piece of logic you are entering during the running process.
If you need to check the internal operation of the program, you need to inform the outside world from inside the program. The way of informing is actually to output logs.
· Print output
The program can output the program execution data to the console through the print output function.
1 |
print('hello python') |
!!!note
print() is the printing function, and the content to be printed and displayed is in the brackets.
If what is printed is a sentence, it needs to be wrapped with '''', but numbers are not required.
· Comments
Single line comments
Single-line comments start with # , followed by a space, followed by the content of the comment, for example :
linenums
1 |
|
Multi-line comments
If the comment content is relatively large, you can use multi-line comments
Multi-line comments start with ''' and end with ''' , or start with """ and end with """
linenums
1 |
''' |
operator
Basic operations of addition, subtraction, multiplication and division
- addition
1 |
print(1 + 1) |
- Subtraction
1 |
print(3 - 1) |
- multiplication
1 |
print(3 * 2) |
- division
1 |
print(8 / 4) |
- Take the remainder
1 |
print(7 % 2) |
!!!noteAddition
, subtraction, multiplication, division, and remainder are represented by + , - , * , / , % respectively.
Mixed operations
1 |
print((2 + 3) * 5) |
When doing mixed operations, parentheses have priority.
Special operators
- exponentiation
1 |
print(3 ** 2) |
- Integer division
1 |
print(7 // 3) |
** The exponentiation operator, preceded by a number and followed by a power
// It is an integer division, and the result of the division is an integer
variable
Variables are used to describe the data storage space in the computer .
We can save defined data through variables.
variable definition
Rule: variable name = stored value
For example, I defined a variable age to store a number:
1 |
age = 18 |
Variable naming rules
Variable names follow the following rules:
- Can only be composed of numbers, letters, _ (underscore)
- cannot start with a number
- Cannot be a keyword
- case sensitive
The !!!tip
keyword is a word that is already occupied by the system by default, and programmers are not allowed to name it after these.
Python’s keywords (33) are:
`and`, `as`, `assert`, `break`,
`class`, `continue`, `def`, `del`,
`elif`, `else`, `except`, `finally`,
`for`, `from`, `global`, `if`,
`import`, `in`, `is`, `lambda`,
`nonlocal`, `not`, `or`, `pass`,
`raise`, `return`, `try`, `while`,
`with`, `yield`,
`False`, `None`, `True`
For example, the following names are illegal:
1 |
itcast.cn = 'Hello' |
!!!warning
The name contains . , which is illegal.
Variable naming convention
When we write python code, we usually use underscore nomenclature:
1 |
person_count = 100 |
Person and count are two different words, and we hope to include a combined meaning when naming them.
We use _ to connect. This is the way we recommend.
Of course, you can also name it in two ways: `personCount` or `PersonCount` (small camel case and big camel case naming methods).
But not recommended.
In the future, other people's APIs will be used, such as Qt's API, which uses camel case naming, mainly to ensure that cross-language APIs are the same.
Common data types
integer
1 |
age = 10 |
Floating point number (decimal)
1 |
age = 10.5 |
Boolean type
1 |
is_ok = True |
string type
1 |
name = 'Prince of Wisdom' |
some cases
Multiple variable assignment
1 |
name, age, gender = 'Prince Dark Horse' , 10 , True |
!!!note
python can assign values to multiple variables at the same time
Variable operations
hl_lines
1 |
age = 10 |
or
hl_lines
1 |
age = 10 |
!!!note
When a variable is of numeric type, it can directly participate in operations.
`+=`: **add** a value to itself
`-=`: **subtract** a value from itself
`*=`: **multiply** a value on its own basis
`/=`: Divide a value by itself
list definition
A list is a sequence, which we can understand as a container for data.
In Python, lists are used very frequently. You can store a string of data, and each stored data is called an element .
The type of the list is list , represented by a pair of []
1 |
names = ['itcast', 'itheima', 'bxg'] |
List length
1 |
names = ['itcast', 'itheima', 'bxg'] |
Get the length of a list through the len function
access element
通过下标进行访问, 列表下标从0开始
1 |
names = ['itcast', 'itheima', 'bxg'] |
!!!note
通过下标进行访问元素,下标从0开始。
下标也可以为负数,为 **当前下标减去列表长度**
超出长度,会有异常
增加元素
通过append函数添加元素
1 |
names = ['itcast', 'itheima', 'bxg'] |
通过insert函数插入指定位置
1 |
names = ['itcast', 'itheima', 'bxg'] |
删除元素
通过remove函数移除指定元素
1 |
names = ['itcast', 'itheima', 'bxg'] |
通过del函数移除指定下标
1 |
names = ['itcast', 'itheima', 'bxg'] |
修改元素
通过索引来修改元素
1 |
names = ['itcast', 'itheima', 'bxg'] |
索引
通过元素获得下标索引
1 |
names = ['itcast', 'itheima', 'bxg'] |
反转
1 |
names = ['itcast', 'itheima', 'bxg'] |
排序
升序
1 |
names = ['itcast', 'itheima', 'bxg'] |
降序
1 |
names = ['itcast', 'itheima', 'bxg'] |
元组
Python的元组与列表类似,也是容器的一种,不同之处在于元组的元素 不能修改
元组的类型为tuple, 用一对() 表示,中间用,分隔
1 |
names = ('itcast', 'itheima', 'bxg') |
定义注意
1 |
names = ('itcast') |
!!!error
以上是错误的元组定义.
1 |
names = ('itcast', ) |
!!!success
以上是元组的正确定义.
如果定义的元组中只有一个元素,后面要跟一个`,`
组包解包交换
元组具备自动组包功能
1 |
names = 'itcast', 'itheima', 'bxg' |
!!!note
names的类型是元组类型,这就是元组的自动组包特征
元组具备自动解包功能
1 |
names = ('itcast', 'itheima', 'bxg') |
元组具备数据交互功能
传统的数据交换:
1 |
a = 10 |
元组数据交换:
1 |
a = 10 |
类比列表
访问
1 |
names = ('itcast', 'itheima', 'bxg') |
索引
1 |
names = ('itcast', 'itheima', 'bxg') |
添加,删除,修改,排序
tuple是只读的数据类型。因此,不可以做任何修改操作。
!!!error
tuple不具备修改的能力。
添加,删除,修改,排序等功能是不存在的。
切片
切片,英文单词为slicing。
python中,用来取列表(list),元组(tuple),字符串(str)部分元素的操作。
切片的格式
1 |
data[start:end:step] |
!!!note
data 为 list或者tuple或者str。
`start` 为 开始索引
`end` 为结束索引
`step` 为步长
**包含开始索引,不包含结束索引**
获取部分元素
需求: 获取列表前3个元素.
hl_lines
1 |
nums = [0, 1, 2, 3, 4, 5, 6] |
如果步长为1,可以省略
hl_lines
1 |
nums = [0, 1, 2, 3, 4, 5, 6] |
如果开始索引为0,可以省略
hl_lines
1 |
nums = [0, 1, 2, 3, 4, 5, 6] |
如果为末尾结束,可以省略结尾索引
1 |
nums = [0, 1, 2, 3, 4, 5, 6] |
索引正序和倒序
索引分为正序和倒序, 正序自左至右,从0开始;倒序自右至左,从-1开始。
需求: 获取列表前3个元素.
hl_lines
1 |
nums = [0, 1, 2, 3, 4, 5, 6] |
步长为负数
步长为负数时,代表反向切片.
需求: 获取列表中从下标为2开始的3个元素,要求倒序输出.
1 |
nums = [0, 1, 2, 3, 4, 5, 6] |
集合set
Python的集合与列表类似,也是容器的一种,不同之处在于:
- 列表是有序的 , 集合是无序的。
- 列表的元素可以重复, 集合的元素不可以重复
集合的类型为set, 用一对{} 表示,中间用,分隔
1 |
names = {
'itcast', 'itheima', 'bxg'} |
集合长度
1 |
names = {
'itcast', 'itheima', 'bxg'} |
通过len函数获得列表的长度
添加元素
1 |
names = {
'itcast', 'itheima', 'bxg'} |
删除元素
删除指定元素, 没有时报错
1 |
names = {
'itcast', 'itheima', 'bxg'} |
删除指定元素, 没有时不做任何操作,不报错
1 |
names = {
'itcast', 'itheima', 'bxg'} |
随机删除元素
1 |
names = {
'itcast', 'itheima', 'bxg'} |
字典
字典(dictionary) 和列表从功能角度而言,都是一个装数据的容器.
- 字典可以存储多个数据。
- 字典采用 键值对 方式存储数据
- 字典没有索引,是无序的
- 字典的键是唯一的
字典的类型为’dict’, 用一对’{}’包裹, 每一组元素采用,分隔,一组元素包含key和value,key和value采用: 分隔。
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
字典长度
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
通过len函数获得字典元素的数量
访问元素
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
增加和修改
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
!!!note
不存在key就是添加。存在就是修改
删除
del删除
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
pop删除
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
pop删除时会将删除元素的value返回
clear清空
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
复杂数据结构
字典可以描述复杂的数据结构.
例如,我们描述一个学生可以这个样子:
1 |
stu = { 'name': 'itcast', 'age': 10, 'gender': True} |
我们描述多个个学生,用学生的名字做唯一标识
1 |
stus = {
|
条件判断
if语句
代码格式:
1 |
if 条件: |
示例:
1 |
if 1 < 2: |
if…else…语句
代码格式:
1 |
if 条件: |
示例:
1 |
if 1 < 2: |
if…elif…else语句
代码格式:
1 |
if 条件1: |
示例:
1 |
if 1 > 2: |
一些案例
input输入函数
input函数,可以帮助我们的程序接收外部提供的数据,一个阻塞式的代码
1 |
age = input('请输入年龄') |
if…else案例
需求:
- 输入用户年龄
- 判断是否满 18 岁 (>=)
- 如果满 18 岁,允许进网吧嗨皮
- 如果未满 18 岁,提示回家写作业
1 |
age = int(input('请输入你的年纪:')) |
if…elif…else案例
需求:
需求
- 定义 holiday 字符串变量记录节日名称
- 如果是 情人节 应该 买玫瑰/看电影
- 如果是 平安夜 应该 买苹果/吃大餐
- 如果是 生日 应该 买蛋糕
- 其他的日子每天都是节日啊……
1 |
holiday = input('请输入节日名称') |
嵌套案例
需求:
- 定义布尔型变量 has_ticket 表示是否有车票
- 定义整型变量 knife_length 表示刀的长度,单位:厘米
- 首先检查是否有车票,如果有,才允许进行 安检
- 安检时,需要检查刀的长度,判断是否超过 20 厘米
果超过 20 厘米,提示刀的长度,不允许上车
如果不超过 20 厘米,安检通过 - 如果没有车票,不允许进门
1 |
has_ticket = input("请输入是否有车票:") |
in和not int
in和not int是python的操作符,用来判断元素释放在容器中,如果在,返回True,否则False。
这里的容器包含了我们前面学习的列表list,元组tuple,集合set,字典set以及字符串str
字符串
1 |
str = 'itcast' |
列表
1 |
names = ['itcast', 'itheima', 'bxg'] |
元组
1 |
names = ('itcast', 'itheima', 'bxg') |
集合
1 |
names = {
'itcast', 'itheima', 'bxg'} |
字典
字典中,in 和 not in主要用来判断 字典的键
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
while循环语法
1 |
while 条件: |
死循环
死循环在程序中有一定的使用场景,可以保证程序不会停止。
1 |
import time |
!!!note
time是python系统内置的模块,提供时间操作相关的api。
`time.sleep`可以帮助睡眠
循环变量
可以通过变量来控制循环
1 |
# 1.定义循环变量 |
break和contiune
- break: 某一条件满足时,不再执行循环体中后续重复的代码,并退出循环。
- continue: 某一条件满足时,不再执行本次循环体中后续重复的代码,但进入下一次循环判断.
break示例:
1 |
i = 0 |
contiune示例:
1 |
i = 0 |
嵌套循环
while 里面还有 while
1 |
while 条件1: |
示例代码:
1 |
# 外层循环 |
for循环语法
for循环的主要作用是遍历数据(容器)中的元素 字符串、列表等高级数据类型都属于容器,都可以通过for循环遍历.
for循环的语法格式如下:
1 |
for 临时变量 in 列表或者字符串等可迭代对象: |
遍历操纵
字符串
1 |
str = 'itheima' |
遍历列表元组集合
1 |
names = ['itcast', 'itheima', 'bxg'] |
遍历字典
字典遍历过程中,获得的是字典的键.
1 |
d = {
'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True} |
range区间
range是一个内置的函数,可以自动帮我们创建 整数列表.
语法格式为:
1 |
range(start, end, step) |
!!!note
* `start`为起始值
* `end`为结束值
* `step`为步长
意思为,创建一个从`start`开始,间隔`step`,一直到`end`结束的列表
**包含start,不包含end**
1 |
arr = range(1, 10, 2) |
步长为1
步长为1时,可以省略
1 |
arr = range(1, 10) |
起始值为0,步长为1
起始值为0,步长为1,起始值可以省略,步长也可以省略
1 |
arr = range(10) |
遍历range
1 |
for num in range(0, 10, 2): |
函数
函数是程序非常重要的组成部分,是计算机执行命令的单元.
所谓函数,就是把 具有独立功能的代码块 组织为一个整体,在需要的时候 调用.
使用函数可以提高编写的效率以及 代码的重用.
函数的使用包含两个部分:
- 定义函数: 在函数中编写代码,实现功能
- 调用函数: 执行编写的代码
函数定义格式
1 |
def 函数名(): |
!!!note
def时英文define的缩写,意为声明
`函数名`是根据自己的业务来取的,和变量命名规则相同。
函数调用格式
1 |
函数名() |
第一个函数
需求:
- 编写一个打招呼 say_hello 的函数,封装三行打招呼的代码
- 在函数下方调用打招呼的代码
1 |
# 定义函数 |
函数的参数
函数的参数,可以传递数据给函数内部 参数的作用是增加函数的 通用性.
定义和调用格式:
1 |
# 定义函数 |
需求:
- 定义函数,传递a和b,求a+b的和
1 |
def sum(a,b): |
函数返回值
定义和调用格式:
1 |
# 定义函数 |
需求:
- 定义函数返回两个数最大值
1 |
# 定义函数 |
多返回值
python函数可以返回多个结果
需求:
- 计算两个数的加和减
1 |
def cacl(a, b): |
局部变量和全局变量
局部变量
- 局部变量,指的是在函数内部定义的变量
- 局部变量的目的是存储需要临时保存的数据
1 |
def func1(): |
全局变量
- 全局变量是在整个py文件中声明,全局范围内都可以访问
1 |
# 全局变量 |
函数内修改全局变量
1 |
# 定义全局变量 |
函数注释
函数名并不能完全的表示出函数的含义,定义函数的时候就需要给函数加上注释
函数的注释就是文档注释
注释的规则和格式如下:
- 注释应该定义在函数的下方
- 使用三对引号注释
1 |
def say_hello(): |
类
类的定义
- 属性(变量)
- 函数
1 |
class MyClass: |
!!!note
class为关键字,用来声明一个类
`__init__`是构造函数,构造函数也是函数,是一个具体实例对象创建时默认调用的函数。
`self`表示当前创建实例对象本身
类中的函数,有个特点,默认第一个参数都是`self`
对象
- 类是一种模板模型
- 对象是这个类的具体实现
!!!tip
狗和旺财,哪一个是类?哪一个是对象?
狗是一种类型,属于模板
旺财是狗的实现,属于具体的,具体的就是对象
类的使用
类的使用,其实就是将类具体化,获得对象,然后使用对象的属性和方法
1 |
class Car: |
!!!note
self.speed是属性,用来记录数据的
`self.x`是属性,用来记录数据的
`move`是函数,是一种行为,行为的变化会产生数据的变化
整个对象,其实就是维护状态数据的。
以上就是python基础知识的整理
创作不易,看到最后的小伙伴们,动动你们发财的手指点个赞支持一下