本文实例讲述了Python中for循环控制语句用法。分享给大家供大家参考。具体分析如下:
第一个:求 50 - 100 之间的质数
import math for i in range(50, 100 + 1): for j in range(2, int(math.sqrt(i)) + 1): if i % j == 0: break else: print i
输出如下:
53 59 61 67 71 73 79 83 89 97
第二个:把else的位置与if处于同一缩进。
import math for i in range(50, 100 + 1): for j in range(2, int(math.sqrt(i)) + 1): if i % j == 0: break else: print i
第三个:在else后加一个break语句。
import math for i in range(50, 100 + 1): for j in range(2, int(math.sqrt(i)) + 1): if i % j == 0: break else: print i break
说明:
for语句是python中的循环控制语句。可用来遍历某一对象,还具有一个附带的可选的else块,主要用于处理for语句中包含的break语句。
如果for循环未被break终止,则执行else块中的语句。
break 在需要时终止for循环
continue 跳过位于其后的语句,开始下一轮循环。
for语句的格式如下:
>>>for in :
... if :
... break
... if :
... continue
...
...else:
...
...
关于第一个程序
在这里,我解释一下为何导入math模块:导入math模块就是为了开方。
如果导入了math模块,然后对 i 进行开方,可以减少运算次数。
求一个数是否质数。只需对它进行这样的运算:
将这个数n,循环与 2 到 这个n的开平方 进行相除
如果这个区间内的所有整数不能整除n,则n为质数。
这样,就节省了运算 ‘大于n的开平方 小于n' 之间这段运算的时间。
第二,我解释一下那‘+1':
int(math.sqrt(i)) 输出的是比 i的开平方 小 的最大整数。
比如说:math.sqrt(51) 结果比7大一点,而 int(math.sqrt(51)) 输出的是7
而且在range(m, n)这里,range()函数产生的是一个从 m至n-1的整数列表,因而需要‘+1',使运算完整。
顺便提一下range()函数。
range([start,] stop [, step])
# start 可选参数,起始数
#stop 终止数,如果 range 只有一个参数x,则产生一个包含 0 至 x-1 的整数列表
#step 可选参数,步长
第二个程序
else那行不对,如果else放在那个地方的话,一旦有某个数遇到不能整除自己的数,就会输出i,直道找到一个整除自己等于0的数。那样就会连续输出这个数。
例如:i = 77,他不是质数,但是也会连续输出5次77,懂不?
只不过,只是自己不明白当else与if位于同一缩进的话,它是怎样运行的。
你解释得很详细,用‘茅塞顿开'来形容一点都不过分。
而且,我必觉得画图是理解循环一个非常好的办法。
希望本文所述对大家的Python程序设计有所帮助。

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.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

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

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

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),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor
