


In Python, what is the difference between a for loop and a while loop?
In this article, we will understand the difference between “for” loop and “while” loop.
For Loop
A for loop is a control flow statement that executes code for a predefined number of iterations. The keyword used in this control flow statement is "for". Use a for loop when the number of iterations is known.
The for loop is divided into two parts -
Title - This section specifies the iterations of the loop. In the header section, the loop variable is also declared, which tells the body which iteration is being executed.
Body - The body section contains the statements executed for each iteration.
Initialization, condition checking and iteration statements are all written at the beginning of the loop.
Use this only when the number of iterations is known in advance.
If no condition is mentioned in the "for" loop, the loop will iterate infinite times.
Initialization is only done once and will not be repeated.
The iteration statement is written at the beginning.
So it will execute once all statements in the loop have been executed.
grammar
for(initialization; condition; iteration){ //body of the 'for' loop }
Example
The following program uses a for loop to print all list elements -
# input list inputList = [10, 20, 30, 40, 50] print("Input list elements:") # traversing through all elements of the list using for loop for element in inputList: # printing each element of the list print(element)
Output
When executed, the above program will generate the following output -
Input list elements: 10 20 30 40 50
While Loop
A loop that runs a single statement or a set of statements against a given true condition. This loop is represented by the keyword "while". A "while" loop is used when the number of iterations is unknown. Repeat this statement until the Boolean value is false. Since the condition is tested at the beginning of the while loop, it is also called a pre-test loop.
Initialization and condition checking are completed at the beginning of the loop.
Use only when the number of iterations is unknown.
If no condition is mentioned in the "while" loop, it will cause a compilation error.
If initialization is done when checking a condition, initialization will occur each time the loop is iterated.
The iteration statement can be written at any point within the loop.
grammar
while ( condition) { statements; //body of the loop }
Example
The following program uses a for loop to print all list elements -
# Initializing a dummy variable with 1 i = 1 # Iterate until the given condition is true while i < 10: # printing the current value of the above variable print(i) # incrementing the value of i value by 1 i += 1
Output
When executed, the above program will generate the following output -
1 2 3 4 5 6 7 8 9
When should you use For and While loops?
A for loop is used when we know the number of iterations (i.e. how many times a statement must be executed). That's why when we initialize the for loop, we have to define the end point.
When the number of iterations is unknown, use a while loop. This can be used when we need to end a loop based on conditions other than the number of repetitions. In this case, there is no need to know the situation in advance. That's why we can use boolean expressions in the initialization of loops.
Without conditions
If no conditions are specified in for and while loops, the loops will iterate infinitely.
Without conditionals, here is the difference between for loop and while loop -
For Loop - In the example below, the loop will run an infinite number of times.
Example
l = [1] for m in l: print("TutorialsPoint") l.append(m)
Output
When executed, the above program will generate the following output -
TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint . . . . runs infinite times
We start with a list and initialize it with a single random value. Then, using a for loop and the in operator, we iterate over the elements of the list. Inside the loop it will print some random text and then we add another element to the list so the for loop will execute again because of the new element. This loop will be executed an infinite number of times.
While Loop - In the example below, the loop will run an infinite number of times.
Example
while True: print("TutorialsPoint")
Output
When executed, the above program will generate the following output -
TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint . . . . runs infinite times
差异表
比较基础 | For循环 | While循环 |
---|---|---|
关键字 | 使用for关键字 | 使用while关键字 |
已使用 | 当迭代次数已知时,使用 For 循环。 | 当迭代次数未知时使用While循环。 |
不存在条件 | 不存在条件时循环无限次运行 | 在不存在条件的情况下返回编译时错误 |
初始化的性质 | 一旦完成,不可重复 | 在while循环中,每次迭代都可以重复。 |
函数 | 要进行迭代,请使用 range 或 xrange 函数。 | while循环中没有这样的函数。 |
基于迭代的初始化 | 在循环开始时完成。 | 在 while 循环中,可以在循环体中的任何位置执行此操作。 |
生成器支持 | Python 的 for 循环可以迭代生成器。 | While 循环不能直接在生成器上迭代。 |
速度 | for 循环比 while 循环更快。 | 与 for 循环相比,While 循环相对较慢。 |
结论
在本文中,我们通过示例了解了 for 和 while 循环之间的区别,以及 while 和 for 循环的工作原理。
The above is the detailed content of In Python, what is the difference between a for loop and a while loop?. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

WebStorm Mac version
Useful JavaScript development 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.

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