Some important questions about the while loop in Python to practice
- While loop execute a set a statement as long as test statement is true.
- A relevant variable has to be declared at the beginning of the loop
Until a specified condition is met, a block of statements will be periodically executed in a Python while loop. And the line in the programme that follows the loop is run when the condition changes to false.
The while loop is an example of an infinite loop. When a loop is iterated indefinitely, the number of times the loop is run isn’t explicitly stated beforehand.
Explanation of the flowchart:
- Start: The program begins execution.
- Initialize iterator: A variable (often called an iterator) is initialized with the first element of the sequence.
- Check condition: The iterator is compared to the end of the sequence. If it has reached the end, the loop terminates.
- Loop body: The code within the loop is executed using the current value of the iterator.
- Increment iterator: The iterator is updated to point to the next element in the sequence.
- Repeat: Steps 3-5 are repeated until the end of the sequence is reached.
- End: The loop ends, and the program continues with the code following the loop.
Key points about the for loop:
- The iterator automatically takes on the value of each element in the sequence.
- There’s no need for explicit incrementing or initialization of the iterator.
- The loop automatically stops when it reaches the end of the sequence.
Example
Table of Contents
Toggle# Example: Printing numbers from 1 to 10 count = 1 while count <= 10: print(count) count += 1
Breakdown:
Initialization:
count = 1: A variable named count is created and assigned the value 1. This variable will be used to keep track of the numbers to be printed.
Condition:
while count <= 10: This line starts a while loop. The loop will continue to execute as long as the value of count is less than or equal to 10.
Loop Body:
print(count): This line prints the current value of count to the console.
count += 1: This line increments the count variable by 1 for the next iteration of the loop.
Loop Termination:
Once count becomes greater than 10, the loop condition becomes false, and the loop ends.
Key Points:
The while loop is used for indefinite iteration, meaning the number of times it runs isn’t predetermined.
The loop continues as long as the specified condition is true.
Indentation is crucial in Python to define the code block that belongs to the loop.
Example Output:
1
2
3
4
5
6
7
8
9
10
Calculate the sum of numbers from 1 to n
n = int(input("Enter a number: ")) sum = 0 i = 1 while i <= n: sum += i i += 1 print("Sum =", sum)
Check if a number is prime
num = int(input("Enter a number: ")) i = 2 flag = 0 while i < num: if num % i == 0: flag = 1 break i += 1 if flag == 0: print(num, "is a prime number") else: print(num, "is not a prime number")
Find the sum of even numbers
n = int(input("Enter a number: ")) sum = 0 i = 2 while i <= n: sum += i i += 2 print("Sum of even numbers:", sum)
Python While Loop
# while loop
count = 0
while (count < 3):
count = count + 1
print("Vista Academy Data Science Institute")
output
Vista Academy Data Science Institute
Vista Academy Data Science Institute
Vista Academy Data Science Institute
Write a program to print table of a number entered from the user.
number = int(input("Enter a number: ")) i = 1 while i <= 10: result = number * i print(f"{number} x {i} = {result}") i += 1
Create a programme that uses a while loop to determine whether an integer is prime or not.
num1 = int(input("Enter any number: ")) if num1 <= 1: print(num1, "is not a prime number") else: is_prime = True for i in range(2, int(num1**0.5) + 1): if num1 % i == 0: is_prime = False break if is_prime: print(num1, "is a prime number") else: print(num1, "is not a prime number")
Python program to calculate the factorial of a number using a while loop.
def factorial(n): """Calculates the factorial of a non-negative integer using a while loop. Args: n: The non-negative integer to calculate the factorial of. Returns: The factorial of n. Raises: ValueError: If n is negative. """ if n < 0: raise ValueError("Factorial is not defined for negative numbers.") elif n == 0 or n == 1: return 1 else: factorial = 1 i = 2 while i <= n: factorial *= i i += 1 return factorial # Example usage: number = int(input("Enter a non-negative integer: ")) result = factorial(number) print(f"The factorial of {number} is {result}")
finds the first 10 prime numbers using a while loop
count = 0 num = 2 primes = [] while count < 10: if num <= 1: num += 1 continue if num <= 3: primes.append(num) count += 1 num += 1 continue if num % 2 == 0 or num % 3 == 0: num += 1 continue i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: num += 1 break i += 6 else: primes.append(num) count += 1 num += 1 print(primes)
Reverse a number
num = int(input("Enter a number: ")) reverse = 0 while num > 0: remainder = num % 10 reverse = (reverse * 10) + remainder num //= 10 print("Reversed number:", reverse)
Find the sum of odd numbers
n = int(input("Enter a number: ")) sum = 0 i = 1 while i <= n: sum += i i += 2 print("Sum of odd numbers:", sum)
A flowchart is a graphical representation of an algorithm or process. It uses symbols to represent different actions and arrows to show the flow of control.
Flowcharts help visualize the logic of a program, making it easier to understand, debug, and modify. They are particularly helpful when dealing with complex algorithms.
A while loop is a control flow statement that repeatedly executes a block of code as long as a given condition is true.
The condition is evaluated.
If the condition is true, the code inside the loop is executed.
The condition is evaluated again.
Steps 2 and 3 repeat until the condition becomes false.
count = 0 while count < 5: print(count) count += 1
An infinite loop occurs when the condition in a while loop never becomes false. To avoid it, ensure that the condition will eventually become false.
Vista Academy Master Program in Data Science
Vista Academy’s Master Program in Data Science offers in-depth training in advanced topics such as machine learning, artificial intelligence, big data analytics, and predictive modeling. Gain hands-on experience with Python, R, SQL, and TensorFlow to build a strong foundation for your career in data science.
Address: Vista Academy, 316/336, Park Rd, Laxman Chowk, Dehradun, Uttarakhand 248001