search
HomeBackend DevelopmentPython TutorialPython中的条件判断语句与循环语句用法小结

if语句

>>通用格式
if语句一般形式如下:

if <test1>:
 <statements1>
elif <test2>:
 <statements2>
else:
 <statements3>

另外需要注意的是,Python中是没有switch/case语句的


while循环

while语句是Python语言中最通用的迭代结构,简而言之,只要顶端测试一直计算到真值,就会重复执行一个语句块。

>>一般格式

while <test>:
 <statements1>
else:
 <statements2>
>>break,continue,pass和循环else

break

跳出最近所在的循环(跳过整个循环语句)。

continue

跳到最近所在循环的开头处(来到循环的首行)。

pass

什么事也不做,只是空占位符语句。

循环else块

只有当前循环正常离开时才会执行(也就是没有碰到break语句)

>>一般循环格式
加入break和continue语句后,while的一般格式变为:

while <test1>:
 <statements1>
 if <test2>:break
 if <test3>:continue
else:
 <statements2>
>>pass

pass语句是无运算的占位符,当语法需要语句并且还没有任何实用的语句可写时,就可以使用它。

>>循环else
在while语句中加入else和C/C++中的语法不太一样,这里详细说明一下。else后面的代码只有当循环正常结束时才会执行,如果是用break跳出循环的,这部分代码就不会运行,具体看一个求质数的例子:

x = y // 2
while x > 1:
 if y % x == 0:
  print(y,'has factor',x)
  break
 x -= 1
else:
 print(y,'is prime')

再看一个对比的例子,没有使用else的情况:

found=False
while x and not found:
 if (matchx[0]):
  print('Ni')
  found=True
 else:
  x=x[1:]
if not found:
 print('not found')
使用else后的情况:

while x:
 if (match(x[0])):
  print('Ni')
  break
else:
 print('not found')

for循环

for循环在Python中是一个通用的序列迭代器:可以遍历任何有序的序列对象内元素。for语句可以用于字符串、列表、元组、其他内置可迭代对象。

>>一般格式

for <target> in <object>:
 <statements>
else:
 <statements>

此处的else的作用和while语句中的一样。另外需要注意的是,当Python运行for循环时,会逐个将序列对象中的元素赋值给目标,然后为每个元素执行循环体。

编写循环的技巧

内置range函数:返回一系列连续增加的整数,可作为for中的索引
内置zip函数:返回并行元素的元组的列表,可用于在for中遍历数个数列
>>循环计数器:while和range
range

当range函数只有一个参数时,会返回从零算起的整数列表,但其中不包括该参数的值。如果传进两个参数,那第一个参数是上边界,第二个参数是下边界。如果传进三个参数时,第三个参数表示步进值。

range提供了一种简单的方法,重复特定次数的动作:

for i in range(5):
 print(i,'Pythons')

相应的C++代码则是:

int i;
for(i = 0;i < 5;++i)
{
 std::cout<<i<<"Python";
}

>>并行遍历:zip和map
zip会取得一个或多个序列为参数,然后返回元组的列表,将这些序列中的并排的元素配成对。

L1=[1,2,3,4]
L2=[5,6,7,8]
list(zip(L1,L2))

上述代码的执行结果是:

[(1,5),(2,6),(3,7),(4,8)]

当参数的长度不同时,zip会以最短序列的长度为准来截断所得到的元组。

使用zip构造字典:

keys=['spam','eggs','totast']
values=[1,2,5]
D = dict(zip(keys,values))

>>产生偏移和元素:enumerate
enumerate函数一个比较新的内置函数,它能同时返回元素值和偏移值:

s='spam'
for (offset,item) in enumerate(s):
 print(item,'appears at offset',offset)

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
What are some common reasons why a Python script might not execute on Unix?What are some common reasons why a Python script might not execute on Unix?Apr 28, 2025 am 12:18 AM

The reasons why Python scripts cannot run on Unix systems include: 1) Insufficient permissions, using chmod xyour_script.py to grant execution permissions; 2) Shebang line is incorrect or missing, you should use #!/usr/bin/envpython; 3) The environment variables are not set properly, and you can print os.environ debugging; 4) Using the wrong Python version, you can specify the version on the Shebang line or the command line; 5) Dependency problems, using virtual environment to isolate dependencies; 6) Syntax errors, using python-mpy_compileyour_script.py to detect.

Give an example of a scenario where using a Python array would be more appropriate than using a list.Give an example of a scenario where using a Python array would be more appropriate than using a list.Apr 28, 2025 am 12:15 AM

Using Python arrays is more suitable for processing large amounts of numerical data than lists. 1) Arrays save more memory, 2) Arrays are faster to operate by numerical values, 3) Arrays force type consistency, 4) Arrays are compatible with C arrays, but are not as flexible and convenient as lists.

What are the performance implications of using lists versus arrays in Python?What are the performance implications of using lists versus arrays in Python?Apr 28, 2025 am 12:10 AM

Listsare Better ForeflexibilityandMixdatatatypes, Whilearraysares Superior Sumerical Computation Sand Larged Datasets.1) Unselable List Xibility, MixedDatatypes, andfrequent elementchanges.2) Usarray's sensory -sensical operations, Largedatasets, AndwhenMemoryEfficiency

How does NumPy handle memory management for large arrays?How does NumPy handle memory management for large arrays?Apr 28, 2025 am 12:07 AM

NumPymanagesmemoryforlargearraysefficientlyusingviews,copies,andmemory-mappedfiles.1)Viewsallowslicingwithoutcopying,directlymodifyingtheoriginalarray.2)Copiescanbecreatedwiththecopy()methodforpreservingdata.3)Memory-mappedfileshandlemassivedatasetsb

Which requires importing a module: lists or arrays?Which requires importing a module: lists or arrays?Apr 28, 2025 am 12:06 AM

ListsinPythondonotrequireimportingamodule,whilearraysfromthearraymoduledoneedanimport.1)Listsarebuilt-in,versatile,andcanholdmixeddatatypes.2)Arraysaremorememory-efficientfornumericdatabutlessflexible,requiringallelementstobeofthesametype.

What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor