Разница for while python

Что выбрать for или while?

Больше теоритический вопрос выбора. На мой субъективный взляд и я указывал на это в нескольких ответах на SO, я почти всегда искользую for . И только где необходим бесконечный цикл (например слушать входящие сообщения) я использую while . Есть ли конкретные правила где и почему надо использовать ту или иную конструкцию?

Для каждой конкретной задачи нужно выбирать то что вам подходит лучше всего в данный момент. Считаю что вопрос нужно закрыть не по причине «слишком простой» а по причине «нельзя дать однозначный ответ», т.к. сейчас ответ на данный вопрос будет пересказыванием главы учебника про циклы.

@Dmitry простите, а если у «них» станет модно прыгать с моста, вы предлагаете и нам начать повторять? Не вижу засилья таких вопросов на ruSO, как и не вижу необходимости разжевывать то что есть в каждом учебнике. Ответ в пять строк не даст понимания когда конкретно это использовать в граничных случаях, и может в таковых быть даже вредным, считаю что данный вопрос имеет право на существование только если автор вопроса сделает подробную выдержку в виде ответа, о которой вы говорите, иначе это скатится к пересказу документации.

4 ответа 4

В принципе, на английском SO нормально написано. Но даже не заглядывая туда я был готов дать такой же ответ по сути.

for — для перебора элементов такой сущности, по которой можно итерироваться: коллекция, генератор, итератор.

while — для бесконечного цикла, а также для циклов, где нет последовательного перебора сущностей, а есть некое условие окончания цикла, либо вычисляемое, либо зависящее от ввода пользователя или какого-то другого недетерминированного события.

Большинство циклов в питоне всё же сводится к for , потому что обычно требуется именно что-то перебрать, какую-то коллекцию: список объектов, диапазон чисел, строки файла, выборку из базы данных.

Читайте также:  Access class method java

Да, while при желании тоже можно использовать для перебора сущностей, но это будет: более длинно, менее красиво и менее понятно. И наоборот, превратить while в for теоретически тоже можно, но это будет ещё более сложно, непонятно и бессмысленно.

Источник

What is The Difference Between For and While Loop in Python?

Loops are the most powerful and basic concept in computer programming. A loop is an instruction that executes a statement until a specific condition is reached. The number of times the loop repeats itself is known as iteration. Some loop controlling statements are break and continue. Various types of loops are for, while, do while, etc. Every programming language, including C, C++, Java, Python, etc., has the concept of a loop.

  1. For loop: A for loop is a control flow statement that executes code repeatedly for a particular number of iterations. In this control flow statement, the keyword used is for . The for loop is used when the number of iterations is already known.

The for loop has two parts:

  • Header: The header part specifies the iteration of the loop. In this part, the loop variable is also declared, which tells the body which iteration is executed.
  • Body: This part contains the statement executed per iteration.

Let’s see the flow of the for loop:

Flow of for Loops

  • Initialise the starting value
  • Check that the starting value is less than the stopping value.
  • Execute the statement.
  • Increment the starting value. Let’s see how the for loop works.

Syntax of for loop:

Example of for loop:

Flow for While Loops

  1. While loop: A loop that executes a single statement or a group of statements for the given true condition. The keyword used to represent this loop is «while«. A «while» loop is used when the number of iterations is unknown. The statement repeats itself till the boolean value becomes false. In a while loop, the condition is tested at the start, also known as the pre-test loop. Let’s see the flow of the while loop:
  • Initialise the starting value
  • Check that the starting value is less than the stopping value.
  • Execute the statement.
  • Increment the starting value. Let’s see how the while loop works.
Читайте также:  Java jmx management javax

Syntax of while loop:

Example of while loop:

Initialization in Accordance to Iteration

In the case of the for loop, the syntax gets executed when the initialization is at the top of the syntax. On the other hand, in the case of the while loop, the position of the initialization statement does not matter for the syntax of the while loop to get executed.

When to Use?

The for loop is used when we already know the number of iterations, which means when we know how many times a statement has to be executed. That is why we have to specify the ending point in the for loop initialization.

When we need to end the loop on a condition other than the number of times, we use a while loop. In this case, it is not necessary to know the condition beforehand. That is why we can give a boolean expression in the initialization of the loop.

Absence of Condition

When no condition is given in the for and while loop, the for loop will iterate infinite times.. The difference between for loop and while loop in the absence of condition:

Initialization Nature

In the case of a for loop, the initialization is done once at the start, so there is no need to initialize it again. But in the case of a while loop, we require to initialize the loop manually by taking a variable that is further modified (incremented, decremented, multiplied, etc.) as per our requirement.

For vs While Loop in Python

Let’s see the difference between the for loop and the while loop:

Читайте также:  Monte carlo tree search python
Parameter For Loop While Loop
Keyword For Keyword is used. While Keyword is used.
Use Number of iterations already known. No prior information on the number of iterations.
In absence of condition Loop runs infinite times. Display the compile time error.
Initialization Nature Once done cannot be repeated. Repeat at every iteration.
Initialization in accordance with iteration To be done at starting of the loop. Can be done anywhere in the loop body.
Function used Range or xrange function is used to iterate. No such function is used in the while loop.
Generator Support For loop can be iterated on generators in Python. While loop cannot be iterated on Generators directly.
Speed For loop is faster than while loop. While loop is slower as compared to for loop.

So these were the main difference between the for loop and the while loop.

Learn More

Conclusion

Let’s conclude our topic, «difference between for loop and while loop,» by mentioning some of the important points.

  • In a for loop, the set of declarations, including iterations and conditions, sits at the top of the body.
  • In a while loop, initialization is always outside the loop. Before or after the execution of the statement(s), update can be performed.
  • A for loop is a control flow statement that executes code repeatedly for a particular number of iterations.
  • A loop that executes a single statement or a group of statements for the given true condition. The keyword used to represent this loop is while .
  • When no condition is given in the for loop, the loop will iterate infinite times, while in the case of the while loop, it will give an error (compile time error).

Источник

Оцените статью