If-Else Statements in Python

CondicionalesIf anidado

The if-else statement is one of the most important tools in programming. It lets your code make decisions: do one thing if a condition is true, and something different if it's false.

Think of it like real-life choices: if it's raining, take an umbrella; else, wear sunglasses. In code, this helps create programs that respond to different situations – like checking if a player won a game or if a password is correct.

We'll start with the basic if-else, then add elif for more options, look at practical examples, common mistakes, and give you plenty of practice.

Basic if-else Syntax

The structure is simple: if (condition): do this, else: do that. The colon : is required, and indentation defines the blocks.

If the condition is True, the if block runs. If False, the else block runs – exactly one of them will execute.

You can have as many lines as you want in each block – just keep the indentation consistent.

Real-World Examples

Let's look at some everyday situations to see how useful if-else is.

Example 1: Even or odd number

Example 2: Login check

Example 3: Simple game score

Using elif for Multiple Conditions

When you have more than two possibilities, use elif (else if). Python checks conditions from top to bottom and runs only the first true block.

This is cleaner than many nested if-else statements.

You can have as many elif blocks as needed. The final else is optional – it runs if nothing else matched.

Common Mistakes to Avoid

  • Forgetting the colon : after if/elif/else
  • Wrong indentation – blocks must be aligned
  • Using = (assignment) instead of == (comparison)
  • Forgetting parentheses in complex conditions
  • Putting code outside the block by mistake

Quick Quiz

Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.

✨ Pregunta a Lara — tu compañera de estudio con IA

Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.


Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.

Sigue Tu Progreso 🚀

Aprende más fácilmente siguiendo tu progreso completamente gratis.