Python basic knowledge point nanny level (recommended collection)

· 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
2


# The following code is to print hello to the black horse unmanned car ( 'hello black horse unmanned car' )

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
2
3
4
5
6

'''
The first line of code is to say hello to the Dark Horse unmanned car.
The second line of code is to say hello to Chuanzhi Podcast
'''
print ( 'hello Dark Horse unmanned car' )
print ( 'hello Spongebob' )

operator

Basic operations of addition, subtraction, multiplication and division

  1. addition

1

print(1 + 1)

  1. Subtraction

1

print(3 - 1)

  1. multiplication

1

print(3 * 2)

  1. division

1

print(8 / 4)

  1. Take the remainder

1

print(7 % 2)

!!!noteAddition
, subtraction, multiplication, division, and remainder are represented by + , - , * , / , % respectively.

Mixed operations

1
2
3
4

print((2 + 3) * 5)
print((5 - 3) * 2)
print((5 + 3) / 2)
print((5 + 3) * (2 + 1))

​ When doing mixed operations, parentheses have priority.

Special operators

  1. exponentiation

1

print(3 ** 2)

  1. 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
2

age = 18
print(age)

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
2
3

age = 10
age = age + 5
print(age)

or

hl_lines

1
2
3

age = 10
age += 5
print(age)

!!!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
2
3

names = ['itcast', 'itheima', 'bxg']
print(names)
print(type(names))

List length

1
2

names = ['itcast', 'itheima', 'bxg']
print(len(names))

Get the length of a list through the len function

access element

通过下标进行访问, 列表下标从0开始

1
2
3
4
5

names = ['itcast', 'itheima', 'bxg']
print(names[0])
print(names[1])
print(names[2])
print(names[-1])

!!!note
通过下标进行访问元素,下标从0开始。

下标也可以为负数,为 **当前下标减去列表长度**

超出长度,会有异常

增加元素

通过append函数添加元素

1
2
3

names = ['itcast', 'itheima', 'bxg']
names.append('czxy')
print(names)

通过insert函数插入指定位置

1
2
3

names = ['itcast', 'itheima', 'bxg']
names.insert(1, 'czxy')
print(names)

删除元素

通过remove函数移除指定元素

1
2
3

names = ['itcast', 'itheima', 'bxg']
names.remove('bxg')
print(names)

通过del函数移除指定下标

1
2
3

names = ['itcast', 'itheima', 'bxg']
del names[1]
print(names)

修改元素

通过索引来修改元素

1
2
3

names = ['itcast', 'itheima', 'bxg']
names[1] = 'czxy'
print(names)

索引

通过元素获得下标索引

1
2
3

names = ['itcast', 'itheima', 'bxg']
index = names.index('itheima')
print(index)

反转

1
2
3

names = ['itcast', 'itheima', 'bxg']
names.reverse()
print(names)

排序

升序

1
2
3

names = ['itcast', 'itheima', 'bxg']
names.sort()
print(names)

降序

1
2
3

names = ['itcast', 'itheima', 'bxg']
names.sort(reverse=True)
print(names)

元组

Python的元组与列表类似,也是容器的一种,不同之处在于元组的元素 不能修改

元组的类型为tuple, 用一对() 表示,中间用,分隔

1
2
3

names = ('itcast', 'itheima', 'bxg')
print(names)
print(type(names))

定义注意

1

names = ('itcast')

!!!error
以上是错误的元组定义.

1
2

names = ('itcast', )
names = ('itcast', 'itheima')

!!!success
以上是元组的正确定义.

如果定义的元组中只有一个元素,后面要跟一个`,`

组包解包交换

元组具备自动组包功能

1
2
3

names = 'itcast', 'itheima', 'bxg'
print(names)
print(type(names))

!!!note
names的类型是元组类型,这就是元组的自动组包特征

元组具备自动解包功能

1
2
3
4
5

