本文实例形式讲解了Python3的条件与循环控制语句及其用法,是学习Python所必须掌握的重要知识点,现共享给大家供大家参考。具体如下:
一般来说Python的流程控制语句包括:if条件语句、while循环语句、for循环语句、range函数以及break、continue、pass控制语句。这些语句在Python中的语义和在其他语言中基本是一样的,所以这里就只说它们的用法。
一、if语句
if语句是最常用的条件控制语句,Python中的一般形式为:
if 条件一: statements elif 条件二: statements else: statements
Python中用elif代替了else if,所以if语句的关键字为:if – elif – else。
注意:
1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。
示例代码如下:
x = int(input("Please enter an integer: ")) if x < 0: print('Negative.') elif x == 0: print('Zero.') else: print('Positive.')
二、while语句
Python中while语句的一般形式:
while 判断条件: statements
同样需要注意冒号和缩进。另外,在Python中没有do..while循环。
示例代码如下:
a, b = 0, 1 while b < 10: # 循环输出斐波纳契数列 print(b) a, b = b, a+b
三、for语句
Python中的for语句与C语言中的for语句有点不同:C语言中的for语句允许用户自定义迭代步骤和终止条件;而Python的for语句可以遍历任何序列(sequence),按照元素在序列中的出现顺序依次迭代。一般形式为:
for variable in sequence: statements else: statements
示例代码如下:
words = ['cat','love','apple','python','friends'] for item in words: print(item, len(item))
如果你需要在循环体内修改你正迭代的序列,你最好是制作一个副本,这时切片标记就非常有用了:
words = ['cat','love','apple','python','friends'] for item in words[:]: # 制作整个列表的切片副本 if len(item) >= 6: words.insert(0, item) print(words)
我们注意到循环语句中还可以使用else子句,下面第五点有讲到。
四、range函数
如果你要遍历一个数字序列,那么内置的range()函数就可以派上用场了。函数range()常用于for循环中,用于产生一个算术数列:
>>> list(range(10)) # 默认从0开始 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) # 从1到11,前闭后开 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) # 5表示步长,每隔5取一个数 [0, 5, 10, 15, 20, 25]
示例代码如下:
for i in range(2, 11): print(i)
五、break、continue、pass及else子句
①.break
break语句与C语言中的一样,跳出最近的for或while循环。
②.continue
continue语句同样是从 C 语言借用的, 它终止当前迭代而进行循环的下一次迭代。
③.pass
pass语句什么都不做,它只在语法上需要一条语句但程序不需要任何操作时使用。pass语句是为了保持程序结构的完整性。
④.else子句
在循环语句中还可以使用else子句,else子句在序列遍历结束(for语句)或循环条件为假(while语句)时执行,但循环被break终止时不执行。如下所示:
# 循环结束执行else子句 for i in range(2, 11): print(i) else: print('for statement is over.') # 被break终止时不会执行else子句 for i in range(5): if(i == 4): break; else: print(i) else: print('for statement is over') # 不会输出

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools
