Robotics · lesson 23 of 30 · free

If / else with sensors — Robotics for kids

An if / else lets a robot choose using a sensor. In “if (distance < 20) { turn right } else { go forward }”, the robot checks the distance sensor: if the reading is less than 20 cm it turns away, otherwise it drives on. Exactly 20 is not less than 20, so the else part runs. A while loop keeps repeating while its condition is true: “while (distance > 20) { forward 10 cm }” drives closer and closer, then stops.

▶ Watch how it works

Got it? Practise ↓

Robot tip

True → if, false → else — “put the sensor reading into the condition; only one part runs”

  1. Put the reading into the condition: true → the if part, false → the else part.
  2. < means strictly less; an equal reading makes it false.
  3. else if: check the conditions from the top; the first true one wins. while: repeat until the condition is false.

Use it for: Obstacle-avoiding robots, robot vacuums, coding lessons on conditions and robotics competitions.

Worked example: 🤖 if (distance < 20) { turn right } else { go forward } The distance sensor reads 12 cm. What does the robot do? → turn right

  1. Is 12 less than 20? Yes — the condition is true.
  2. So the if part runs: turn right.

Check: A reading of 25 cm would make the robot go forward ✓

▶ Watch it animated

✏️ Practice

Work it out in your head or on paper, type the answer and press Check. Stuck? Press “Show me how”.

Right: 0 · Tried: 0

🏁 Lesson 23 test

20 questions. Check each answer, then go to the next one. Get 16 or more right to pass.

🏅 Sign in with Google to earn the 🚧 Obstacle Dodger badge when you pass — and a certificate when you finish all 10 lessons of Part 3 · Programming robots. You can still take the test without signing in.

🖨️ Robotics Worksheet: Robot If / Else

✨ Free AI tutor

Ask the AI tutor about this lesson

Why does it work? When should you use it? Ask in English, मराठी or हिंदी.

Sign in with Google to ask Free — 20 questions a day.

👩‍🏫 Robotics classes near you — online or at home

Prefer a real teacher? TalentJR teachers take live online classes anywhere in India and visit homes in selected cities. Tell us what you need and our team will call you with timings and fees.

Live online classesSmall groups or 1:1 with a teacher, from home, any city.
Teacher at homeA TalentJR teacher visits your home (selected cities).
At a centreClasses at a TalentJR partner centre near you, where available.
Badges, certificates & gifts A badge for every lesson you pass, a certificate for every part you finish, plus TalentJR Points for daily practice. Electronics & IoT Circuits, sensors and microcontroller boards.