Decisions and loops
Programs become useful when they can choose (conditions) and repeat (loops). These two ideas, plus sequence, can express any algorithm.
Conditions: if / else
Notice the syntax differences:
- Python uses a colon
:and indentation to group code. Indentation isn't optional there! - JavaScript uses
( )around the condition and{ }braces around the block.
Comparison and logic
| Meaning | Python | JavaScript |
|---|---|---|
| equal | == |
=== |
| not equal | != |
!== |
| greater / less | > < >= <= |
same |
| and | and |
&& |
| or | or |
|| |
| not | not |
! |
Loops: repeat work
for: do something for each item
while: repeat until a condition changes
⚠️ Infinite loops: if the condition never becomes false, the loop runs forever. Make sure something inside the loop moves you toward the end. (The editors here stop runaway code after a few seconds.)
break and continue
Combining them: the accumulator pattern
Start with an empty result and build it up in a loop. You'll use this pattern constantly:
Classic exercise: FizzBuzz
Print the numbers 1 to 20, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both. It's a famous interview warm-up because it combines loops, conditions and the order of checks.
Hint: check "multiple of both" first. Why?
1.In Python, how is the body of an if block defined?
2.Which loop is best when you don't know in advance how many repetitions you need?