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.
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.
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:
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:
Explanation:
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:
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.
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:
Explanation:
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)))
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.
49 videos|38 docs|18 tests
|
|
Explore Courses for EmSAT Achieve exam
|