names = ('itcast', 'itheima', 'bxg')
name1, name2, name3 = names
print(name1)
print(name2)
print(name3)

元组具备数据交互功能

传统的数据交换:

1
2
3
4
5
6

a = 10
b = 5
tmp = a
a = b
b = tmp
print("a = {}, b = {}".format(a, b))

元组数据交换:

1
2
3
4

a = 10
b = 5
a, b = b, a
print("a = {}, b = {}".format(a, b))

类比列表

访问

1
2

names = ('itcast', 'itheima', 'bxg')
print(names[0])

索引

1
2
3

names = ('itcast', 'itheima', 'bxg')
index = names.index('itheima')
print(index)

添加,删除,修改,排序

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
2

nums = [0, 1, 2, 3, 4, 5, 6]
print(nums[0:3:1])

如果步长为1,可以省略

hl_lines

1
2
3
4
5

nums = [0, 1, 2, 3, 4, 5, 6]
# 省略步长
print(nums[0:3:])
# 或者完全省略
print(nums[0:3])

如果开始索引为0,可以省略

hl_lines

1
2
3

nums = [0, 1, 2, 3, 4, 5, 6]
print(nums[0:3])
print(nums[:3])

如果为末尾结束,可以省略结尾索引

1
2
3
4

nums = [0, 1, 2, 3, 4, 5, 6]
# 获取从索引2开始
print(nums[0:3])
print(nums[:3])

索引正序和倒序

索引分为正序和倒序, 正序自左至右,从0开始;倒序自右至左,从-1开始。

需求: 获取列表前3个元素.

hl_lines

1
2
3
4
5

nums = [0, 1, 2, 3, 4, 5, 6]
# 方式一
print(nums[0:3])
# 方式二
print(nums[0:-4])

步长为负数

步长为负数时,代表反向切片.

需求: 获取列表中从下标为2开始的3个元素,要求倒序输出.

1
2

nums = [0, 1, 2, 3, 4, 5, 6]
print(nums[4:1:-1])

集合set

Python的集合与列表类似,也是容器的一种,不同之处在于:

  • 列表是有序的 , 集合是无序的
  • 列表的元素可以重复集合的元素不可以重复

集合的类型为set, 用一对{} 表示,中间用,分隔

1
2
3

names = { 'itcast', 'itheima', 'bxg'}
print(names)
print(type(names))

集合长度

1
2

names = { 'itcast', 'itheima', 'bxg'}
print(len(names))

通过len函数获得列表的长度

添加元素

1
2
3

names = { 'itcast', 'itheima', 'bxg'}
names.add('czxy')
print(names)

删除元素

删除指定元素, 没有时报错

1
2
3

names = { 'itcast', 'itheima', 'bxg'}
names.remove('itheima')
print(names)

删除指定元素, 没有时不做任何操作,不报错

1
2
3

names = { 'itcast', 'itheima', 'bxg'}
names.discard('itheima')
print(names)

随机删除元素

1
2
3

names = { 'itcast', 'itheima', 'bxg'}
names.pop()
print(names)

字典

字典(dictionary) 和列表从功能角度而言,都是一个装数据的容器.

  • 字典可以存储多个数据。
  • 字典采用 键值对 方式存储数据
  • 字典没有索引,是无序的
  • 字典的键是唯一的

字典的类型为’dict’, 用一对’{}’包裹, 每一组元素采用,分隔,一组元素包含keyvalue,keyvalue采用: 分隔。

1
2
3

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
print(d)
print(type(d))

字典长度

1
2

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
print(len(d))

通过len函数获得字典元素的数量

访问元素

1
2

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
print(d['name'])

增加和修改

1
2
3
4

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
d['name'] = 'itheima'
d['address'] = 'sz'
print(d)

!!!note
不存在key就是添加。存在就是修改

删除

del删除

1
2
3

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
del d['name']
print(d)

pop删除

1
2
3
4

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
value = d.pop('name')
print(d)
print(value)

