Hướng dẫn while loop counter python

Vòng lặp được sử dụng trong lập trình Python để lặp lại một khối mã cụ thể. Trong bài đăng này, bạn sẽ học cách tạo vòng lặp while trong Python.

  • Python While Loop
    • Cú pháp
      • Đầu ra
  • Vòng lặp While trong Python với else
  • Câu lệnh break trong Python

Trong khi lặp lại Trong Python được sử dụng để lặp lại khối mã miễn là kiểm tra tình trạng) là đúng. Vòng lặp While được sử dụng để thực hiện tập hợp các câu lệnh miễn là điều kiện là đúng. Vòng lặp while yêu cầu máy tính thực hiện điều gì đó nếu điều kiện được đáp ứng hoặc giữ nguyên. Cấu trúc của nó bao gồm khối mã và điều kiện. Điều kiện được đánh giá và nếu điều kiện là đúng, mã trong khối sẽ được thực thi. Nó lặp lại cho đến khi điều kiện trở thành sai.

Chúng ta thường sử dụng vòng lặp while khi chúng ta không biết số lần lặp lại.

Xem cú pháp sau của vòng lặp while.

Cú pháp

Xem cú pháp sau của vòng lặp while.

while test_expression:
    { body of while }

Trong vòng lặp while, biểu thức kiểm tra được kiểm tra đầu tiên. Sau đó, phần thân của một vòng lặp chỉ được nhập khi test_expression đánh giá ĐÚNG VẬY.

Sau một lần lặp, biểu thức kiểm tra được kiểm tra lại. Quá trình này tiếp tục cho đến khi text_expression đánh giá Sai. Hãy nhớ rằng, chúng ta cần thay đổi giá trị bằng cách nào đó. Nếu không, nó sẽ đi vào một vòng lặp vô hạn.

Trong Python, phần thân của vòng lặp while được xác định bằng cách thụt lề. Phần nội dung bắt đầu bằng một dấu thụt lề và dòng đầu tiên không có dấu đầu dòng đánh dấu phần cuối. Python diễn giải mọi giá trị khác 0 thành ĐÚNG VẬY. Không có và 0 được hiểu là Sai.

Xem ví dụ sau về vòng lặp while trong Python.

# app.py

i = 21
while i < 29:
  print(i)
  i += 1

Đầu ra

Trong chương trình trên, biểu thức kiểm tra sẽ giữ miễn là biến của chúng ta tôi nhỏ hơn hoặc bằng 29 trong chương trình của chúng tôi bắt đầu từ 21.

Chúng ta cần tăng giá trị của biến i trong phần thân của vòng lặp. Nó rất cần thiết và hầu như bị lãng quên. Nếu chúng ta không làm như vậy sẽ dẫn đến một vòng lặp vô hạn hoặc vòng lặp không bao giờ kết thúc. Cuối cùng, kết quả được hiển thị.

Vòng lặp While trong Python với else

Hãy lấy một ví dụ về vòng lặp while với người khác bằng Python.

Nếu bạn đã sử dụng Python For Loop, chúng tôi đã chặn tương tự ở đây vì chúng tôi có thể có tùy chọn khác khối với vòng lặp while.

Các khác một phần được thực thi nếu điều kiện trong vòng lặp while đánh giá là Sai.

Một vòng lặp while có thể được dừng lại bằng câu lệnh break. Trong trường hợp như vậy, khác một phần bị bỏ qua. Do đó, vòng lặp while là khác phần chạy nếu không xảy ra ngắt và điều kiện là sai.

Đây là một ví dụ.

# app.py

counter = 0

while counter < 3:
    print(counter)
    counter = counter + 1
else:
    print('Executed Else Statement')

Trong đoạn mã trên, bộ đếm được in trừ khi điều kiện sai. Sau khi điều kiện sai, khác khối được thực thi. Xem kết quả bên dưới.

Hướng dẫn while loop counter python

Câu lệnh break trong Python

Với câu lệnh break, chúng ta có thể dừng vòng lặp ngay cả khi điều kiện while là đúng.

# app.py

i = 1
while i < 5:
  print(i)
  if i == 3:
    break
  i += 1

Xem kết quả bên dưới.

Hướng dẫn while loop counter python

Đó là nó cho hướng dẫn này.

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.

Nội dung chính

  • Video: Python while Loop
  • What is while loop in Python?
  • Syntax of while Loop in Python
  • Flowchart of while Loop
  • Example: Python while Loop
  • While loop with else
  • Table of Contents
  • Not the answer you're looking for? Browse other questions tagged python loops while-loop menu continue or ask your own question.

Video: Python while Loop

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax of while Loop in Python

while test_expression:
    Body of while

In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

The body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Flowchart of while Loop

Flowchart for while loop in Python

Example: Python while Loop

# Program to add natural
# numbers up to 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)

When you run the program, the output will be:

Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).

We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).

Finally, the result is displayed.


While loop with else

Same as with for loops, while loops can also have an optional else block.

The else part is executed if the condition in the while loop evaluates to False.

The while loop can be terminated with a break statement. In such cases, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Here is an example to illustrate this.

'''Example to illustrate
the use of else statement
with the while loop'''

counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the fourth iteration, the condition in while becomes False. Hence, the else part is executed.

Table of Contents

  • What is while loop in Python?
    • Syntax of while Loop in Python
    • Flowchart of while loop
    • Example: Python while Loop
  • While loop with else

I am writing a program that has multiple options to modify a dictionary in python. The user has four options, and after completing an option I want the program to bring back the user to the main menu. So far, every option works correctly except it doesn't bring the user back to the main menu, and instead loops for ever

user_input = int(input("Faites un choix..."))
liste_epicerie = {}
while True:

    if user_input == 1:
        print(liste_epicerie)
        if liste_epicerie == {}:
            print("La liste est vide")
            continue

So this code should bring back the user to user_input, but instead prints "La liste est vide" for ever. What am I doing wrong?

asked Sep 30, 2019 at 15:08

1

You have to actually read the user input again (inside the loop):

liste_epicerie = {}

while True:
    user_input = int(input("Faites un choix..."))
    if user_input == 1:
        # ...
    elif ...:
        # ...
    # under some condition
    break

The variable user_input does not magically remember and repeat how its value came to be.

answered Sep 30, 2019 at 15:10

user2390182user2390182

68.5k6 gold badges60 silver badges82 bronze badges

sum=0
count=0
while True:
  n=input ("enter the value :")
  if n=="exit":
    break
    try:
     float(n)
    except:
     print ("enter the numeric value")
  continue
   sum=sum+n
   count=count+1
print(sum,count,sum/count)

cigien

55.9k11 gold badges64 silver badges103 bronze badges

answered Oct 11, 2021 at 1:23

1

Not the answer you're looking for? Browse other questions tagged python loops while-loop menu continue or ask your own question.