扩大
缩小
人生本来就短暂,为什么还要栽培苦涩。
返回顶部

python 快速入门(变量,八大数据类型,if嵌套 ,for循环,while循环)

python 快速入门基础知识(二)

python解释器:

- 将人类编写好的代码转成机器能看得懂的字符。- 
解释器的作用:    帮你执行python代码。

pycharm编辑器:

- 编辑器的作用:    可以更好的编写python代码,编辑器内部有很多强大的功能。    能够快速编写代码。

字符编码

结论: 以什么编码,就以什么解码。

        utf-8:
            - 存中文是3个字节。
            - 存英文是1个字节

        gbk:
            - 存中文是2个字节。
            - 存英文是2个字节

执行python程序的两种方式

交互式

写一行解释一行

命令行式

python 文件.py

变量

什么是变量

描述世间万物变化的状态(指可变化的量)

变量的组成

变量名:可以与变量值绑定关系,通过变量名可以访问变量值

赋值符号(=): 是用来将变量名与变量值绑定关系。

变量值: 变量值 指的是 “数据”, 存放在内存中。

变量名(描述;接收变量值)= 变量值(一个具体的值)

变量名的命名规范

  1. 具有描述意义
  2. 只能由数字/字母/下划线组成,不能以数字开头
  3. 不能用python关键字

变量名的两种定义方式

  1. 下划线(推荐)
比如: JasonSb
  1. 驼峰体
比如: jason_sb

常量

常量只是约定俗成的不能变化,其实是可以变化的

python变量内存管理

引用计数(变量值)

变量值的引用次数加1,则引用计数加1

垃圾回收机制

GC: 就是用来做垃圾回收机制的。

当变量值的引用计数为0的时候,自动触发垃圾回收机制,释放变量值的内存占用

c --> free()

小整数池

针对[-5,256]之间的整数,python会在python启动的时候就会自动分配内存地址

虚拟地址() --》 硬盘(物理地址)

变量的三种打印方式

  1. 打印变量值
  2. 打印变量内存地址
  3. 打印变量的数据类型

查看变量三大特征:

- id
- type
- value

数字类型

整型 int

使用方法:+-*/ % // **

import cmath

浮点型 float

使用方法:+-*/ % // **

import cmath

字符串 str

定义方式:单(双)引号内的一串字符,三单(双)引号内的字符可以换行

使用方法:+ *

# 强制类型转换 --》 动态语言
str(10)  --> 字符串的10
int('10') --> 整型的10
float('10') --> 浮点型的10.0

# 不可以强制类型转换 --》 静态语言

花式赋值

链式赋值

a = b = c = 10

交叉赋值

x = 10
y = 20

x, y = y, x

列表list

[]内用逗号隔开多个元素(任意数据类型)

索引取值:索引从0开始,从-1开始

字典dict

dic = {'a':1}

{}内用逗号隔开多个键(一般为字符串(不可变类型))值(任意数据类型)对

按key取值

布尔值(bool)

所有数据类型都自带布尔值,0/None/空(空字符串/空列表/空字典)/False自带布尔值为False,其他均为True

解压缩

一次性取多个值,如果某一个值不要,就用_表示

lt = [1,2,3]
s1,s2,s3 = lt
print(s1,s2,s3)

python与用户的交互

input()

  1. 暂停程序
  2. 接收用户的输入
  3. 接收的所有数据都为字符串

三种格式化输出方式

f-string

f'{name}'

占位符

'%s'%(name)

format

'{}'.format(name)

基本运算符

算术运算符

+ - * / // % **

逻辑运算符

1. and 两边都为True,则为True
2. or 一边为True,则为True
3. not 否定

比较运算符

< <= > >= == !=

身份运算符

1. is 比较内存地址
2. is not

成员运算符

1. in 判断元素是否存在容器类元素内部(包括字符串)
2. not in

赋值运算符

= += -= *= /= **= %= //=

x += 10 # x = x + 10

位运算符

111 000
&
011 100

011 000

& 都为1则为1,否则为0

运算符的优先级

优先级: 要优先的加个括号就行了

流程控制之if判断

单分支结构

if 条件:
	代码块
cls = 'human'
gender = 'female'
age = 18

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('开始表白')

print('end...')
#
开始表白
end...

双分支结构

if 条件:
	代码块 条件成立走这个
else:
    代码块 条件不成立走这个

cls = 'human'
gender = 'female'
age = 38

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('开始表白')
else:
    print('阿姨好')

多分支结构

if 条件:
	代码块 条件成立走这个
elif 可以有多个
else:
    代码块 条件不成立走这个
    
cls = 'human'
gender = 'female'
age = 28

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('开始表白')
elif cls == 'human' and gender == 'female' and age > 22 and age < 30:
    print('考虑下')
else:
    print('阿姨好')

if 嵌套

if
if

cls = 'human'
gender = 'female'
age = 18
is_success = False

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('开始表白')
    if is_success:
        print('那我们一起走吧...')
    else:
        print('我逗你玩呢')
else:
    print('阿姨好')
    
开始表白
我逗你玩呢

流程控制之while循环

while True:
    user_db = 'nick'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
    else:
        print('username or password error')

while + break

break : 中断循环。

while True:
    user_db = 'nick'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        break
    else:
        print('username or password error')

print('退出了while循环')

#
username: nick
password: 123
login successful
退出了while循环

while + continue

continue: 退出本次循环,不执行下面的代码,进行下一次循环。

n = 1
while n < 10:
    if n == 8:
        # n += 1  # 如果注释这一行,则会进入死循环
        continue
    print(n)
    n += 1

while + else

else: 不被break中断就执行else缩进下的代码。

n = 1
while n < 3:
    print(n)
    n += 1
else:
    print('else会在while没有被break时才会执行else中的代码')
#
1
2
else会在while没有被break时才会执行else中的代码

tag控制while退出

while tag(count < 3):
    pass

while嵌套

while

​	while

while True:
    user_db = 'nick'
    pwd_db = '123'

    inp_user = input('username: ')
    inp_pwd = input('password: ')

    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')

        while True:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                break
            print(f'{cmd} 功能执行')
        break
    else:
        print('username or password error')

print('退出了while循环')

username: nick
password: 123
login successful
请输入你需要的命令:q
退出了while循环

流程控制之for循环

info = {'name': 'nick', 'age': 19}

for item in info:
    # 取出info的keys
    print(item)
#
name
age

for + break

break: 中断循环。

name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    if name == 'jason':
        break
    print(name)
    
# nick

for + continue

continue: 跳出本次循环,不执行下面代码,开始下一次循环。

name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    if name == 'jason':
        continue
    print(name)
#
nick
tank
sean

for + else

else : 没有被break掉,就执行else缩进下的代码

name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    print(name)
else:
    print('for循环没有被break中断掉')
#   
nick
jason
tank
sean
for循环没有break中断掉

for循环嵌套

for i in range(1,10):
    for j in range(i):
        print(....)
    print()

python中的八大数据类型 tank

八大数据类型

int  : 整型
float: 浮点型
str  : 字符串
list : 列表
tuple :元组
dict : 字典
set  : 集合
bool :布尔类型

八大数据类型使用方法及特征

 - int:
            number = 100  # number = int(100)
            - 不可变类型

        - float
            salary = 1.0  # salary = float(1.0)
            - 不可变类型

        - str
            str1 = 'tank'  # str1 = str('tank')
            - 不可变类型
            # 按照索引取值
            str1[1]  # 取第二个值
            str1[1:10:2]  # 顾头不顾尾

            # 内置方法
            str1.split()  # 切分
            str1.strip()  # 去左右两边的空格
            str1.strip('i')  # 去左右两边的i
            # tank10
            str1.join(['tank', '10'])  # 字符串的拼接,必须是字符串类型
            # 判断字符串开头,若正则返回True,否则返回False
            str.startswith()
            # 判断字符串结尾,若正则返回True,否则返回False
            str.endswith()
            # 判断字符串是否是数字,若正则返回True,否则返回False
            str.isdigit()
            # 新旧替换
            str.replace('旧的', '新的')
            # 获取某个字符的数量
            str.count('字符')

            # 查找字符的位置  索引   可能是面试题
            str.find('字符')  # 找不到返回-1
            str.index('字符')  # 找不到报错

        - list
            在[]内,可以存放多个值,每个值以逗号隔开。
            list([v1, v2..])
            - 可变类型

            - 常用内置方法:
                list.append()  # 追加
                list.insert()  # 插入值到指定的索引中
                list.pop()  # 取出某个值,默认取出最后一个
                list.remove()  # 真正的删除元素
                list.extend()  # 列表合并
                list.sort(reverse=True)  # 默认升序 , reverse=True降序
                list.copy()  # 浅拷贝


        - tuple
            tuple((v1, v2...))
            - 不可变类型

        - dict
            特点: key是唯一的。
            dict({key:value, ...})
            - 可变类型
            dict[key]  # 没有key会报错
            dict.get(key, '自定义默认值')  # 没有key会报错,默认返回None
            dict.items()  # 返回一个可迭代对象
            dict.keys()
            dict.values()
            dict.fromkeys('k1', [])  # 生成字典 ---》 {'k1': []}

        - set
            特点: 内置去重功能。
            set({v1, v2...})
            - 默认可变类型

            # 内置方法
            set.add()
            set.remove()

        - bool:
            True or False
            - 不可变类型

        什么是可变?
            值变了,id不变称之为可变类型。

        什么是不可变?
            值变了,id也变 称之为不可变类型。

可变 or 不可变

 什么是可变?
            值变了,id不变称之为可变类型。

        什么是不可变?
            值变了,id也变 称之为不可变类型。

数字类型内置方法 nk

整型

浮点型

字符串内置方法

优先掌握

1. 索引取值
2. 索引切片
3. for循环
4. 成员运算
5. len长度
6. strip
7. split

需要掌握

1. rstrip/lstrip
2. rsplit
3. lower/upper
4. startswith/endswith
5. isdigit/isalpha

了解

1. find/rfind/index/rindex/count
2. center/ljust/rjust/zfill
3. expandtabs
4. capital/swapcase/title
5. is系列

列表内置方法

优先掌握

1. 索引取值/索引修改值
2. 索引切片
3. for循环
4. 成员运算
5. len长度
6. append
7. del 删除某一个元素

需要掌握

1. sort
2. reverse
3. pop
4. remove
5. index
6. insert
7. extend
8. copy
9. clear

有序or无序

有索引,有序;无索引,无序

可变or不可变

可变:值变id不变

不可变:值变id变化

元组内置方法

不可更改的列表,其他的和列表一模一样

散列表

![](D:\上海python12期视频\python12期视频\day 08\03 散列表(哈希表).png)

  1. 乱序
  2. 不可重复的
  3. key不能为可变数据类型

字典内置方法

  1. 乱序 --》 python2中字典是乱序的,但是python3做了优化(本来是乱序的,但是在c这个层面做了不乱序的优化)。
  2. key为什么是不可变的,假设key是可变的,

[key]可以取值,也可以修改值

get 获取值,没有默认None

setdefault 有就不修改,没有就增加

集合内置方法

  1. 去重 --》同样的值存的位置是一样的,拿到第一个就不会拿到第二个
  2. 乱序 --》插值是按照某种哈希算法随机插的
  3. 进行数学集合运算
    1. 交集 &
    2. 并集 |
    3. 差集 -
    4. 补集 ^
add 添加

remove 删除

discard 删除

深浅拷贝

拷贝:

拷贝:(你变我也变,如你添加函数值,我也跟着添加)

当l2为l1的拷贝对象,l1变换,l2变化

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = l1
l1.append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']

浅拷贝

浅拷贝:(你的可变数据类型变化,我才跟着变化)

当l2为l1的浅拷对象,l1内部不可变数据类型变化,l2不变;l1内部可变数据类型变化,l2变

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.copy(l1)

l1.append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
l1[3].append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f', 'g']]

深拷贝

​ 深拷贝:(不管你怎么变,我就是不变)

当l2为l1的深拷贝对象,l1内部变化,l2不变

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.deepcopy(l1)

l1.append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]
l1[3].append('g')

print(l1)
['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)
['a', 'b', 'c', ['d', 'e', 'f']]

posted @ 2019-11-28 09:40  晴天sky  阅读(380)  评论(0编辑  收藏  举报
左边日期 搜索的制定样式