Software Development Exam  >  Software Development Notes  >  Basics of Python  >  While Loops in Python

While Loops in Python | Basics of Python - Software Development PDF Download

Introduction

When writing programs, we often come across situations where we need to repeat a certain set of instructions until a specific condition is met. This is where loops come in handy. One type of loop in Python is the while loop. A while loop repeatedly executes a block of code as long as a given condition is true. In this article, we will explore the concept of while loops, understand their syntax, and go through various examples to solidify our understanding.

Syntax of a While Loop

The syntax of a while loop in Python is as follows:

while condition:

    # code block to be executed

The 'condition' is an expression that evaluates to either 'True' or 'False'. The code block inside the loop will be executed as long as the condition is true. It is important to ensure that the condition eventually becomes false; otherwise, the loop will continue indefinitely, resulting in an infinite loop.

Example 1: Counting with a While Loop

Let's start with a simple example to demonstrate how a while loop works. Consider the following code that counts from 1 to 5:

count = 1

while count <= 5:

    print(count)

    count += 1

Output:

1

2

3

4

5

Explanation:

  • We initialize the variable 'count' to 1.
  • The while loop checks if 'count' is less than or equal to 5. Since it is true initially, the loop is executed.
  • Inside the loop, we print the current value of 'count' and then increment it by 1 using the '+=' operator.
  • After the loop body is executed, the condition is checked again. If it is still true, the loop continues. This process repeats until the condition becomes false (when 'count' is greater than 5).

Example 2: User Input with a While Loop

A while loop can be useful when we want to repeatedly prompt the user for input until a specific condition is met. Let's see an example where we ask the user to enter a positive number:

number = -1

while number <= 0:

    number = int(input("Enter a positive number: "))

print("You entered:", number)

Output:

  • Enter a positive number: -2
  • Enter a positive number: 0
  • Enter a positive number: 5
  • You entered: 5

Explanation:

  • We initialize the 'variable' number to -1 to ensure that the loop runs at least once.
  • Inside the loop, we prompt the user to enter a positive number using the 'input()' function and convert the input to an integer using 'int()'.
  • If the entered number is less than or equal to 0, the condition remains true, and the loop repeats. Once the user enters a positive number, the condition becomes false, and the loop terminates.
  • Finally, we print the positive number entered by the user.

Example 3: Countdown Timer

Let's create a countdown timer using a while loop. We will start from a given number and keep decrementing it until it reaches 0:

import time

countdown = 10

while countdown > 0:

    print(countdown)

    time.sleep(1)

    countdown -= 1

print("Blast off!")

Output:

10

9

8

7

6

5

4

3

2

1

Blast off!

Explanation:

  • We import the 'time' module to use the 'sleep()' function, which delays the execution of the loop by 1 second.
  • We initialize the variable 'countdown' to 10.
  • Inside the loop, we print the current value of 'countdown', wait for 1 second using 'time.sleep(1)', and then decrement it by 1 using the '-=' operator.
  • Once the loop terminates (when countdown becomes 0), we print "Blast off!".

Example 4: Infinite Loop

It is important to ensure that the condition in a while loop eventually becomes false; otherwise, the loop will run indefinitely, resulting in an infinite loop. Consider the following example:

while True:

    print("This is an infinite loop!")

Output:

This is an infinite loop!

This is an infinite loop!

This is an infinite loop!

...

Explanation:

The condition in this while loop is 'True', which is always true. Therefore, the loop will continue indefinitely, printing "This is an infinite loop!" repeatedly.

Example 5: Using a While Loop to Filter a List

A while loop can be used to filter a list based on a specific condition. Let's see an example where we filter out negative numbers from a list of integers:

numbers = [5, -2, 10, -8, 3, -1]

filtered_numbers = []

index = 0

while index < len(numbers):

    if numbers[index] >= 0:

        filtered_numbers.append(numbers[index])

    index += 1

print("Original list:", numbers)

print("Filtered list:", filtered_numbers)

Output:

  • Original list: [5, -2, 10, -8, 3, -1]
  • Filtered list: [5, 10, 3]

Explanation:

  • We define a list of integers 'numbers'.
  • We initialize an empty list 'filtered_numbers' and a variable 'index' to 0.
  • Inside the loop, we check if the current element in numbers is greater than or equal to 0. If it is, we append it to 'filtered_numbers'.
  • We increment 'index' by 1 after each iteration of the loop.
  • Once the loop terminates (when 'index' becomes equal to the length of 'numbers'), we print both the original list and the filtered list.

Sample Problems

Now that we have seen various examples of while loops, let's try some practice problems.

Problem 1: Factorial Calculator
Write a program that takes an integer input from the user and calculates its factorial using a while loop. The factorial of a non-negative integer n is defined as the product of all positive integers less than or equal to n.

Example:
Enter a number: 5
Factorial of 5 is 120

number = int(input("Enter a number: "))

factorial = 1

while number > 0:

    factorial *= number

    number -= 1

print("Factorial of", number, "is", factorial)

Problem 2: Fibonacci Sequence
Write a program that takes an integer input from the user and prints the first n terms of the Fibonacci sequence using a while loop. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers.

Example:
Enter a number: 7
Fibonacci sequence: 0 1 1 2 3 5 8

number = int(input("Enter a number: "))

a, b = 0, 1

fibonacci_sequence = []

while number > 0:

fibonacci_sequence.append(a)

a, b = b, a + b

number -= 1

print("Fibonacci sequence:", ' '.join(map(str, fibonacci_sequence)))

Conclusion

In this article, we have explored the concept of while loops in Python. We learned about their syntax and how they can be used to repeat a block of code as long as a given condition is true. We covered various examples, including counting, user input, countdown timer, filtering a list, and infinite loops. Finally, we solved sample problems involving factorial calculation and generating the Fibonacci sequence. By practicing and experimenting with while loops, you can enhance your programming skills and effectively solve repetitive tasks in your programs.

The document While Loops in Python | Basics of Python - Software Development is a part of the Software Development Course Basics of Python.
All you need of Software Development at this link: Software Development
49 videos|38 docs|18 tests

Top Courses for Software Development

49 videos|38 docs|18 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

While Loops in Python | Basics of Python - Software Development

,

past year papers

,

While Loops in Python | Basics of Python - Software Development

,

Free

,

Summary

,

MCQs

,

Viva Questions

,

Previous Year Questions with Solutions

,

ppt

,

Exam

,

mock tests for examination

,

video lectures

,

While Loops in Python | Basics of Python - Software Development

,

practice quizzes

,

study material

,

Important questions

,

Semester Notes

,

shortcuts and tricks

,

Sample Paper

,

Objective type Questions

,

Extra Questions

,

pdf

;