Definition:
The for loop firstly checks the condition.
If the condition is true, the loop inside the curly braces executes.
After that, an increment or a decrement will occur.
Then again, the loop rechecks the condition.
If the condition is false, the loop exits from the curly braces.
Now you will clearly understand the code logic with the help of the flowchart.
For Loop Flowchart:
First step: → You will write the program
|
Second step: → Now you will set the initialization (start value)
|
Then you will check the condition (true/false)
If you find the condition "True", then
|
Execute Code
|
Do the increment/decrement
|
Go back and check the condition again
If the condition is "False", then
|
Stop the loop
|
End the program
Syntax:
for variable in range(start, stop):
# The code is written here
Example:
a = 2
b = 4
sum = 0
for i in range(1,2):
sum = a + b
print(sum)
Output:
Exercise
Write a Python program to print the sum of two numbers using a for loop.
