Bytes

home

bytes

tutorials

python

while loop in python

While loop in Python

Module - 3 Loops and Iterations in Python
While loop in Python

Overview:

The Python While Loop ūüĒĀ repeatedly executes a block of statements ¬†until a specified condition :thinking: becomes false. Once the condition becomes false, the first line after the Loop executes.

A while loop is a type of indefinite iteration . The while loop continues looping  as long as the condition remains true. When the condition becomes false, the Loop terminates and the first statement after executing the loop body.

While loop in Python-min.png

What is While Loop in Python?

"A while loop in Python is a control flow statement that allows a block of code to be executed repeatedly based on a given Boolean condition. In other words, the while loop will keep iterating and running the code block inside of it until the specified condition evaluates to False.‚ÄĚ

Syntax of While Loop in Python

while condition:
    statements
  • A while loop in Python repeats a code block while an expression is true.
  • The while keyword starts the Loop.
  • An expression follows that evaluates to true or false.
  • The indented statement after the expression is the loop body.
  • The body repeats while the expression is true.
  • The expression checks the loop condition.
  • The body contains the code that runs on each iteration of the Loop.

Working of while:

A while loop in Python continually executes a code block if a specified condition is true. The Loop will run the code block repeatedly until the condition becomes false. Once the condition is false, the program exits the while loop and continues.

The condition for the Loop can be any expression that evaluates to true or false. True is any non-zero value. The Loop can also be terminated early using the break statement. While loops are a helpful control structure that allows a program to execute a set of statements multiple times. They run the code block within the Loop repeatedly until the defined condition is no longer met.

Example of Python While Loop

# Initialize counter
counter = 0

# While loop
while counter < 10:
    print(counter)
    # Increment counter
    counter += 1

This code is an example of Python while Loop. The code initializes a counter variable to 0, then prints the counter value and increments the counter by 1 until the counter is no longer less than 10. The output of this code will be a list of numbers from 0 to 9.

While Loop with else

Let's further discuss while Loop with else. Let's check the syntax. A while loop with else executes a block of code as long as a given condition is true. Once the condition becomes false, the else block of code is executed. The else block of code is executed only if the condition is false. This is useful for ensuring that certain code is executed at least once or after the while loop ends.

Syntax

while <condition>:
    <code to execute>
else:
    <code to execute>

Example:

i = 0
while (i <= 100 and i % 7 != 0):
  i += 1
else:
  if (i % 7 == 0):
    print("The first number divisible by 7 is", i)
  else:
    print("No number is divisible by 7")

This code uses a while loop with an else statement to find the first number divisible by 7 between 0 and 100. The while loop checks if the value of i is less than or equal to 100 and is not divisible by 7, and if it is not, then it increments the value of i by 1. The else statement checks if the value of i is divisible by 7; if it is, then it prints the value of i. If the while loop fails to find any number divisible by 7, then the else statement prints that no number is divisible by 7.

Single Statement While Loop in Python

while condition:
    statement

Example:

i=0
while i < 5:
    print(i)
    i += 1

This while loop will execute the print(i) statement repeatedly if the condition i < 5 evaluates to True. On each iteration of the Loop, the value of i is incremented by 1 using the i += 1 statement. The Loop will continue printing the value of i and incrementing it until i reach the value of 5. At this point, the condition i < 5 will become False, and the Loop will exit, proceeding to the first statement after the while loop. In summary, this while loop will print the numbers 0 through 4, and then the Loop will terminate.

The Infinite While Loop in Python

The infinite while loop in Python continuously executes the code inside the Loop until the user stops it. This Loop runs endlessly unless the user explicitly ends the Loop or an error occurs. The Loop can perform tasks that need constant looping, like checking for user input or monitoring a system.

Example:

while True:
    print("Data scientists are like artists, except instead of paint and canvas, they use data and algorithms to create a masterpiece.")

An infinite while loop continually executes in Python until a specified condition is met. For example, the Loop below will print "Hello World" repeatedly until the Loop is manually stopped. This Loop is useful when code needs to run until certain criteria are satisfied, such as continually accepting user input.

Conclusion:

This lesson provides an overview of Python while Loop, which repeatedly executes a code block until a specified condition becomes false. The lesson covers the syntax ūüďĚūüďĚ of the while loop, how it works, and provides examples ūüďä of its use, including while loops with else statements ūü§Ě, single statement while loops, and infinite while loops ūüĒĀ.

Key takeaways:

  1. A while loop executes a code block repeatedly until a specified condition is met.
  2. The Loop continues until the condition becomes false.
  3. While loops can iterate over lists, strings, collections, and more.
  4. If the condition is initially false, the loop body will not execute.
  5. Using a proper condition in the while loop is essential to avoid an infinite loop.

Quiz:

  1. What is the purpose of a while loop? 
    1. To iterate multiple times through a loop 
    2. To evaluate a condition before proceeding 
    3. To execute a block of code until the condition is false 
    4. To repeat a set number of times

Answer: C. To execute a block of code until the condition is false.

  1. How is a while loop entered in a program?
    1. By typing the keyword ‚Äúwhile‚Ä̬†
    2. By calling the loop function 
    3. By setting a condition 
    4. By defining a loop variable

Answer: A. By typing the keyword ‚Äúwhile‚ÄĚ.

  1. When does a while loop stop executing?
    1. When the condition is false 
    2. When the condition is true 
    3. When a break statement is encountered 
    4. When the loop is exited

Answer: A. When the condition is false.

  1. What is the output of the following code?
a = [1, 2, 3]

i = 0

while i < len(a):
    a[i] = a[i] ** 2
    i += 1

a. [1, 4, 9] 

b. [1, 2, 3] 

c. [2, 4, 6] d. [1, 3, 5]

Answer: A. [1, 4, 9]

Recommended Courses
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter