Course
BASICModule 1: How Programs Think· 3/3

Conditions & Logic

A program makes decisions

Until now instructions ran one after another. A condition is the first construct that makes a program smart: "if X — do this, otherwise — that." A discount at 5000 and up, access with the right password, an alert when a balance drops — all of these are conditions.

PLAYGROUND

Anatomy: the word if, a condition (an expression that yields true or false), a block "what to do when true," and an optional else — "what to do otherwise." The language difference is how the block is marked: JavaScript wraps the body in curly braces {}, Python marks it with a four-space indent. In Python the indent is part of the language: a slipped indent changes the meaning of the program.

Comparisons and logic

Conditions are built from comparisons:

  • > greater, < less, >= / <= — with "or equal"
  • equality: === in JS (remember: triple!), == in Python
  • inequality: !== in JS, != in Python

Comparisons combine with logical connectors: AND (&& / and), OR (|| / or), NOT (! / not):

PLAYGROUND

The chain "if — else if — else" (else if / elif) is checked top to bottom, the first true branch fires, the rest are skipped. The order of branches is part of the logic.

The trap: assignment instead of comparison

= puts a value into a variable, ==/=== compares. Mix them up and you get a bug that's hard to spot by eye:

PLAYGROUND

Exercise

Write a promo-code check: if the code equals "QUBIT" — print "20% discount," if "FRIEND" — "10% discount," anything else — "Code not found." Test all three branches.

PLAYGROUND

Key takeaways

  • if / else if / else — branching; the first true branch runs.
  • Code block: {} in JavaScript, indent in Python (and there it's mandatory).
  • Logic: &&/and, ||/or, !/not; comparison is === (JS) and == (Python).
  • = assigns, == compares — a classic spot for bugs.
CHECK YOURSELF
1. What does an if / elif / else chain do if two branches are true at once?
2. How does a code block in Python differ from JavaScript?
3. The condition if (x = 5) in JavaScript — what is wrong?
Variables & TypesLoops