python基本变量和操作

文章目录

对变量的基本操作

如何查看变量类型?

type检测变量类型

如何将变量的类型强制转化?

在这里插入图片描述

变量基本运算符的优先级顺序

运算优先级从上到下

不同逻辑结构

分类讨论(分支)

elif(即相当于C/C++里面的else if)

连续做相同操作(循环)

for num in range(1,10):

# python喜欢用左闭右开的结构,range相当于1-9
for _ in range(2):
#重复两次操作

特殊变量:字符串

如何用一个变量储存多行字符串?

s3 = '''
hello, 
world!
'''
print(s3, end='')

如何取消print()的默认换行输出

print(s3, end=’’)
print函数中的end=’‘表示输出后不换行,即将默认的结束符\n(换行符)更换为’’(空字符)。

如何输出’Hello,world!'类型的字符串

1、(使用转义符号\)

s1 = '\'hello, world!\''
print(s1)
#'hello,world'

2、在字符串前加小写r

# 字符串s1中\t是制表符,\n是换行符
s1 = '\time up \now'
print(s1)
# 字符串s2中没有转义字符,每个字符都是原始含义
s2 = r'\time up \now'
print(s2)
#	ime up 
#ow
#\time up \now

字符串的运算

如何把两个字符串拼起来
s1 = 'hello' + ' ' + 'world'
print(s1)    # hello world
如何重复输出一个字符串

1、for循环
2、*操作

s2 = '!' * 3
print(s2)    # !!!
如何确定变量的地址是否相同?(一般什么情况下需要确认地址?)
s1 = 'hello world'
s2 = 'hello world'
s3 = s2
# 比较字符串的内容
print(s1 == s2, s2 == s3)    # True True
# 比较字符串的内存地址
print(s1 is s2, s2 is s3)    # False True
如何确定一个字符串是否包含某个字符子串?(作业包括,文献查找?)
s1 = 'hello, world'
print('wo' in s1)    # True
s2 = 'goodbye'
print(s2 in s1)      # False
如何截取字符子串

s[a: b : s]
a:开始位置
b:结束位置
s:步长

如何遍历字符串

1、

s1 = 'hello'
for ch in s1:
    print(ch)

2、用索引

s1 = 'hello'
for index in range(len(s1)):
    print(s1[index])
如何将其他形式的变量用字符串形式输出
a = 321
b = 123
print(f'{a} * {b} = {a * b}')
能不能通过字符串的索引改变其中的字符内容?

注意:
字符串是不可变类型,所以不能通过索引运算修改字符串中的字符

s1 = 'fack'
s1[1] = 'u'

print(s1)
#TypeError: 'str' object does not support item assignment

容器(相当于一个类):列表list

通过生成式创建列表

# 创建一个由1到9的数字构成的列表
items1 = [x for x in range(1, 10)]
print(items1)    # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 创建一个由'hello world'中除空格和元音字母外的字符构成的列表
items2 = [x for x in 'hello world' if x not in ' aeiou']
print(items2)    # ['h', 'l', 'l', 'w', 'r', 'l', 'd']

# 创建一个由个两个字符串中字符的笛卡尔积构成的列表
items3 = [x + y for x in 'ABC' for y in '12']
print(items3)    # ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']

拼接、重复、成员运算、索引和切片以及比较运算(类似字符串)

和数组类似,不过list可以放入的变量类型不限于单个字符或者整数,什么都可以放,因此相当方便

items1 = [35, 12, 99, 68, 55, 87]
items2 = [45, 8, 29]

# 列表的拼接
items3 = items1 + items2
print(items3)    # [35, 12, 99, 68, 55, 87, 45, 8, 29]

# 列表的重复
items4 = ['hello'] * 3
print(items4)    # ['hello', 'hello', 'hello']

# 列表的成员运算
print(100 in items3)        # False
print('hello' in items4)    # True

# 获取列表的长度(元素个数)
size = len(items3)
print(size)                 # 9

# 列表的索引
print(items3[0], items3[-size])        # 35 35
items3[-1] = 100
print(items3[size - 1], items3[-1])    # 100 100

