search
HomeBackend DevelopmentPython TutorialPython basics loop statements

1. Scene introduction

## Circular scenes in life

Runway


Python basics loop statements##Fan

Python basics loop statements## Usage scenarios of loops in software development

When admitting a mistake, saying "I was wrong" ten thousand times will feel very troublesome and cumbersome.

    print("我错了")
    print("我错了")
    print("我错了")
    ...(还有9997遍)...

Use a loop statement to do it in one sentence.
    i = 0
    while i<10000:
        print("我错了")
        i+=1

Generally, code that needs to be executed multiple times can be completed in a loop.
Loops are not necessary, but in order to improve the reuse rate of code, experienced developers will use loops.

2. Introduction to common loops (while, for, break and continue)

while

##< ;1> Format of while loop

 while 条件:
        条件满足时,做的事情1
        条件满足时,做的事情2
        条件满足时,做的事情3
        ...(省略)...

Example:
    i = 0
    while i<5:
        print("当前是第%d次执行循环"%(i+1))
        print("i=%d"%i)
        i+=1

运行结果 :

    当前是第1次执行循环
    i=0
    当前是第2次执行循环
    i=1
    当前是第3次执行循环
    i=2
    当前是第4次执行循环
    i=3
    当前是第5次执行循环
    i=4

while循环应用

例:计算1~100的累积和(包含1和100)

#encoding=utf-8


i = 1
sum = 0
while i<=100:
    sum = sum + i
    i += 1


print("1~100的累积和为:%d"%sum)

运行结果:

Python basics loop statements


while循环嵌套

 while嵌套的格式 :

while 条件1:


    条件1满足时,做的事情1
    条件1满足时,做的事情2
    条件1满足时,做的事情3
    ...(省略)...


    while 条件2:
        条件2满足时,做的事情1
        条件2满足时,做的事情2
        条件2满足时,做的事情3
        ...(省略)...

例:九九乘法表

代码如下:

i = 1
while i<=9:
    j=1
    while j<=i:
        print("%d*%d=%-2d "%(j,i,i*j),end=&#39;&#39;)
        j+=1
        print(&#39;\n&#39;)
        i+=1

运行结果:

Python basics loop statements

可以看到while循环可以轻松的实现,避免出现代码冗余的情况。


for

for循环介绍

像while循环一样,for可以完成循环的功能。

在Python中for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

for循环的格式

for 临时变量 in 列表或者字符串等:
    循环满足条件时执行的代码

小项目

定义name变量,for循环打出以下结果。

name = &#39;dongGe&#39;


for x in name:
    print(x)

运行结果:

d
o
n
g
G
e


总结:

1.while循环一般通过数值是否满足来确定循环的条件。

2.for循环一般是对能保存多个数据的变量,进行遍历。

break

break和for嵌套

带有break的循环示例如下:

name = &#39;dongGe&#39;


for x in name:
    print(&#39;----&#39;)
    if x == &#39;g&#39;: 
        break
    print(x)

运行结果:

Python basics loop statements


break和while循环嵌套

带有break的循环示例如下:

i = 0


while i<10:
    i = i+1
    print(&#39;----&#39;)
    if i==5:
        break
    print(i)

Python basics loop statements


小总结 :

break的作用:用来结束整个循环。


Continue

continue和for嵌套

带有continue的循环示例如下 :

name = &#39;dongGe&#39;


for x in name:
    print(&#39;----&#39;)
    if x == &#39;g&#39;: 
        continue
    print(x)

运行结果:

Python basics loop statements


 continue和 while嵌套

带有continue的循环示例如下 :

i = 0


while i<10:
    i = i+1
    print(&#39;----&#39;)
    if i==5:
        continue
    print(i)

运行结果 :

Python basics loop statements

小总结 :

1. continue的作用:用来结束本次循环,紧接着执行下一次的循环。

2. break/continue只能用在循环中,除此以外不能单独使用。

3. break/continue在嵌套循环中,只对最近的一层循环起作用。

三、总结

本文以生活中的基础现象为切入点,主要介绍了Python基础中循环语句,对于每个循环的用法,以及循环之间相互嵌套使用,做了详细的讲解,用丰富的案例帮助大家更好理解。

The above is the detailed content of Python basics loop statements. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools