Phython Loop
Phython Loop
Output:
The sum of numbers from 1 to 10 is: 55
# Initialize a variable to store the sum
total_sum = 0
Add numbers:
During each iteration of the loop, the current value of number is added to total_sum. This step accumulates the sum of the numbers.
# Initialize variables
total_sum = 0
number = 1 Output:
1. Initialize Variables:
total_sum is initialized to 0 to store the cumulative sum of the numbers.
number is initialized to 1, which will be the starting point of our loop
The loop will continue as long as number is less than or equal to 10 (number <= 10). The moment this
condition is no longer true (when number becomes 11), the loop will stop.
3. Add Numbers:
Inside the loop:
We add the current value of number to total_sum.
Then, we increment the value of number by 1 (number += 1) to move to the next number in the sequence.
4. End of Loop:
When number becomes 11, the condition number <= 10 fails, so the loop exits, and the final sum is printed.
The while loop is useful when the number of iterations is not known in advance. It
will keep executing as long as the specfied condition is true.
In this case, the loop continues until the value of number exceeds 10.