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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Serialization and Deserialization of Python Objects: Part 1 Serialization and Deserialization of Python Objects: Part 1 Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Mathematical Modules in Python: Statistics Mathematical Modules in Python: Statistics Mar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Scraping Webpages in Python With Beautiful Soup: Search and DOM Modification Scraping Webpages in Python With Beautiful Soup: Search and DOM Modification Mar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python? How to Create Command-Line Interfaces (CLIs) with Python? Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles