百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python 3.9部分教程 计算 列表 字符串 切片等

off999 2024-09-21 21:03 27 浏览 0 评论

>>> 2 + 2

4

>>> 50 - 5*6

20

>>> (50 - 5*6) / 4

5.0

>>> 8 / 5

1.6 # division always returns a floating point number 除法总是返回一个浮点数


>>> 17 / 3

5.666666666666667 # classic division returns a float 经典除法返回一个浮点数


>>>

>>> 17 // 3

5 # floor division discards the fractional part 向下取整丢弃小数部分



>>> 17 % 3

2 # the % operator returns the remainder of the

division %操作符返回除法的余数


>>> 5 * 3 + 2

17 # floored quotient * divisor + remainder 商*除数+余数


>>> 5 ** 2 # 5 squared 5的平方

25

>>> 2 ** 7 # 2 to the power of 7 2的7次方

128


>>> width = 20

>>> height = 5 * 9

>>> width * height

900


>>> n # try to access an undefined variable 未定义变量

Traceback (most recent call last):

File "<stdin>", line 1, in <module> 第一行

NameError: name 'n' is not defined 未定义n


>>> 4 * 3.75 - 1 浮点运算

14.0


>>> tax = 12.5 / 100

>>> price = 100.50

>>> price * tax

12.5625

>>> price + _

113.0625

>>> round(_, 4)

113.0625

>>> round(_,3)

113.062


>>>'spam eggs' # single quotes 单引号

'spam eggs'

>>> 'doesn\'t'

"doesn't" # use \' to escape the single quote... 使用 \' 转义符 把单引号变双引号 …


>>> "doesn't"

"doesn't" # ...or use double quotes instead 或者使用双引号


>>> '"Yes," they said.' 放在单引号内

'"Yes," they said.'


>>> "\"Yes,\" they said." 使用\' 转义符 把双引号变单引号

'"Yes," they said.'

>>> '"Isn\'t," they said.'

'"Isn\'t," they said.'


>>> print('"Isn\'t," they said.') #输出单引号内的内容

"Isn't," they said.



# \n means newline \ n表示换行符

>>> s = 'First line.\nSecond line.'

>>> s

'First line.\nSecond line.' # without print(), \n is included in the output 没有print() \n包含在输出中


>>> print(s)

First line.

Second line # with print(), \n produces a new line 使用print(), \n产生换行作用


>>> print('C:\some\name')

C:\some

ame # here \n means newline! 这里\n默认会表示换行


>>> print(r'C:\some\name')

C:\some\name # note the r before the quote 注意前面加 r 可以让特殊符号失去作用


''' ''' 或 """ """ \ 可以跨越多行输入

print(''' ''') 或者 print(""" """)


>>> # 3 times 'un', followed by 'ium' 3乘以un,然后加ium

>>> 3 * 'un' + 'ium'

'unununium'


>>> 'Py' 'thon'

'Python'

>>> '大''家''好'

'大家好'

>>> text = ('Put several strings within parentheses '

'to have them joined together.')

>>> text

'Put several strings within parentheses to have them joined together.


如果您要将变量或变量与文字串联,请使用 +

>>> prefix = 'Py'

>>> prefix + 'thon'

'Python'


>>> word = 'Python'

>>> word[0]

'P' # character in position 0 索引第一个字符默认是 0

>>> word[5]

'n' # character in position 5 位置5的字符是n 因第一个字符是0

>>> word[-1]

'n' # last character 最后一个字符 由于 -0 与 0 相同 负指数从 -1 开始

>>> word[-2] # second-last character 倒数第二字符

'o'

>>> word[-6]

'P

>>> word[0:2]

'Py' # characters from position 0 (included) to 2 (excluded) 还可以切片 从0到2但不包括2的所有字符

>>> word[2:5]

'tho # characters from position 2 (included) to 5 (excluded) 从位置2到5但不包括5的所有字符

>>> word[:2]

'Py' # character from the beginning to position 2 (excluded) :前没数索引位置默认是0也就是最开头 从开始到位置2但不包括位置2全部字符

>>> word[4:]

'on' # characters from position 4 (included) to the end :后没数默认是从......一直到最后 从位置4到最后的全部字符

>>> word[-2:]

'on' # characters from the second-last (included) to the end 从倒数第2到最后的全部字符

