返回顶部

python可变不可变数据类型, if 流程控制

一.可变不可变数据类型

# 可变不可变类型
# 可变类型: 值改变, id不变, 证明改的原值, 证明原值是可以被改变的
# 不可变类型: 值改变, id也变了, 证明是产生新的值, 压根没有改变原来的值, 证明原值是不可以被改变的
  • 不可变数据类型
    • int, str, float, bool
  • 可变数据类型
    • list
    • 字典(key必须是不可变数据类型, value可以是任意数据类型)
# 验证
# int是不可变数据类型
# x = 10
# print(id(x))
# x = 11  # 赋值, 是产生了新的值
# print(id(x))

# float 是不可变类型
# x = 1.1
# print(id(x))
# x = 1.2  # 赋值, 产生新的值
# print(id(x))

# str字符串也是不可以改变类型
# 小结: int, float, str 都设计成了不可分割的整体, 不能够被改变

# list列表时可变类型  改变list其中一个元素, 整个列表的内存地址是不变的
# l =[111, 222, 333]
# print(id(l))
# l[1] = 'qwe'
# print(id(l))

# dict字典 是可变类型
# dic = {'name': '八戒', 'age': 19}
# print(id(dic))
# dic['name'] = '悟空'
# print(id(dic))

# bool 是不可变类型

# 字典: 在字典中, key必须是不可变数据类型, value可以是任意数据类型

二.条件

  • 显式布尔值:True、False
  • 隐式布尔值:所有数据类型,其中0、None、空为假

三.逻辑运算符 not and or(not>and>or)

# not and or 的基本使用
# 1 not: 后面的那个条件取反

# print(not True)
# print(not 0)
# print(not 10)
# print(not None)
# print(not {})
# print(not [])
# print(not '')
# print(not '   ')  # 空格也是字符 取反是False

# 2 and: 逻辑与 and用来链接左右两个条件, 两个条件同时为True, 则为真, 否则为false
print(False and 1 < 2)  # False


# 3 or: 逻辑或, or来链接左右两个条件, 两个条件但凡有个为True, 则为真, 否则为false
print(0 or 1 > 2)  # false
print(None or True)  # true
print('' or True)  # true

# 优先级: not>and>or

四.成员运算符(in) 身份运算符(is)

# 1、成员运算符
# print("word" in "hello word") # 判断一个字符串是否存在于一个大字符串中
# print("e" in "hello word") # 判断一个字符串是否存在于一个大字符串中

# print(111 in [111,222,33]) # 判断元素是否存在于列表

# 判断key是否存在于字典
# print(111 in {"k1":111,'k2':222})
# print("k1" in {"k1":111,'k2':222})

# not in
# print("word" not in "hello word") # 推荐使用
# print(not "word" in "hello word") # 逻辑同上,但语义不明确,不推荐

# 2、身份运算符
# is # 判断的是id是否相等

五.if流程控制

语法:
'''
语法3:
if 条件1:
    代码1
    代码2
    代码3
elif 条件2:
    代码1
    代码2
    代码3
elif 条件2:
    代码1
    代码2
    代码3
...
else:
    代码1
    代码2
    代码3
'''
# score = input('请输入您的成绩:') # score="18"
# score=int(score)
#
# if score >= 90:
#     print('优秀')
# elif score >= 80:
#     print('良好')
# elif score >= 70:
#     print('普通')
# else:
#     print('很差,小垃圾')
#
# print('=====>')

六.if的嵌套

age = 17
is_beautiful = True
star = '水平座'

if 16 < age < 20 and is_beautiful and star == '水平座':
    print('开始表白。。。。。')
    is_successful = True
    if is_successful:
        print('成功了。。。')
else:
    print('抱歉,不合适.....')

print('其他代码.............')
posted @ 2022-06-24 16:32  fuju  阅读(43)  评论(0)    收藏  举报