Python学习笔记(一)

发布于:2024-12-07 ⋅ 阅读:(94) ⋅ 点赞:(0)

MJ大神的Python课,课堂笔记

  • int 和float运算结果是 float
  • 除法(/)的结果是float
  • 整除(//),向下取整(floor)
  • int 和 int 进行整除(//),得到的结果是int

绘制一个填充色+边框色

import turtle

# 绘制一个填充色+边框色
turtle.hideturtle()
turtle.pencolor('green')
turtle.pensize(10)

turtle.fillcolor('yellow')
turtle.begin_fill()
turtle.circle(100)
turtle.end_fill()

# 运行完还保存在原地
turtle.mainloop()

在这里插入图片描述

画一个彩色圆

import turtle

turtle.hideturtle()
turtle.pensize(10)
turtle.color('green')
turtle.circle(100, 90)

turtle.color('yellow')
turtle.circle(100, 90)

turtle.color('red')
turtle.circle(100, 90)

turtle.color('blue')
turtle.circle(100, 90)
# 运行完还保存在原地
turtle.mainloop()

在这里插入图片描述

变量

变量可以由:单词字符(英文字母、中文等)、数字、下划线组成

变量的交互

a = 10
b = 20
print('a =', a, 'b =', b)
a, b = b, a
print('a =', a, 'b =', b)
print('a = ' + str(a) + ' b = ' + str(b))

a = 10 b = 20
a = 20 b = 10
a = 20 b = 10

输入数字,绘制正方形

import turtle

# width = int(input("请输入正方形的边长:"))

# width = int(turtle.textinput("title", "content"))

width = turtle.numinput("title", "content")

turtle.forward(width)
turtle.right(90)

turtle.forward(width)
turtle.right(90)

turtle.forward(width)
turtle.right(90)

turtle.forward(width)

turtle.mainloop()

转义字符

print('123\n456')
print(r'123\n456')

123
456
123\n456

前面加r,表示raw string,原始字符串,禁止转义
使用前提:去掉r,里面的字符串也是一个正确的字符串

当print打印内容过多的时候,可以使用**\ 回车**的方式,进行换行,这样打印出来的时候,还是连续的,没有换行

打印*练习

print("方法一:")
print('*')
print('**')
print('***')
print('****')
print('*****')

print('\n方法二:')
print('*\n**\n***\n****\n*****')

print('\n方法三:')
print('*')
print('*' * 2)
print('*' * 3)
print('*' * 4)
print('*' * 5)

print('\n方法四:')
print('''*
**
***
****
*****
''')

有变量的打印

a = 10
b = 100
print(f"a = {10}, b = {100}")
print(F"a = {10}, b = {100}")

打印结果:
a = 10, b = 100
a = 10, b = 100

name = 'Jack'
age = 19
# %s %d/%i %f
print('My name is %s, and I am %d years old' % (name, age))

打印结果:
My name is Jack, and I am 19 years old

age = 19
print('我的名字是%d岁' % age)
print('我的名字是%4d岁' % age)
print('我的名字是%-4d岁' % age)

打印结果:
我的名字是19岁
我的名字是  19岁
我的名字是19  岁


h = 1
m = 2
s = 3
print('现在的时间是:%02d:%02d:%02d' % (h, m, s))

打印结果:
现在的时间是:01:02:03

and or

and、or的运算结果并不一定就是True、False

a or b

  • 如果a为假,就返回b,否则返回a

a or b 一真则真
a是假的,则整体a or b是真是假的,需要看b的结果
a是真的,则整体的真假,只需要看a即可

a and b

  • 如果a为假,就返回a,否则返回b

a and b 一假则假
a是假的,那么整体就是假的,不需要看b,直接返回a就行
a是真的,那么,就看b是真假

总结一下and、or的运算结果

  • 要么是a、要么是b
  • 其实是最后被执行到的那个值

while练习

# 提示输入一个1~100的正整数
# 如果输入错误,要求重新输入
# 如果输入正确,请打印一下计算结果1+2+3+...+n
n = int(input("请输入[1, 100]范围的正整数:"))

while n < 1 or n > 100:
    n = int(input("请输入[1, 100]范围的正整数:"))

result = 0
while n > 0:
    result = result + n
    n = n - 1
print(f"相加结果是:{result}")

绘制一个五角星

import turtle
n = int(input("输入五角星宽度:"))

turtle.color('red')
turtle.hideturtle()

turtle.begin_fill()

for _ in range(5):
    turtle.forward(n)
    turtle.left(72)
    turtle.forward(n)
    turtle.right(144)

turtle.end_fill()

turtle.mainloop()

在这里插入图片描述

import turtle
# 修改箭头颜色
turtle.shape('turtle')
#'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
turtle.color('green')

for i in range(50):
    turtle.forward(50 + i * 5)
    turtle.right(60)
    #盖章
    turtle.stamp()

turtle.mainloop()

在这里插入图片描述


List

负数索引

可以使用负数索引
比如-1表示倒数第1个

非负索引 + 负索引的绝对值 == len(列表)

假设列表的长度是n
那么索引的取值范围是[ -n, n - 1]

all() any()

  • all(x):如果可迭代对象x中的所有元素都是真,就返回True,否则返回False
  • any(x):只要可迭代对象x中的有元素为真,就返回True,否则返回False

切片(slice)

列表的切片:从列表中选取一部分元素,组成一个新的列表

s[i:j]代表:从s[i] 到s[j-1]的元素

s1 = [55, 44, 33, 22, 11]
对其切片:
s2 = s1[1:4]代表:s2 = [44, 33, 22]

对s1切片,获取s2,此时,s1不会发生任何变化

s = [i ** 2 for i in range(12, 17)]
代表的意思是:
s = [12^2, 13^2, 14^2, 15^2, 16^2]


方法(method)

方法:是一种需要通过 对象 来调用的特殊函数(function)
方法的使用格式:对象.方法名(参数)

函数

print("你好")

方法

s = [1, 2, 3]
s.index(2)

append和extend的区别

在这里插入图片描述


str操作

s.index(x):从左往右,查找x元素,在s中的最小索引
s.rindex(x):从右往左,查找x元素,在s中的最大索引

s.find(x):从左往右,查找x元素,在s中的最小索引
s.rfind(x):从右往左,查找x元素,在s中的最大索引

两者区别:

  • index找不到的话报错(ValueError)
  • find找不到的话,给-1

给一个字符串,统计字符串中0、1出现的次数

inputStr = input("请输入数字:")
count0 = 0
count1 = 0

for i, e in enumerate(inputStr):
    if inputStr[i] == "0":
        count0 += 1
    if inputStr[i] == "1":
        count1 += 1

print(f"0出现了{count0}次")
print(f"1出现了{count1}次")

sep=修改分隔符

print(11, 222, 33, sep='+', end='\n')

打印结果:
11+222+33
s.title():将字符串里面,每一个单词的首字符变大写
s1 = "my name is jack"
s2 = s1.title()

print(s1, s2, sep='\n')

打印结果:
my name is jack
My Name Is Jack
s.capitalize():将字符串里面,首字符变大写,其余保持不变
s1 = "my name is jack"
s2 = s1.capitalize()

print(s1, s2, sep='\n')

打印结果:
my name is jack
My name is jack
name = 'jack'
age = 19

print(f"my name is {name}, i am {age} years old")  #最新支持写法,推荐
print("my name is {}, i am {} years old".format(name, age))

打印结果:
my name is jack, i am 19 years old
my name is jack, i am 19 years old

s.strip(): 删除左右两端的空格字符
s1 = ' 1 2   '
s2 = s1.strip()

print(f'_{s1}_')
print(f'_{s2}_')

打印结果:
_ 1 2   _
_1 2_

只删除两端的,中间的空格不管

s.strip(s2):将s字符串两端有s2的字符删除
s1 = 'www.baidu.com'
s2 = s1.strip('999m2.w')

print(f'_{s2}_')

打印结果:
_baidu.co_
  • lstrip:只删除左边
  • rstrip:只删除右边

s.join

s.join(x)
x是一个可迭代对象
x中的所有元素(必须是str),使用s作为分割符,拼接成新的字符串

s1 = '+-'
data = ['red', 'green', 'blue']

s2 = s1.join(data)

print(s1, s2, sep='\n')

打印结果:
+-
red+-green+-blue

s.split

s.split(x):以x为分隔符,将s切割成若干个子串,并将这些子串放到一个列表中

s = '192.169.0.1'
print(s.split('.')) #按.分割
print(list(s)) #将字符串每一个元素都拿出来
print(s.split('12')) #以一个不存在的12去分割,依然返回原来的内容,并且加到列表里面

打印结果:
['192', '169', '0', '1']
['1', '9', '2', '.', '1', '6', '9', '.', '0', '.', '1']
['192.169.0.1']

s.zfill(x)

用字符0,填充到s的左边,直到字符串的长度达到x

s1 = '123'
s2 = s1.zfill(10)

s3 = '+123'
s4 = s3.zfill(10)

s5 = '-123'
s6 = s5.zfill(10)

s7 = '*123'
s8 = s7.zfill(10)

print(s1, s2)
print(s3, s4)
print(s5, s6)
print(s7, s8)

打印结果:
123 0000000123
+123 +000000123
-123 -000000123
*123 000000*123

s.replace(x, y)

将所有的子串x替换为字符串y

s.replace(x, y, k)
k是最大替换次数
当k为负数时,不限制替换次数

s1 = '192.168.0.1'
s2 = s1.replace('.', '_')
s3 = s1.replace('.', '_', 2) #最大替换2个
s4 = s1.replace('', '_') #在每一个地方都加上_
s5 = s1.replace('.', '') #将.都删掉

print(s1)
print(s2)
print(s3)
print(s4)
print(s5)

打印结果:
192.168.0.1
192_168_0_1
192_168_0.1
_1_9_2_._1_6_8_._0_._1_
19216801
s.removeprefix(x)

删除前缀x
如果s中存在前缀x,等价于s[len(x):]

s1 = 'www.baidu.com'
s2 = s1.removeprefix('www.') #存在就可以删
s3 = s1.removeprefix('baidu') #前缀不存在,删不了

print(s2)
print(s3)
print(s1[len('www.'):]) #等价于`s[len(x):]`,s取[4, 最后],就是baidu.com,相当于删了头

打印结果:
baidu.com
www.baidu.com
baidu.com
  • s.removesuffix(x)删除后缀

Tuple(元组)

以下几种形式,都是元组

t1 = 18, 'k171', 3.14
t2 = (18, 'k171', 3.14)
t3 = 18, 'k171', 3.14,
t4 = (18, 'k171', 3.14, )

print(type(t1))
print(type(t2))
print(type(t3))
print(type(t4))

打印结果:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

如何写只有一个元素的元组?

t1 = (55,)即可
或者t1 = 55,

t1 = (55,)
t2 = 55,

print(type(t1))
print(type(t2))

打印结果:
<class 'tuple'>
<class 'tuple'>

元组的解包

t = (20, 'Jack', True)
age, name, male = t #将元组,赋值给其他三个变量
print(age)
print(name)
print(male)

打印结果:
20
Jack
True

a = 10
b = 2
a, b = b, a #这个交换,其实是元组的解包
print(a, b)

打印结果:
2 10

divmod

divmod函数可以同时返回:商数、余数

t1 = divmod(13, 4)
print(t1)

打印结果:
(3, 1)

div, mod = divmod(14, 5)
print(div)
print(mod)

打印结果:
2
4

序列类型

  • list、tuple、range、str都属于序列类型,其中
  • list:可变类型
  • tuple、range、str都属于:不可变类型

list:数组
tuple:元组
range:是一个内置函数,可以创建一个整数列表
str:字符串

在这里插入图片描述

  • tuple是不可变类型
  • tuple没有append、insert、extend、pop、remove、clear等方法
  • tuple拥有index、count等方法,用法与list类似

关于+=

t1 = (55, 44)
s1 = [33, 22]

print(t1 + s1)

报错:TypeError: can only concatenate tuple (not "list") to tuple


s2 = [55, 41]
s2 += (33, 22)
print(s2)

打印结果:
[55, 41, 33, 22]

t2 = (55, 44)
t2 += [33, 22]

报错:TypeError: can only concatenate tuple (not "list") to tuple

list(可变序列)运用 += ,相当于expend()
而range或者tuple使用+=,就是普通的 t2 = t2 + t1


集合(set)

可迭代 vs 序列类型

  • 可迭代、序列类型并不是等价的概念
  • 可迭代:可以逐个访问内部的元素
  • 序列类型:元素之间有严格的先后顺序

在这里插入图片描述

集合的操作

  • s.add(x): 添加x
  • s.discard(x):删除元素x, 如果x不存在,则没任何问题
  • s.remove(x):删除元素x, 如果x不存在,则报错
  • s.pop(): 删除 并返回1个元素(不确定是哪一个)(如果集合s的长度为0,再删就会报错)
  • s.clear(): 删除集合s中所有元素

字典(dict)

字典形式:

{
	key1: value1,
	key2: value2,
	key3: value3
}
  • dict[key]: 获取dict字典里面为key的value,如果当不存在这个 key的时候,就报错
  • dict.get(key):获取dict字典里面为key的value,如果当不存在这个 key的时候,返回None
  • dict.get(key, x):获取dict字典里面为key的value,如果当不存在这个 key的时候,返回x
  • dict.update(x):将x中的键值对,合并到dict中
d1 = {"name": 'jack'}
d2 = {
    "age": 18,
    "name": "rose"
}

d1.update(d2)
print(d1)

打印结果:
{'name': 'rose', 'age': 18}
  • d.setdefault(key, value)
  • 如果d中不存在这个key,就执行d[key] = value,并返回value
  • 如果d中存在这个key,就直接返回d[key]

在这里插入图片描述


函数

可变参数

在函数参数前面加上*,就是可变参数
可变参数会将实参打包成元组传递给形参

def hello(*names):
    print(names)
    print(type(names))

hello("123")
hello("123", "456")

打印结果:
('123',)
<class 'tuple'>
('123', '456')
<class 'tuple'>

*names是一个可变参数,它可以将任意数量的值,打包成1一个元组对象

解包
s = [5, 6, 7]
a, b, c = s

将s里面的数据分别拿出来赋值出去,就叫解包

调用函数的时候,在参数前面加个*,就是对该参数进行解包:
s = [5, 6, 7] move_circle(*s)

def hello(*names):
	print(type(names))#<class 'tuple'>
    for n in names:
        print(f'Hi, {n}!')

s = ['jack', 'rose', 'jim']#<class 'list'>

hello(s)

hello(*s)

打印结果:
Hi, ['jack', 'rose', 'jim']!
Hi, jack!
Hi, rose!
Hi, jim!

首先,hello(*s),相当于对s进行解包,也就是相当于:hello('jack', 'rose', 'jim')
相当于hello接收了三个参数,并且打包成一个元组
然后对元组names进行for循环,所以打印三次

而,hello(s),相当于hello(['jack', 'rose', 'jim'])
直接将一个list打包到元组names里面
相当于names = (['jack', 'rose', 'jim'])
names元组只有一个元素,该元素是一个list
然后进行for循环,输出的只是第一个元素['jack', 'rose', 'jim']

第一个打印,带了一个[],也就是,list打印,连[]也打印了
t1 = ([1, 2, 3], (“1”, “2”, “3”), “3”, 4, 9.0, {})
print(t1)
打印结果:
([1, 2, 3], (‘1’, ‘2’, ‘3’), ‘3’, 4, 9.0, {})

关键字参数 字典化

在这里插入图片描述
当函数定义的时候,某个参数用**的时候,表示:将入参包装成一个字典,传递给函数

def hello(name, times):
    for _ in range(times):
        print(f'Hi, {name}!')

d = {
    'times': 2,
    'name': 'Jack'
}

# 方法一
hello(name='Jack', times=2)
# 方法二
hello(name=d['name'], times=d['times'])
# 方法三
hello(**d)

打印结果:
Hi, Jack!
Hi, Jack!
Hi, Jack!
Hi, Jack!
Hi, Jack!
Hi, Jack!

hello(**d)**用来解包d这个字典的实参,也就是将字典解包成:name=d['name'], times=d['times']

  • ** 字典实参:会将字典实参解包为关键字参数,key作为参数名,value作为参数值

需要注意的是:d的参数,要与hello接收的参数一一对应

在这里插入图片描述

引用传递

在python中,将实参传递给形参时,使用的是:引用传递
实参、形参指向的是同一个对象

  • Python的形参可以接收任意类型的实参
def hello(name, times):
    print(name, type(name))
    print(times, type(times))

hello('Jack', 10)
print('---')
hello(10, 'Rose')

打印结果:
Jack <class 'str'>
10 <class 'int'>
---
10 <class 'int'>
Rose <class 'str'>

这家伙,形参包容万物,一时不知说什么好,真6

但是,这种可能会有潜在问题,还是加上类型比较好:
def hello(name: str, times: int):

age: int = 10
age += 2
age = 'ppp'
age -= 1
age = 10
运行报错:age -= 1 因为前面age是str类型


age: int = 10
age += 2
age = 'ppp'
age = 10
print(age)#10
# 一点事没有,神奇,真是弱类型

作用域

def test1():
    k = 10

    def test2():
        k = 100
        print("test2")

    print(f'k = {k}')
    test2()
    print(f'k = {k}')

test1()

打印结果:
k = 10
test2
k = 10

当我们想用test2里面的k也可以修改test1中的k时,需要在test2中加上:nonelocl k

def test1():
    k = 10

    def test2():
        nonlocal k
        k = 100
        print("test2")

    print(f'k = {k}')
    test2()
    print(f'k = {k}')

test1()

打印结果:
k = 10
test2
k = 100

nonelocl k只能找局部变量里面的
并且,只能找父级或者父父级的某一个k,而不是这条链上的所以k

另外,nonelocl k也不能修改全局的k

需要修改全局的k,需要使用 global k


网站公告

今日签到

点亮在社区的每一天
去签到