>>> word[:2] + word[2:]

'Python' 开始到第2位置但不包含2 + 从第2位置到最后

>>> word[:4] + word[4:]

'Python' 开始到第4位置但不包含4 + 从第4位置到最后


# the word only has 6 characters 太大的索引将导致错误 word只有6个字符

>>> word[42]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of rang 索引错误字符串索引超出范围


但是切片就会优雅地处理范围外切片索引

>>> word[4:42]

'on'

>>> word[42:]

''


Python字符串无法更改 它们是不变的。

>>> word[0] = 'J'

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment


但是可以创建一个新的字符串

>>> 'J' + word[1:]

'Jython'

>>> word[:2] + 'py'

'Pypy'


索引位置

+---+---+---+---+---+---+

| P | y | t | h | o | n |

+---+---+---+---+---+---+

0 1 2 3 4 5 6

-6 -5 -4 -3 -2 -1


内置功能 len() 返回字符串长度

>>> s = 'supercalifragilisticexpialidocious'

>>> len(s)

34


列表

>>> squares = [1, 4, 9, 16, 25]

>>> squares

[1, 4, 9, 16, 25]

列表也可以索引和切片

>>> squares[0] # indexing returns the item

1

>>> squares[-1]

25

>>> squares[-3:] # slicing returns a new list

[9, 16, 25]

>>> squares[:]

[1, 4, 9, 16, 25]

列表还支持串联等操作

>>> squares + [36, 49, 64, 81, 100]

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


与不变的字符串不同,列表是一种可变类型,即可以更改其内容

>>> cubes = [1, 8, 27, 65, 125] # something's wrong here 这里的第四个是错误输入

>>> 4 ** 3

64 # the cube of 4 is 64, not 65! 4的三次方是64不是65

>>> cubes[3] = 64 # replace the wrong value 替换65

>>> cubes

[1, 8, 27, 64, 125]

在列表末尾添加新项目

>>> cubes.append(216) # add the cube of 6 加入6的3次方

>>> cubes.append(7 ** 3) # and the cube of 7 加入7的3次方

>>> cubes

[1, 8, 27, 64, 125, 216, 343]


分配到切片也是可能的,这甚至可以更改列表的大小或完全清除它

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> letters

['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> # replace some values 替换一些值

>>> letters[2:5] = ['C', 'D', 'E']

>>> letters

['a', 'b', 'C', 'D', 'E', 'f', 'g']

>>> # now remove them 现在删除它们

>>> letters[2:5] = []

>>> letters

['a', 'b', 'f', 'g']

>>> # clear the list by replacing all the elements with an empty list 通过将所有元素替换为空列表来清除列表

>>> letters[:] = []

>>> letters

[]


内置功能len()也适用于列表

>>> letters = ['a', 'b', 'c', 'd']

>>> len(letters)

4


可以嵌套列表(创建包含其他列表的列表)

>>> a = ['a', 'b', 'c']

>>> n = [1, 2, 3]

>>> x = [a, n]

>>> x

[['a', 'b', 'c'], [1, 2, 3]]

>>> x[0] # x第一个列表a

['a', 'b', 'c']

>>> x[0][1] # x第一个列表 a里的第2个元素

'b'


>>> # Fibonacci series: 斐波纳契数列

... # the sum of two elements defines the next

... a, b = 0, 1 # a b分别赋值0和1

>>> while a < 10:

... print(a) # 注意缩进TAB

... a, b = b, a+b # a赋值等于b ,b赋值等于a+b

...

0

1

1

2

3

5

8


>>> i = 256*256

>>> print('The value of i is', i)

The value of i is 65536

>>> a, b = 0, 1

>>> while a < 1000:

... print(a, end=',')

... a, b = b, a+b

...

0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,


任何非零整数值都是真实的 零是假的 任何长度为非零的都是真的, 空序列是假的

(小于)、(大于)、(等于)、(小于或等于)、(大于或等于)和(不等于)

< > == <= >= !=



>>> x = int(input("Please enter an integer: "))

Please enter an integer: 56


if语句

>>> if x < 0: # 如果

... x = 0 # 注意缩进

... print('Negative changed to zero')

... elif x == 0: 否则

... print('Zero')

... elif x == 1:

... print('Single')

... else:

... print('More')

...

More


for语句

>>> # Measure some strings: 测量一些字符串

... words = ['cat', 'window', 'defenestrate']

>>> for w in words:

... print(w, len(w))

...

cat 3

window 6

defenestrate 12

相关推荐

让 Python 代码飙升330倍:从入门到精通的四种性能优化实践

花下猫语:性能优化是每个程序员的必修课,但你是否想过,除了更换算法,还有哪些“大招”?这篇文章堪称典范,它将一个普通的函数,通过四套组合拳,硬生生把性能提升了330倍!作者不仅展示了“术”,更传授...

7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制

“本文整理自开发者AbdurRahman在Stackademic的真实记录,所有代码均经过最小化删减,确保在50行内即可运行。每段脚本都对应一个日常场景,拿来即用,无需额外依赖。一、在朋...

Python3.14:终于摆脱了GIL的限制

前言Python中最遭人诟病的设计之一就是GIL。GIL(全局解释器锁)是CPython的一个互斥锁,确保任何时刻只有一个线程可以执行Python字节码,这样可以避免多个线程同时操作内部数据结...

Python Web开发实战:3小时从零搭建个人博客

一、为什么选Python做Web开发?Python在Web领域的优势很突出:o开发快:Django、Flask这些框架把常用功能都封装好了,不用重复写代码,能快速把想法变成能用的产品o需求多:行业...

图解Python编程:从入门到精通系列教程(附全套速查表)

引言本系列教程展开讲解Python编程语言,Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,它也是互联网最热门的编程语言之一。Python生态丰富,库(模块)极其丰富,这使...

Python 并发编程实战:从基础到实战应用

并发编程是提升Python程序效率的关键技能,尤其在处理多任务场景时作用显著。本文将系统介绍Python中主流的并发实现方式,帮助你根据场景选择最优方案。一、多线程编程(threading)核...

吴恩达亲自授课,适合初学者的Python编程课程上线

吴恩达教授开新课了,还是亲自授课!今天,人工智能著名学者、斯坦福大学教授吴恩达在社交平台X上发帖介绍了一门新课程——AIPythonforBeginners,旨在从头开始讲授Python...

Python GUI 编程:tkinter 初学者入门指南——Ttk 小部件

在本文中,将介绍Tkinter.ttk主题小部件,是常规Tkinter小部件的升级版本。Tkinter有两种小部件:经典小部件、主题小部件。Tkinter于1991年推出了经典小部件,...

Python turtle模块编程实践教程

一、模块概述与核心概念1.1turtle模块简介定义:turtle是Python标准库中的2D绘图模块,基于Logo语言的海龟绘图理念实现。核心原理:坐标系系统:原点(0,0)位于画布中心X轴:向右...

Python 中的asyncio 编程入门示例-1

Python的asyncio库是用于编写并发代码的,它使用async/await语法。它为编写异步程序提供了基础,通过非阻塞调用高效处理I/O密集型操作,适用于涉及网络连接、文件I/O...

30天学会Python,开启编程新世界

在当今这个数字化无处不在的时代,Python凭借其精炼的语法架构、卓越的性能以及多元化的应用领域,稳坐编程语言排行榜的前列。无论是投身于数据分析、人工智能的探索,还是Web开发的构建,亦或是自动化办公...

Python基础知识(IO编程)

1.文件读写读写文件是Python语言最常见的IO操作。通过数据盘读写文件的功能都是由操作系统提供的,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个...

Python零基础到精通,这8个入门技巧让你少走弯路,7天速通编程!

Python学习就像玩积木,从最基础的块开始,一步步搭建出复杂的作品。我记得刚开始学Python时也是一头雾水,走了不少弯路。现在回头看,其实掌握几个核心概念,就能快速入门这门编程语言。来聊聊怎么用最...

一文带你了解Python Socket 编程

大家好,我是皮皮。前言Socket又称为套接字,它是所有网络通信的基础。网络通信其实就是进程间的通信,Socket主要是使用IP地址,协议,端口号来标识一个进程。端口号的范围为0~65535(用户端口...

Python-面向对象编程入门

面向对象编程是一种非常流行的编程范式(programmingparadigm),所谓编程范式就是程序设计的方法论,简单的说就是程序员对程序的认知和理解以及他们编写代码的方式。类和对象面向对象编程:把...

取消回复欢迎 发表评论: