Home > Backend Development > Python Tutorial > In Python, what is the difference between a for loop and a while loop?

In Python, what is the difference between a for loop and a while loop?

WBOY
Release: 2023-09-09 15:37:02
forward
1760 people have browsed it

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
}
Copy after login

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)
Copy after login

Output

When executed, the above program will generate the following output -

Input list elements:
10
20
30
40
50
Copy after login

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
}
Copy after login

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 
Copy after login

Output

When executed, the above program will generate the following output -

1
2
3
4
5
6
7
8
9
Copy after login

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)
Copy after login

Output

When executed, the above program will generate the following output -

TutorialsPoint
TutorialsPoint
TutorialsPoint
TutorialsPoint
TutorialsPoint
TutorialsPoint
.
.
.
.
runs infinite times
Copy after login
Copy after login

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")
Copy after login

Output

When executed, the above program will generate the following output -

TutorialsPoint
TutorialsPoint
TutorialsPoint
TutorialsPoint
TutorialsPoint
TutorialsPoint
.
.
.
.
runs infinite times
Copy after login
Copy after login

差异表

比较基础 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!

source:tutorialspoint.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template