pop删除时会将删除元素的value返回

clear清空

1
2
3

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
d.clear()
print(d)

复杂数据结构

字典可以描述复杂的数据结构.

例如,我们描述一个学生可以这个样子:

1

stu = { 'name': 'itcast', 'age': 10, 'gender': True}

我们描述多个个学生,用学生的名字做唯一标识

1
2
3
4
5

stus = {
    'itcast': { 'age': 10, 'gender': True},
    'itheima': { 'age': 12, 'gender': True},
    'bxg': { 'age': 14, 'gender': False},
}

条件判断

if语句

代码格式:

1
2

if 条件:
    条件成立时,要做的事情

示例:

1
2
3

if 1 < 2:
    print("1 < 2")
print('hello')

if…else…语句

代码格式:

1
2
3
4

if 条件:
    条件成立时,要做的事情
else:
    条件不成立时,要做的事情

示例:

1
2
3
4

if 1 < 2:
    print("ok")
else:
    print("not ok")

if…elif…else语句

代码格式:

1
2
3
4
5
6
7
8

if 条件1:
    条件1成立时,要做的事情
elif 条件2:
    条件2成立时,要做的事情
elif 条件3:
    条件3成立时,要做的事情
else:
    以上条件都不满足时,要做的事情

示例:

1
2
3
4
5
6

if 1 > 2:
    print("logic if")
elif 1 > 3:
    print("logic elif")
else:
    print("logic else")

一些案例

input输入函数

input函数,可以帮助我们的程序接收外部提供的数据,一个阻塞式的代码

1
2

age = input('请输入年龄')
print(age)

if…else案例

需求:

  1. 输入用户年龄
  2. 判断是否满 18 岁 (>=)
  3. 如果满 18 岁,允许进网吧嗨皮
  4. 如果未满 18 岁,提示回家写作业

1
2
3
4
5
6

age = int(input('请输入你的年纪:'))
# if判断
if age>=18:
    print('允许进网吧嗨皮')
else:
    print('回家写作业')

if…elif…else案例

需求:
需求

  1. 定义 holiday 字符串变量记录节日名称
  2. 如果是 情人节 应该 买玫瑰/看电影
  3. 如果是 平安夜 应该 买苹果/吃大餐
  4. 如果是 生日 应该 买蛋糕
  5. 其他的日子每天都是节日啊……

1
2
3
4
5
6
7
8
9

holiday = input('请输入节日名称')
if holiday == '情人节':
    print('买玫瑰/看电影')
elif holiday == '平安夜':
    print('买苹果/吃大餐')
elif holiday == '生日':
    print('买蛋糕')
else:
    print('每天都是节日,每天一个红包')

嵌套案例

需求:

  1. 定义布尔型变量 has_ticket 表示是否有车票
  2. 定义整型变量 knife_length 表示刀的长度,单位:厘米
  3. 首先检查是否有车票,如果有,才允许进行 安检
  4. 安检时,需要检查刀的长度,判断是否超过 20 厘米
    果超过 20 厘米,提示刀的长度,不允许上车
    如果不超过 20 厘米,安检通过
  5. 如果没有车票,不允许进门

1
2
3
4
5
6
7
8
9
10
11
12
13

has_ticket = input("请输入是否有车票:")
# 0 没有 1 有
has_ticket = int(has_ticket)
knife_length = input("请输入刀的长度:")
knife_length = int(knife_length)

if bool(has_ticket):
    if knife_length>20:
        print("不能进站")
    else:
        print("可以进站")
else:
    print("不能进站")

in和not int

innot int是python的操作符,用来判断元素释放在容器中,如果在,返回True,否则False。

这里的容器包含了我们前面学习的列表list,元组tuple,集合set,字典set以及字符串str

字符串

1
2

str = 'itcast'
print('it' in str)

列表

1
2

names = ['itcast', 'itheima', 'bxg']
print('itheima' in names)

