Table of contents
Python while loopPython for loop
Python if statement
Python if...elif...else
Python control statements
A while loop repeatedly executes a block of program inside it as long as a given condition is true. Imagine you're repeatedly checking if a jar still has cookies. As long as there are cookies inside, you take one and enjoy it.
This simple loop continues until the cookie jar is empty. In each cycle, it checks the condition (cookies > 0), similar to asking, "Is there still a cookie in the jar?" If yes, you take one and eat it (decreasing the number of cookies left in the jar).
A for
loop lets you iterate over a sequence (like a list or range) without manually tracking a condition.
Imagine you have a box of candies and want to give each one to a friend. Each candy is handled exactly once:
An if
statement checks whether a condition is true. If it is, the code inside the if
block runs.
Think of it like deciding whether you need an umbrella:
When you have multiple conditions, you can chain them together with elif
(short for "else if") and end with else
as a catch-all.
Think of it like choosing an activity depending on the time of day:
There are three control statements in Python: break, continue, and pass.
A break
stops a loop immediately, while continue
skips the rest of the current loop iteration and moves on to the next.
A pass
does nothing (a placeholder) and is useful when a statement is required syntactically but you don’t want to run any code.
Suppose you are searching through a box of fruits:
break
.continue
pass
is suitable for this case. Author
Dr. Roger Ianjamasimanana