search
HomeBackend DevelopmentPython Tutorial跟老齐学Python之正规地说一句话

小孩子刚刚开始学说话的时候,常常是一个字一个字地开始学,比如学说“饺子”,对他/她来讲,似乎有点难度,大人也聪明,于是就简化了,用“饺饺”来代替,其实就是让孩子学会一个字就能表达。当然,从教育学的角度,有人不赞成这种方法。这个此处不讨论了。如果对比学习编程,就好像是前面已经学习过的那些各种类型的数据(对应这自然语言中的单个字、词),要表达一个完整的意思,或者让计算机完成一个事情(动作),不得不通过一句话,这句话就是语句,它是按照一定规则组织起来的。自然语言中的一句话,按照主谓宾的语法方式组织,计算机编程中的语句,也是按照一定的语法要求进行组织。

虽然在第一部分中,已经零星涉及到语句问题,并且在不同场合也进行了一些应用。毕竟不那么系统。本部分,就比较系统地介绍python中的语句。

为了有总括的印象,先看看python中都包括哪些语句:

赋值语句

if语句,当条件成立时运行语句块。经常与else, elif(相当于else if)配合使用。
for语句,遍列列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。
while语句,当条件为真时,循环运行语句块。
try语句。与except, finally, else配合使用处理在程序运行中出现的异常情况。
class语句。用于定义类型。
def语句。用于定义函数和类型的方法。
pass语句。表示此行为空,不运行任何操作。
assert语句。用于程序调适阶段时测试运行条件是否满足。
with语句。Python2.6以后定义的语法,在一个场景中运行语句块。比如,运行语句块前加锁,然后在语句块运行退出后释放锁。
yield语句。在迭代器函数内使用,用于返回一个元素。
raise语句。抛出一个异常。
import语句。导入一个模块或包。常用写法:from module import name, import module as name, from module import name as anothername
特别说明,以上划分也不是很严格,有的内容,有的朋友不认为属于语句。这没关系,反正就是那个东西,在编程中使用。不纠结于名词归类上。总之这些都是要掌握的,才能顺利编程呢。

再谈赋值语句

还记得赋值,简单也不简单那一讲中所提到的赋值语句吗?既然谈语句,就应该从这个开始,一方面复习,另外一方面,希望能够深点,深点的感觉总是很好的(我说的是理解python,思无邪。前面有一个关于list的内容:再深点,更懂list,就有喜欢看玩笑的看官思邪了。哈哈。)

复制代码 代码如下:

>>> qiwsir = 1
>>> python = 2
>>> x, y = qiwsir, python   #相当于x=qiwsir,y=python
>>> x
1
>>> y
2
>>> x, y                    #输出的是tuple
(1, 2)
>>> [x, y]                  #这就是一个list
[1, 2]

>>> [a, b] = [qiwsir, python]
>>> a
1
>>> b
2
>>> a, b
(1, 2)
>>> [a, b]
[1, 2]

换一种方式,以上两种赋值方法交叉组合一下:

复制代码 代码如下:

>>> [c, d] = qiwsir, python
>>> c
1
>>> d
2
>>> c, d
(1, 2)
>>> f, g = [qiwsir, python]
>>> f
1
>>> g
2
>>> f, g
(1, 2)

居然也行。其实,从这里我们就看出来了,赋值,就是对应着将左边的变量和右边的对象关联起来。

有这样一个有趣的问题,如果a=3,b=4,想把这两个变量的值调换一下,也就是a=4,b=3。在有的高级语言中,是要先引入另外一个变量c做为中间中专,就是这样:

复制代码 代码如下:

a = 3
b = 4
c = a   #即c=3
a = b   #a=4
b = c   #b=3

初学者可能有点糊涂。就是我和你两只手都托着一个箱子,现在我们两个要换一下箱子,但是两个手都被占用了,无法换(当然,要求箱子不能落地,也不要放在桌子上之类的)。于是再找一个名曰张三的人来,他空着两只手,那么我先把箱子给张三,我就空出来了,然后接你的箱子,你的箱子就到我手里了。我的那个箱子现在张三手里呢,你接过来,于是我们两个就换了箱子了。

只所以这么啰嗦,就是因为我们两个没有更多的手。但是,这不是python,python有更多的手。她可以这样:

复制代码 代码如下:

>>> qiwsir = 100
>>> python = 200
>>> qiwsir, python = python, qiwsir
>>> qiwsir
200
>>> python
100

有点神奇,python是三头六臂的。

序列赋值

其实上面实验的赋值,本质上就是序列赋值。只不过这里再强化一番罢了。如果左边的变量是序列,右边的对象也是序列,两者将一一对应地进行赋值。

复制代码 代码如下:

>>> [a, b, c] = (1, 2, 3)   #左右序列一一对应,左边是变量,右边是对象
>>> a
1
>>> b
2
>>> c
3
>>> (a,b,c) = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>> [a,b,c] = "qiw"     #不要忘记了,str也是序列类型的数据
>>> a
'q'
>>> b
'i'
>>> c
'w'
>>> (a,b,c) = "qiw"
>>> a,c
('q', 'w')
>>> a,b,c = 'qiw'       #与前面等价
>>> a,b
('q', 'i')
>>> a,b = 'qiw'         #报错了,因为左边和右边不是一一对应
Traceback (most recent call last):
  File "", line 1, in
ValueError: too many values to unpack

>>> (a,b),c = "qi","wei"    #注意观察,这样的像是是如何对应的
>>> a,b,c
('q', 'i', 'wei')
>>> string = "qiwsir"
>>> a,b,c = string[0],string[1],string[2]   #取切片也一样
>>> a,b,c
('q', 'i', 'w')
>>> (a,b),c = string[:2],string[2:]
>>> a,b,c
('q', 'i', 'wsir')

从实验中,可以看出,要搞清楚这种眼花缭乱的赋值,就仅仅扣住“一一对应”这个命脉即可。

如果看官用python3,在赋值上还有更多有意思的东西呢。不过,本讲座用的还是python2。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software