# 列表的切片
print(items3[:5])          # [35, 12, 99, 68, 55]
print(items3[4:])          # [55, 87, 45, 8, 100]
print(items3[-5:-7:-1])    # [55, 68]
print(items3[::-2])        # [100, 45, 55, 99, 35]

# 列表的比较运算
items5 = [1, 2, 3, 4]
items6 = list(range(1, 5))
# 两个列表比较相等性比的是对应索引位置上的元素是否相等
print(items5 == items6)    # True
items7 = [3, 2, 1]
# 两个列表比较大小比的是对应索引位置上的元素的大小
print(items5 <= items7)    # True

如何在list里添加元素

items = ['Python', 'Java', 'Go', 'Kotlin']

# 使用append方法在列表尾部添加元素
items.append('Swift')
print(items)    # ['Python', 'Java', 'Go', 'Kotlin', 'Swift']
# 使用insert方法在列表指定索引位置插入元素
items.insert(2, 'SQL')
print(items)    # ['Python', 'Java', 'SQL', 'Go', 'Kotlin', 'Swift']

如何删除指定元素,删除指定位置元素,以及删除连续的一行元素

items = ['Python', 'Java', 'Go', 'Kotlin']
# 删除指定的元素
items.remove('Java')
print(items)    # ['Python', 'Go', 'Kotlin']
# 删除指定索引位置的元素
items.pop(0)
print(items)    # ['Go', 'Kotlin']
del items[1]
print(items)    # ['Go']
del items[0:2]  # ['Go', 'Kotlin']

如何查找元素位置

items = ['Python', 'Java', 'Java', 'Go', 'Kotlin', 'Python']

# 查找元素的索引位置
print(items.index('Python'))       # 0
print(items.index('Python', 2))    # 5
# 注意:虽然列表中有'Java',但是从索引为3这个位置开始后面是没有'Java'的
print(items.index('Java', 3))      # ValueError: 'Java' is not in list

如何计算某个元素在list里面的个数

items = ['Python', 'Java', 'Java', 'Go', 'Kotlin', 'Python']

# 查找元素出现的次数
print(items.count('Python'))    # 2
print(items.count('Go'))        # 1
print(items.count('Swfit'))     # 0

如何对列表元素排序和反转

items = ['Python', 'Java', 'Go', 'Kotlin', 'Python']

# 排序
items.sort()
print(items)    # ['Go', 'Java', 'Kotlin', 'Python', 'Python']
# 反转
items.reverse()
print(items)    # ['Python', 'Python', 'Kotlin', 'Java', 'Go']

如何改变list里的所有元素的数据类型

# 把 x 中的变量类型由字符串变为 int
x = [ '1', '2', '3' ]
x = list(map(int, x))

如何判断某个元素在或者不在list里

str = ['s','i','m','o','n']
if('e' in str):
    print("e in str")
if('e' not in str):
    print('e not in str')

如何同时生成元素和元素下标的list

enumerate(list)
注:python内置函数

元组(tuple)

tuple与list的不同之处

元组和列表的不同之处在于,元组是不可变类型(可以放一些不可变量)

如何创建tuple?

# 定义一个三元组
t1 = (30, 10, 55)
# 定义一个四元组
t2 = ('骆昊', 40, True, '四川成都')

如何创建一元组

# 不是元组
b = ('hello')
print(type(b))    # <class 'str'>
# 一元组
d = ('hello', )
print(type(d))    # <class 'tuple'>

如何将元组的值分别给不同的变量?

当我们把多个用逗号分隔的值赋给一个变量时,多个值会打包成一个元组类型;当我们把一个元组赋值给多个变量时,元组会解包成多个值然后分别赋给对应的变量

# 打包
a = 1, 10, 100
print(type(a), a)    # <class 'tuple'> (1, 10, 100)
# 解包
i, j, k = a
print(i, j, k)       # 1 10 100

注意:
解包语法对list也都成立

元组的值分给不同变量,分配的变量的个数少于元组的值,应该怎么办?

加*号(其实就是引用地址)

a = 1, 10, 100, 1000
i, j, *k = a
print(i, j, k)          # 1 10 [100, 1000]

元组和列表如何相互转换?

# 将元组转换成列表
info = ('骆昊', 175, True, '四川成都')
print(list(info))       # ['骆昊', 175, True, '四川成都']
# 将列表转换成元组
fruits = ['apple', 'banana', 'orange']
print(tuple(fruits))    # ('apple', 'banana', 'orange')

集合

与list、tuple的区别

无序性、互异性

如何构建集合

# 创建集合的字面量语法(重复元素不会出现在集合中)
set1 = {1, 2, 3, 3, 3, 2}
print(set1)         # {1, 2, 3}

# 创建集合的构造器语法
set2 = set('hello')
print(set2)         # {'h', 'l', 'o', 'e'}
# 将列表转换成集合(可以去掉列表中的重复元素)
set3 = set([1, 2, 3, 3, 2, 1])
print(set3)         # {1, 2, 3}

集合中的元素必须是hashable类型。

什么是hashable类型?

所谓hashable类型指的是能够计算出哈希码的数据类型,你可以暂时将哈希码理解为和变量对应的唯一的ID值。

通常不可变类型都是hashable类型,如整数、浮点、字符串、元组等,而可变类型都不是hashable类型,因为可变类型无法确定唯一的ID值,所以也就不能放到集合中。

集合本身也是可变类型,所以集合不能够作为集合中的元素,这一点请大家一定要注意。

如何对集合求交集、并集、差集?

set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {2, 4, 6, 8, 10}

# 交集
# 方法一: 使用 & 运算符
print(set1 & set2)        # {2, 4, 6}
# 方法二: 使用intersection方法
print(set1.intersection(set2))  # {2, 4, 6}

# 并集
# 方法一: 使用 | 运算符
print(set1 | set2)         # {1, 2, 3, 4, 5, 6, 7, 8, 10}
# 方法二: 使用union方法
print(set1.union(set2))    # {1, 2, 3, 4, 5, 6, 7, 8, 10}

# 差集
# 方法一: 使用 - 运算符
print(set1 - set2)              # {1, 3, 5, 7}
# 方法二: 使用difference方法
print(set1.difference(set2))    # {1, 3, 5, 7}

# 对称差
# 方法一: 使用 ^ 运算符(相同的去掉,不同的保留,A∪B-A∩B)
print(set1 ^ set2)                        # {1, 3, 5, 7, 8, 10}
# 方法二: 使用symmetric_difference方法
print(set1.symmetric_difference(set2))    # {1, 3, 5, 7, 8, 10}
# 方法三: 对称差相当于两个集合的并集减去交集
print((set1 | set2) - (set1 & set2))      # {1, 3, 5, 7, 8, 10}

集合如何添加删除某个元素?

# 创建一个空集合
set1 = set()
# 通过add方法添加元素
set1.add(33)
set1.add(55)
set1.update({1, 10, 100, 1000})
print(set1)    # {33, 1, 100, 55, 1000, 10}

# 通过discard方法删除指定元素
set1.discard(100)
set1.discard(99)
print(set1)    # {1, 10, 33, 55, 1000}
# 通过remove方法删除指定元素,建议先做成员运算再删除
# 否则元素如果不在集合中就会引发KeyError异常
if 10 in set1:
    set1.remove(10)
print(set1)    # {33, 1, 55, 1000}

如何判断A集合是否为B集合的子集?

set1 = {1, 3, 5}
set2 = {1, 2, 3, 4, 5}
set3 = set2
# <运算符表示真子集,<=运算符表示子集
print(set1 < set2, set1 <= set2)    # True True
print(set2 < set3, set2 <= set3)    # False True
# 通过issubset方法也能进行子集判断
print(set1.issubset(set2))      # True

# 反过来可以用issuperset或>运算符进行超集判断
print(set2.issuperset(set1))    # True
print(set2 > set1)              # True

如何创建不可变集合?

set1 = frozenset({1, 3, 5, 7})

set跟frozenset的区别就如同list跟tuple的区别

字典

创建字典这个类的目的就是通过关键字(而不是list和元组的第几个)找到相关的值