元组

1
2

names = ('itcast', 'itheima', 'bxg')
print('itheima' in names)

集合

1
2

names = { 'itcast', 'itheima', 'bxg'}
print('itheima' in names)

字典

字典中,in 和 not in主要用来判断 字典的键

1
2
3

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
print('name' in d)
print('age' in d)

while循环语法

1
2

while 条件:
    循环逻辑代码

死循环

死循环在程序中有一定的使用场景,可以保证程序不会停止。

1
2
3
4
5

import time

while True:
    print('hello itcast')
    time.sleep(1)

!!!note
time是python系统内置的模块,提供时间操作相关的api。

`time.sleep`可以帮助睡眠

循环变量

可以通过变量来控制循环

1
2
3
4
5
6
7
8

# 1.定义循环变量
i = 0
# 2.使用while判断条件
while i < 10000:
    # 要重复执行的代码
    print('媳妇儿,我错了')
    # 3.修改循环变量
    i += 1

break和contiune

  • break: 某一条件满足时,不再执行循环体中后续重复的代码,并退出循环。
  • continue: 某一条件满足时,不再执行本次循环体中后续重复的代码,但进入下一次循环判断.

break示例:

1
2
3
4
5
6

i = 0
while i < 5:
    if i == 3:
        break # 5后面的数据都不会输出
    print(i)
    i += 1

contiune示例:

1
2
3
4
5
6

i = 0
while i < 5:
    i += 1
    if i-1 == 3:
        continue # 除了3都会输出
    print(i-1)

嵌套循环

while 里面还有 while

1
2
3
4
5

while 条件1:
    ......
    while 条件2:
        ......
    ......

示例代码:

1
2
3
4
5
6
7
8
9

# 外层循环
i = 0
while i < 5:
    # 内层循环
    j = 0
    while j<3:
        print(j)
        j+=1
    i += 1

for循环语法

for循环的主要作用是遍历数据(容器)中的元素 字符串、列表等高级数据类型都属于容器,都可以通过for循环遍历.

for循环的语法格式如下:

1
2

for 临时变量 in 列表或者字符串等可迭代对象:
    执行的代码

遍历操纵

字符串

1
2
3
4

str = 'itheima'
# ele普通变量  接收容器中的元素
for ele in str:
    print(ele)

遍历列表元组集合

1
2
3

names = ['itcast', 'itheima', 'bxg']
for name in names:
    print(name)

遍历字典

字典遍历过程中,获得的是字典的键.

1
2
3

d = { 'name': 'itcast', 'age': 10, 'height': 1.75, 'gender': True}
for key in d:
    print("key = {}, value = {}".format(key, d[key]))

range区间

range是一个内置的函数,可以自动帮我们创建 整数列表.

语法格式为:

1

range(start, end, step)

!!!note

* `start`为起始值

* `end`为结束值

* `step`为步长

意思为,创建一个从`start`开始,间隔`step`,一直到`end`结束的列表

**包含start,不包含end**

1
2

arr = range(1, 10, 2)
print(arr)

步长为1

步长为1时,可以省略

1
2

arr = range(1, 10)
print(arr)

起始值为0,步长为1

起始值为0,步长为1,起始值可以省略,步长也可以省略

1
2

arr = range(10)
print(arr)

遍历range

1
2

for num in range(0, 10, 2):
    print(num)

函数

函数是程序非常重要的组成部分,是计算机执行命令的单元.

所谓函数,就是把 具有独立功能的代码块 组织为一个整体,在需要的时候 调用.

使用函数可以提高编写的效率以及 代码的重用.

函数的使用包含两个部分:

  • 定义函数: 在函数中编写代码,实现功能
  • 调用函数: 执行编写的代码

函数定义格式

1
2

def 函数名():
    函数封装的代码

!!!note
def时英文define的缩写,意为声明

`函数名`是根据自己的业务来取的,和变量命名规则相同。

函数调用格式

1

函数名()

第一个函数

需求:

  1. 编写一个打招呼 say_hello 的函数,封装三行打招呼的代码
  2. 在函数下方调用打招呼的代码

1
2
3
4
5
6
7
8

# 定义函数
def say_hello():
    print('hello itcast')
    print('hello itheima')
    print('hello bxg')

# 调用函数
say_hello()

函数的参数

函数的参数,可以传递数据给函数内部 参数的作用是增加函数的 通用性.

定义和调用格式:

1
2
3
4
5
6

# 定义函数
def 函数名(参数1,参数2):
    函数代码

# 调用函数
函数名(参数1,参数2)

需求:

  • 定义函数,传递a和b,求a+b的和

1
2
3
4
5
6

def sum(a,b):
    result = a + b
    print(result)

# 调用
sum(10,20)

函数返回值

定义和调用格式:

1
2
3
4
5
6
7

# 定义函数
def 函数名(参数1,参数2):
    函数代码
    return 返回值

# 调用函数
返回值 = 函数名(参数1,参数2)

需求:

  • 定义函数返回两个数最大值

1
2
3
4
5
6
7
8
9

# 定义函数
def max_value(a,b):
    if a > b:
        return a
    else:
        return b

# 调用函数
v = max_value(10,20)

多返回值

python函数可以返回多个结果

需求:

  • 计算两个数的加和减

1
2
3
4

def cacl(a, b):
    sum = a + b
    result = a-b
    return sum,result

局部变量和全局变量

局部变量

  • 局部变量,指的是在函数内部定义的变量
  • 局部变量的目的是存储需要临时保存的数据

1
2
3
4

def func1():
    # 局部变量
    b = 20
    print('hello %d' % b)

全局变量

  • 全局变量是在整个py文件中声明,全局范围内都可以访问

1
2
3
4
5
6
7

# 全局变量
m = 10
n = 20

def func():
    # 函数内访问全局变量
    print(m)

函数内修改全局变量

1
2
3
4
5
6
7
8
9

# 定义全局变量
m = 10

def func():
    # 使用global声明全局变量
    global m
    # 将m修改成20
    m = 30
    print('函数内部m = %d' % m)

函数注释

函数名并不能完全的表示出函数的含义,定义函数的时候就需要给函数加上注释

函数的注释就是文档注释

注释的规则和格式如下:

  • 注释应该定义在函数的下方
  • 使用三对引号注释

1
2
3
4
5
6

def say_hello():
    '''
    说hello的函数
    :return:
    '''
    print('hello itcast')

类的定义

  • 属性(变量)
  • 函数

1
2
3
4
5
6

class MyClass:
    def __init__(self):
        self.name = 'itcast'
    
    def say_hello(self):
        print('hello')

!!!note
class为关键字,用来声明一个类

`__init__`是构造函数,构造函数也是函数,是一个具体实例对象创建时默认调用的函数。

`self`表示当前创建实例对象本身

类中的函数,有个特点,默认第一个参数都是`self`

对象

  • 类是一种模板模型
  • 对象是这个类的具体实现

!!!tip
狗和旺财,哪一个是类?哪一个是对象?

狗是一种类型,属于模板

旺财是狗的实现,属于具体的,具体的就是对象

类的使用

类的使用,其实就是将类具体化,获得对象,然后使用对象的属性和方法

1
2
3
4
5
6
7

class Car:
    def __init__(self):
        self.speed = 10
        self.x = 0

    def move(self):
        self.x += self.speed

!!!note
self.speed是属性,用来记录数据的

`self.x`是属性,用来记录数据的

`move`是函数,是一种行为,行为的变化会产生数据的变化

整个对象,其实就是维护状态数据的。

以上就是python基础知识的整理

创作不易,看到最后的小伙伴们,动动你们发财的手指点个赞支持一下

Guess you like

Origin blog.csdn.net/m0_64892604/article/details/129868904