Table of Contents
For Loop
grammar
Example
Output
While Loop
When should you use For and While loops?
Without conditions
差异表
结论
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?

Sep 09, 2023 pm 03:37 PM
difference for loop while循环 (while loop)

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!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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 efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles