Python While loops

Python While Loop

A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. It’s often used when you don’t know in advance how many times you need to execute the loop, but you want to keep executing as long as a condition remains true.
 
Syntax:
while condition:
#block of code
 
Example:
Write a program that prints the numbers from 1 to 3, each on a new line, and then prints “Loop has ended.” on the 4th.

count = 1
while count <= 3:
print(count)
count+=1
print(“Loop has ended”)

”’
Output:
1
2
3
Loop has ended
”’

Explanation:

count = 1

This line declares an variable named count and initializes it with the value 1

while count <= 3:

This is a while loop that will execute the code inside the indented block as long as the condition count <= 3 is true.

First Iteration:
The initial value of the count is 1. The loop checks if count (1) is less than or equal to 3. Since 1 is less than 3, the code inside the block runs. The current value of count (1) is printed. The count is then increased by 1, so the count becomes 2.

Second Iteration:
The value of the count is now 2. The loop checks if count (2) is less than or equal to 3. Since 2 is less than 3, the code inside the block runs. The current value of count (2) is printed. The count is then increased by 1, so the count becomes 3

Third Iteration:
The value of the count is now 3. The loop checks if count (3) is less than or equal to 3. Since 3 is equal to 3, the code inside the block runs. The current value of count (3) is printed. The count is then increased by 1, so the count becomes 4.

Fourth Iteration:
The value of the count is now 4. The loop checks if count (4) is less than or equal to 3. Since 4 is not less than or equal to 3, the loop stops running.

    print(count)

This line prints the current value of count.

    count+=1

This line increments the value of the count by 1.

print(“Loop has ended”)

This line prints “Loop has ended.” after the loop has finished execution.

Nested While Loop Statement
A nested while loop is a control structure where one while loop is placed inside another while loop. This allows for complex iteration patterns where the inner loop completes all its iterations for each iteration of the outer loop. Nested while loops can be useful in various scenarios, such as processing multi-dimensional data structures or implementing certain algorithms that require multiple levels of iteration.
 
Syntax:
while condition:
while condition:
#block of code
 
 
Example:
Write a program using a nested while loop to generate and print a multiplication table for the number 2. The table should display the multiplication results from 2 × 1 to 2 × 5 on each line 

i = 2
while i <= 2:
j = 1
while j <= 5:
result = i * j
print(f”{result}\t”, end=””) # Use `end=””` to stay on same line
j += 1
print() # Move to the next line after inner loop
i += 1
#Output: 2 4 6 8 10

Explanation:

i = 2

This line declares a variable named i and initializes it with the value 2

while i <= 2:

This is a while loop that will execute the code inside the block as long as the condition
count <= 2 is true.

    j = 1

This line declares a variable named j and initializes it with the value 1

    while j <= 5:

This is a while loop that will execute the code inside the block as long as the condition j <= 5 is true.

1. The value of j is 1. The loop checks if j (1) is less than or equal to 5. Since 1 is less than 5, the code inside the block runs. The current value of j (1) is printed. The j is then increased by 1, so j becomes 2.

2. The value of j is now 2. The loop checks if j (2) is less than or equal to 5. Since 2 is less than 5, the code inside the block runs. The current value of j (2) is printed. The j is then increased by 1, so j becomes 3.

3. The value of j is now 3. The loop checks if j (3) is less than or equal to 5. Since 3 is less than 5, the code inside the block runs. The current value of j (3) is printed. The j is then increased by 1, so j becomes 4.

4. The value of j is now 4. The loop checks if j (4) is less than or equal to 5. Since 4 is less than 5, the code inside the block runs. The current value of j (4) is printed. The j is then increased by 1, so j becomes 5.

5. The value of j is now 5. The loop checks if j (5) is less than or equal to 5. Since 5 is equal to 5, the code inside the block runs. The current value of j (5) is printed. The j is then increased by 1, so j becomes 6.

6. The value of j is now 6. The loop checks if j (6) is less than or equal to 5. Since 6 is not less than or equal to 5, the loop stops running. This loop will print the values from 1 to 5 and then stop when j becomes 6.

        result = i * j

Calculates the multiplication result of i and j and assigns it to the variable result.

        print(f”{result}\t”, end=””)

Prints the value of the result followed by a tab space (\t). This prints the multiplication result without moving to the next line.

        j += 1

Increments the value of j by 1 to move to the next number in the inner loop.

    print() 

Move to the next line in the output after all numbers for the current value of i have been printed in the inner loop.

    i += 1

Increments the value of i by 1 to move to the next number in the outer loop. However, since i is already 2 not after incrementing it became 3 so the condition of outer loop has become false now. So the outer loop will stop too.

Task:
Example 1: Print numbers from 1 to 5

i = 1 #variable i with value 1
while i <= 5: #while loop will run till i is less than or equal to 5
print(i,end=’ ‘) #prints the value of i
i += 1 #increments the value of i by 1
#Output: 1 2 3 4 5

Example 2: Print even numbers between 1 and 10

i = 1 #variable i with value 1
while i <= 10: #while loop will run till i is less than or equal to 10
if i % 2 == 0: #condition to check if even or not
print(i,end=’ ‘) #prints the value of i
i += 1 #increments the value of i by 1
#Output: 2 4 6 8 10

Example 3: keep asking the user for the correct password until they enter “iqra123”.

password = “iqra123” #assigning ‘iqra123’ in password variable
user_input = “” #initializing empty user_input
while user_input != password:
#while loop will run till the condition is true

user_input = input(“Enter the password: “) Taking user input
if user_input != password: #checking if input is same as password
print(‘Wrong password, try again!’)

else: #if condition is not met
Break #break out of loop

print(“Access granted!”)

Output:

password = “iqra123” #assigning ‘iqra123’ in password variable
user_input = “” #initializing empty user_input
while user_input != password:
#while loop will run till the condition is true

user_input = input(“Enter the password: “) Taking user input
if user_input != password: #checking if input is same as password
print(‘Wrong password, try again!’)

else: #if condition is not met
Break #break out of loop

print(“Access granted!”)

Task:
1. Print Odd Numbers:
Use a while loop to print all odd numbers between 1 and 20.
Inside the loop, use an if-else statement to check if the number is odd before printing.

2. Guess the Number:
Use a do-while loop to implement a number guessing game.
Use an if-else statement to check if the guessed number is higher, lower, or equal to the target number.
Keep looping until the correct number is guessed.
Define guessing number as 6
Input number from 1,2,3,4,5,6. When number 6 is given as input, the program will exit.

3. Sum of Even Numbers:
Use a while loop to sum all even numbers between 1 and 50.
Inside the loop, use an if-else statement to check if the number is even before adding it to the sum.

4. Temperature Conversion:
Use a while loop to iterate through a list of temperatures in Celsius. L1 = [30, 40, 39, 49, 54]
Inside the loop, convert each temperature to Fahrenheit. Print each temperature in fahrenheit

5. Student Grade Classification:
Use a while loop to iterate through an array of student grades.
Inside the loop, use a switch statement to classify the grades (‘A’, ‘B’, ‘C’, ‘D’, ‘F’).
Inside each switch case, use an if-else statement to print a motivational message for grades A and B.

6. Print Prime Numbers:
Use a while loop to print all prime numbers between 1 and 100.
Inside the loop, use an if-else statement to check if the number is prime before printing.

7. Check if a number is a palindrome. A palindrome number is a number that reads the same backwards as forwards. For e.g. 1221, 121, 14441.
Hint: reverse the input number and store it in reverse variable. Compare the input and reversed number.

Course Video

YouTube Reference :