loops

Whenever we want to repeat some operation, we need loops. There are different types of looping techniques in Python. Firstly, let us go through the while loop. while loop runs or executes a piece of code repeatedly if a certain condition(or expression) evaluates to True. The execution will stop when the given condition(or expression) evaluates to False. The syntax of while is as follows:

while expression:

statement

Note that, just like if statements, indentation is necessary in while statements as well.

Let us see an example,

Here, initially the value of x is True. So, the expression x in line number 2 is satisfied. So, the “hi” in line number 3 will be printed. In the last line of the loop(line number 4), the value of x is set to False. After this, the loop tries to execute lines 3 and 4 again. But as the value of x is False, the expression fails at line number 2. At this point the loop stops. So, we get only one “hi” printed in the output. So, this piece of code is actually not repeating any operation. Let us take a more relevant example to understand loops.

Output:

hi

hi

hi

In this example, the value of x is initialized with 1 in line number 1. Then the condition is checked in line number 2 whether the value of x is less than 4 or not. The condition is satisfied and the loop proceeds to the execution of lines 3 and 4. It prints “hi” and increments the value of x. As the value of x is now 2, it again satisfies the condition and proceeds to line number 3 and 4. This will continue for values of x up to 3 because the express says x<4. After it prints “hi” for the third time, the value of x will be incremented and the value becomes 4 but the condition fails at this point and the loop stops. So, we get “hi” printed three times in the console. This is how the while loop works. 

Please note that if we don’t increment the value of x in line number 4, the code will go into an infinite loop as the value of x remains 1 and the condition is always satisfied.

The while loop also helps us to loop(or iterate) through sequence data types as well. For example, to loop through

string:

Output:

E

d

u

p

o

l

y

In the same way, the len() function can also be used with lists. So, lists can also be looped in a similar way:

Output:

1

5

2

7

3

9

But Python also provides us with a for loop to iterate or loop through sequences. It is easier to read and understand. For example,

Output:

E

d

u

p

o

l

y

Output:

1

4

2

6

3

7

These are the different basic looping techniques in Python. We will learn about more advanced looping techniques later on.

The range() function

The range function returns an object which can be iterated(an iterable). Let’s take a simple example:

range(5) returns an iterable object which when iterated gives us 0 to 4(excluding 5).

Let us combine this with a for loop to see the appropriate output.

Output:

0

1

2

3

4

Here, we can see that it prints 0 to 4 but not including 5. It starts from 0 by default.

We can also specify the starting point and ending point by passing two arguments to the range() function.

Output:

1

2

3

4

Here, 1 is the starting point and 4 is the ending point(not including 5).

We can also specify a step as a third argument to specify a different increment step. Let’s see it through an example:

Output:

1

3

5

7

9

We can also run a loop in the reverse direction if we use a negative step. This will decrement each value instead of incrementing it.

Output:

5

4

3

2

1

Here, the starting point is 5 and the ending point is 1(excluding 0) with a step -1. 

-1 means it will run in a negative direction by decrementing each value by 1.

Similarly, if we put -2 as a step, it will decrement each value by 2 at a time.

Output:

10

8

6

4

2

Interview Questions

Q. What is the primary purpose of a while loop in Python?

Ans. The primary purpose of a while loop is to repeatedly execute a block of code as long as a specified condition evaluates to True. The loop will terminate when the condition becomes False.

Q. Explain the syntax of a while loop and the role of indentation.

Ans. The syntax of a while loop is:

while expression:

    statement

expression: This is a condition that is evaluated before each iteration of the loop. If it’s True, the loop continues. If it’s False, the loop stops.

statement: This is the code block that is executed repeatedly as long as the expression is True.

Indentation: The statement block must be indented (typically four spaces) to indicate that it belongs to the loop. Proper indentation is crucial for Python to understand the structure of your code.

Coding Problems

Q. Write a Python program using a while loop to print numbers from 1 to 10.

Ans.

number = 1

while number <= 10:

    print(number)

    number += 1

Q. Write a Python program that calculates the sum of numbers from 1 to a given limit using a while loop.

Ans

limit = int(input(“Enter the limit: “))

number = 1

sum = 0

while number <= limit:

    sum += number

    number += 1

print(“Sum of numbers from 1 to”, limit, “is:”, sum)

Q. Write a Python program to calculate the factorial of a number using a while loop.

Ans.

num = int(input(“Enter a number: “))

factorial = 1

i = 1

while i <= num:

    factorial *= i

    i += 1

print(“Factorial of”, num, “is:”, factorial)

Q. Write a Python program that takes a number as input and prints its reverse using a while loop.

Ans

num = int(input(“Enter a number: “))

reversed_num = 0

while num > 0:

    digit = num % 10  

    reversed_num = (reversed_num * 10) + digit 

    num //= 10       

print(“Reversed number:”, reversed_num)

Q. Write a Python program to print the Fibonacci series up to a given number using a while loop.

Ans

limit = int(input(“Enter the limit: “))

a, b = 0, 1

count = 0

while count < limit:

    print(a, end=’ ‘)

    a, b = b, a + b

    count += 1 

Code snippet based problems

Q. In the provided code snippet:

x = 1

while x < 4:

    print(“hi”)

    x += 1

  1. Explain how the loop works and why it outputs “hi” three times.
  2. What would happen if you removed the line x += 1 from the code?

Ans.

  1. x is initialized to 1.
  2. The while loop checks if x is less than 4. Since it’s True, the loop starts.
  3. Inside the loop:
    1. “hi” is printed to the console.
    2. x is incremented by 1 (x += 1), so x becomes 2.
  4. The loop checks the condition again. Since x (now 2) is still less than 4, the loop continues.
  5. Steps 3 and 4 repeat until x becomes 4. At this point, the condition x < 4 is False, and the loop terminates.
  6. The output is “hi” printed three times because the loop iterates three times before the condition becomes False.

 If you remove the line x += 1, the value of x would remain 1 throughout the loop. The condition x < 4 would always be True, causing the loop to run indefinitely (an infinite loop).

Q. What is the issue with this code, and how would you fix it?

x = 5

while x > 0:

    print(“Hello”)

Ans. This code results in an infinite loop because the value of x never changes within the loop. To fix it, you need to decrement x in each iteration:

x = 5

while x > 0:

    print(“Hello”)

    x -= 1  # Decrement x

Q. What is the output of this code, and how can it be corrected to print the correct count?

count = 1

while count < 5:

    print(“Counting:”, count + 1)

    count += 1

Ans. The output will be:

Counting: 2 

Counting: 3 

Counting: 4 

Counting: 5

The code is printing count + 1 instead of count. To correct it:

count = 1

while count < 5:

    print(“Counting:”, count)  # Print count directly

    count += 1