如何创建字典类型?

# dict函数(构造器)中的每一组参数就是字典中的一组键值对
person = dict(name='王大锤', age=55, weight=60, home='中同仁路8号')
print(person)    # {'name': '王大锤', 'age': 55, 'weight': 60, 'home': '中同仁路8号'}

如何将两个列表并成一个字典?

# 可以通过Python内置函数zip压缩两个序列并创建字典
items1 = dict(zip('ABCDE', '12345'))
print(items1)    # {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5'}
items2 = dict(zip('ABCDE', range(1, 10)))
print(items2)    # {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

如何根据关键字(key)遍历/修改字典?

person = {'name': '王大锤', 'age': 55, 'weight': 60, 'office': '科华北路62号'}
print(len(person))    # 4
if 'age' in person:
    person['age'] = 25
# 通过索引操作向person字典中存入新的键值对
person['tel'] = '13122334455'
#直接添加新的键值
for key in person:
    print(f'{key}: {person[key]}')

for key, value in students.items():
    print(key, '--->', value)

字典中的键必须是不可变类型,例如整数(int)、浮点数(float)、字符串(str)、元组(tuple)等类型的值;显然,列表(list)和集合(set)是不能作为字典中的键的,当然字典类型本身也不能再作为字典中的键,因为字典也是可变类型,但是字典可以作为字典中的值。

# 字典中的值是一个字典(嵌套的字典)
students = {
    1001: {'name': '狄仁杰', 'sex': True, 'age': 22, 'place': '山西大同'},
    1002: {'name': '白元芳', 'sex': True, 'age': 23, 'place': '河北保定'},
    1003: {'name': '武则天', 'sex': False, 'age': 20, 'place': '四川广元'}
}

# 使用pop方法通过键删除对应的键值对并返回该值
stu1 = students.pop(1002)
print(stu1)             # {'name': '白元芳', 'sex': True, 'age': 23, 'place': '河北保定'}

# 使用popitem方法删除字典中最后一组键值对并返回对应的二元组
# 如果字典中没有元素,调用该方法将引发KeyError异常
key, value = students.popitem()
print(key, value)    # 1003 {'name': '武则天', 'sex': False, 'age': 20, 'place': '四川广元'}

# setdefault可以更新字典中的键对应的值或向字典中存入新的键值对
# setdefault方法的第一个参数是键,第二个参数是键对应的值
# 如果这个键在字典中存在,更新这个键之后会返回原来与这个键对应的值
# 如果这个键在字典中不存在,方法将返回第二个参数的值,默认为None
result = students.setdefault(1005, {'name': '方启鹤', 'sex': True})
print(result)        # {'name': '方启鹤', 'sex': True}
print(students)      # {1001: {...}, 1005: {...}}

# 使用update更新字典元素,相同的键会用新值覆盖掉旧值,不同的键会添加到字典中
others = {
    1005: {'name': '乔峰', 'sex': True, 'age': 32, 'place': '北京大兴'},
    1010: {'name': '王语嫣', 'sex': False, 'age': 19},
    1008: {'name': '钟灵', 'sex': False}
}
students.update(others)
print(students)      # {1001: {...}, 1005: {...}, 1010: {...}, 1008: {...}}

函数

带默认值和不带默认值的函数变量需要怎么排放顺序?

带默认值的参数必须放在不带默认值的参数之后,否则将产生SyntaxError错误,错误消息是:non-default argument follows default argument,翻译成中文的意思是“没有默认值的参数放在了带默认值的参数后面”。

不确定输入几个输入,如何定义函数自变量?

# 用星号表达式来表示args可以接收0个或任意多个参数
def add(*args):
    total = 0
    # 可变参数可以放在for循环中取出每个参数的值
    for val in args:
        total += val
    return total


# 在调用add函数时可以传入0个或任意多个参数
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))

如何引用别的文件的函数?

一般的用法

import module1

module1.foo()

注意:
如果我们如果从两个不同的模块中导入了同名的函数,后导入的函数会覆盖掉先前的导入.

from module2 import foo
from module1 import foo

foo()    # module1:hello, world!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值