Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between for loop and while loop in Python

Shulou Source: shulou.com Published: 2022-06-02 13:12:08 10月03日 Update

This article mainly explains "what's the difference between for cycle and while cycle in Python". The explanation in this article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "what's the difference between for cycle and while cycle in Python"?

In Python, the whilestatement and for statement are used to represent the loop execution of a certain piece of code.

While is followed by a condition, or a sequence (list, tuple, etc.). If the sequence is empty, it jumps out of the loop, otherwise the loop continues.

The for loop is followed by a sequence, and the number of loops is the length of the sequence

The while loop can add an else statement that executes the else when you jump out of the while

Give an example

A = 3

While a > 0:

Print (a)

A-= 1

one

two

three

four

Output:

three

two

one

Shoplist = ['apple',' mango', 'carrot',' banana']

While shoplist:

Print (3)

one

two

three

Output: output 3 until you press ctrl+c

Shoplist = ['apple',' mango', 'carrot',' banana']

While shoplist:

Print (3)

Shoplist = shoplist [: (len (shoplist)-1)] # each loop removes the last element

one

two

three

four

Output:

three

three

three

three

Shoplist = ['apple',' mango', 'carrot',' banana']

While shoplist:

Print (3)

Shoplist = shoplist [: (len (shoplist)-1)]

Else:

Print ('finished') # else statement

one

two

three

four

five

six

Output:

three

three

three

three

Finished

Shoplist = ['apple',' mango', 'carrot',' banana']

For i in shoplist:

Print (I) # where I will be assigned to the elements in shoplist one by one

one

two

three

Output:

Apple

Mango

Carrot

Banana

Shoplist = ('apple',' mango', 'carrot',' banana')

For i in shoplist:

Print (I) # where shoplist is a tuple and a for loop can also follow a tuple

one

two

three

Output:

Apple

Mango

Carrot

Banana

Thank you for your reading, the above is the content of "what is the difference between for cycle and while cycle in Python". After the study of this article, I believe you have a deeper understanding of the difference between for cycle and while cycle in Python. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Loops outputs different statements sequences learning elements content usage code that is ideas situations articles times more conditions times knowledge knowledge points Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS NVidia Huawei Linux Redmi