prev
next
Or press ESC to close.
To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content. To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content.

Python Programming Part 08

Rajjit Oct 03rd, 2023 5 mins read
part-08

TOPIC: Python basic Loop structure / iterative statements - while loop

Basic iterative statements:
In Python, an "iterative statement" is a programming construct that allows you to execute a block of code repeatedly based on a specified condition or for a predetermined number of iterations. The primary iterative statements in Python are: while loop and the for loop
Now let us look at the while loop.

while loop
The while loop continues to execute a block of code as long as a specified condition is True. It's often used when the number of iterations is not known in advance. Some main uses of while loop includes:
→ Conditionally Repeated Execution: The while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is True. It is used when you want to repeat an action or a set of actions until a certain condition becomes False.
→ Dynamic Iteration: Unlike the for loop, which is typically used for a known number of iterations, the while loop is used when the number of iterations is not known in advance. It allows you to create loops that continue as long as a specific condition remains true, making it suitable for situations where the termination point depends on runtime conditions.
Now, let us look at the flowchart and the syntax of while loop:

while-loop-flow while-loop

The while loop is a powerful construct for creating dynamic, condition-based loops in Python, and it's essential for scenarios where you need to repeatedly perform tasks until a specific condition is met. However, you should be cautious when using while loops to ensure that the loop eventually terminates, or you may end up with an infinite loop.

Code as discussed in the video:

# basic loop structures or iterative statements

# while loop

'''
syntax: 
    statement x
    while (condition):
        statement block
    statement y  
'''

# Example 1:
# i = 0
# while(i<100):
#     print(i, end=" ")
#     i = i+1

# Example 2
i = 0
sumN = 0
user_input = int(input("Enter a number: "))
while i <= user_input:
    sumN = sumN + i
    i = i + 1
print(f'The sum of fist {user_input} is', sumN)

You can copy and run this code