Courseiva
PCEP-30-02Chapter 7 of 16Objective 3.2

Conditional Statements: if, elif, else

What problem does a conditional statement solve that a simple sequence of instructions cannot? Imagine you need a program that behaves differently depending on user input, time of day, or a value from a sensor. Without conditional statements, your code would run the same way every single time, like a washing machine with only one cycle. For the PCEP-30-02 exam, you must understand how to create these decision points using if, elif, and else, so your programs can respond intelligently to different situations.

12 min read
Beginner
Updated Jul 23, 2026
Editorial oversight: Johnson Ajibi· Security Systems Architect · MSc IT Security · IEEE Senior Member

A simple way to picture Conditional Statements: if, elif, else

The Railway Switchman Analogy

A railway switchman stands in a signal box beside a set of tracks. A train approaches from the main line. The switchman has a lever with three positions. Position one sends the train to the north platform. Position two sends it to the south platform. Position three sends it to the express bypass, skipping all local stations.

The switchman does not move the lever randomly. He checks a timetable, and then chooses exactly one position. If the train is the 7:14 commuter, he pulls the lever to the north platform. The north platform is the default, or the 'else' in the timetable. If the train is the 7:22 express, he pulls the lever to position two for the south platform. If the train is the 8:05 freight, he pulls to position three for the bypass. He never pulls two positions at once. The tracks stay fixed until the next train.

This maps precisely to if, elif, and else. The 'if' is the first check: is this the 7:14? If yes, take the north route. If not, the switchman moves to the next check: the 'elif'. Is this the 7:22? If yes, take the south route. If not, he checks the next elif. Is this the 8:05? Finally, if none of the specific checks match, the default action — the 'else' — grabs the train and sends it to the local platform. Just like a Python program, the switchman evaluates one condition at a time, in order, and only executes one path. Once a match is found, the rest of the timetable is ignored.

How It Actually Works

A conditional statement is a way to make your code choose between different paths based on a condition. Think of a condition as a question that can only be answered 'true' or 'false'. Is the temperature above 30 degrees? Is the user logged in? Is the score greater than 100? Python uses the 'if' keyword to check that first question.

The simplest structure is a single 'if' statement. You write the word 'if', then a condition, then a colon. On the next line, indented by four spaces, you write what should happen if the condition is true. For example:

if user_age >= 18: print('You can vote')

This code checks if user_age is greater than or equal to 18. If true, it prints the message. If false, Python skips the indented block entirely and moves to the next line after it. The indentation is critical — Python uses it to know which code belongs to the if block. Without correct indentation, your program will crash or behave unpredictably.

The 'else' keyword gives you a default path. If the condition in the 'if' is false, the 'else' block runs instead. You write 'else' after the if block, at the same indentation level as the original 'if', followed by a colon and then indented code. For example:

if user_age >= 18: print('You can vote') else: print('You are too young to vote')

Now your code always prints one of two messages. There is no middle ground.

The 'elif' keyword, short for 'else if', lets you add more than two paths. You can check multiple conditions in order. Python evaluates the first 'if' condition. If it is true, it runs that block and skips all remaining 'elif's and 'else'. If it is false, Python moves to the first 'elif' and checks its condition. If that is true, it runs that block and stops. This continues until either a condition is true or Python reaches the optional 'else'. If no conditions are true and there is no 'else', nothing happens. For example:

score = 85 if score >= 90: print('Grade A') elif score >= 80: print('Grade B') elif score >= 70: print('Grade C') else: print('Grade D')

This code assigns a grade. It checks the first condition (score >= 90). If false, it checks the next (score >= 80). Because score is 85, the second condition is true, so it prints 'Grade B'. It does not check the third condition or the else.

Why does this exist? Without elif, you would have to write nested if statements, which are harder to read. You could write:

if score >= 90: print('A') else: if score >= 80: print('B') else: if score >= 70: print('C') else: print('D')

This is called nested conditionals, and it quickly becomes messy. That is the 'pyramid of doom'. elif flattens the structure and makes it clear that all these conditions are peers being checked in sequence.

A very common trap is using 'if' multiple times instead of 'elif'. If you write:

if score >= 90: print('A') if score >= 80: print('B') if score >= 70: print('C')

For a score of 85, this would print 'B' and 'C' because the second and third conditions are both true. When you use separate 'if' statements, each one is evaluated independently. When you use 'elif', only one block runs.

You can also have a standalone 'if' without 'elif' or 'else'. And sometimes you have an 'if' and multiple 'elif's with no 'else'. That means if no condition is true, the program does nothing. Both are valid.

The condition itself can be any expression that evaluates to a boolean value — True or False. You can use comparison operators (== equal to, != not equal to, < less than, > greater than, <= less than or equal to, >= greater than or equal to). You can also use logical operators 'and', 'or', and 'not' to combine conditions. For example:

if age > 18 and has_license: print('You can drive')

Both conditions must be true for the if block to run. With 'or', at least one must be true. 'not' flips a true to false and vice versa.

In Python, some values are considered 'truthy' or 'falsy' in a conditional context. For example, 0, empty strings, empty lists, and None are all treated as False. Non-zero numbers, non-empty strings, and non-empty lists are treated as True. So you can write:

if name: print('Hello, ' + name)

This checks if name is not an empty string. This is a common Python idiom that you will see in real code.

A flow chart showing how Python evaluates an if/elif/else chain: each condition is checked in order, and only the first true branch executes.

Walk-Through

1

Write the if keyword and condition

Start with the word 'if'. Then write a condition, which is any expression that can be evaluated as True or False. Use comparison operators (==, !=, <, >, <=, >=) or logical operators (and, or, not). End the line with a colon. The colon tells Python that the next indented lines belong to this if block.

2

Indent one level and write the if block

Press Tab or four spaces, then write the code that should execute if the condition is true. This is the body of the if statement. You can have one or more lines here. All lines must have the same level of indentation. Python will run these lines only if the condition is True.

3

Optionally add an elif branch

After the if block, at the same indentation level as the original if, write 'elif', a new condition, and a colon. Indent one level and write the code for this branch. Python checks this condition only if the previous if condition was False. You can have as many elif branches as needed, each with its own condition.

4

Optionally add an else branch

After the last elif block (or directly after the if block if no elif), at the same indentation level as the if, write 'else' followed by a colon. Indent one level and write the code for the else block. This block runs only if none of the preceding conditions were True. You can only have one else in a chain.

5

Continue execution after the entire conditional structure

After the last indented block in the if/elif/else chain, return to the original indentation level (no indent). Any code written at this level runs after the conditional statement has finished, regardless of which branch was taken. Python does not skip this code; it always executes it.

What This Looks Like on the Job

An IT professional working in a small software company is building a user registration system. The person has to validate each input a user types into a web form. For instance, the user enters an email address, a password, and an age. The code must decide whether to accept the registration or show an error message. The developer writes a series of conditional statements.

First, the code checks if the email field is empty. If it is empty (length equals zero), the code runs an if block that sets an error message: 'Email is required'. If the email is not empty, the code moves to an elif that checks if the email contains an '@' symbol. If it does not, the elif block adds a message: 'Email must contain @'. If both the first and second conditions are false, the email is considered valid so far, and the code moves on.

Then the developer writes a separate if statement to check the password. This is a new decision, not chained to the email check. The code checks if the password length is less than 8 characters. If true, it adds an error. Then an and condition checks if the password contains at least one number. If not, another error. These are independent if statements because each check produces its own error and one field can have multiple errors.

Next, the code checks the age field. It uses a chain of elif. If age is less than 13, it blocks registration entirely. Elif age is less than 18, it prints a message saying a parent must approve. Else (age 18 or over), it allows normal registration. The order matters here: you must check the most restrictive condition first (under 13) before checking the less restrictive one (under 18). If you reversed the order, everyone under 18 would get the 'parent approval' message and the under-13 check would never run.

Finally, the developer writes a validation function that returns True or False. The function uses a series of if/elif/else statements to check the overall result. If any critical condition fails, the function returns False and the registration does not proceed. This pattern appears everywhere in IT: validating forms, authorising users, routing traffic, parsing files, and controlling hardware. The if/elif/else structure is the fundamental way that software makes decisions.

The developer also debugs issues by reading the conditions out loud. If a bug occurs where a user under 13 gets accepted, the developer traces through each condition in order. This systematic checking is exactly how Python runs the code, and it is how professionals find and fix logic errors.

How PCEP-30-02 Actually Tests This

The PCEP-30-02 exam tests your understanding of conditional statements in several specific ways. First, you must know the exact syntax of if, elif, and else. This includes the colon at the end of the condition line, the correct indentation of the block (typically 4 spaces), and the order in which the keywords appear. The exam loves to present code with missing colons or inconsistent indentation and ask you to predict the output or identify the error.

Second, the exam tests the concept of short-circuit evaluation. Python stops evaluating a condition as soon as it knows the result. For example, in the condition if x > 0 and y < 10, if x is not greater than 0, Python never checks the y < 10 part. You may see a question where one part of the condition causes an undefined variable error, but because of short-circuiting, the error never occurs. The exam expects you to understand this.

Third, the exam tests truthy and falsy values. You must memorise which values are considered False: None, False, zero (0, 0.0, 0j), empty strings '', empty lists [], empty tuples (), empty dictionaries {}, and empty sets set(). Everything else is True. Questions will present code like if []: print('hello') and ask if anything prints. The answer is no, because an empty list is falsy.

Fourth, the exam tests nested conditionals and the 'dangling else' problem, though Python solves this with indentation. You must understand that an else always belongs to the nearest unmatched if at the same indentation level. Questions will show nested if blocks and ask which else matches which if.

Fifth, the exam tests the use of the 'elif' keyword specifically. You may see code that uses multiple if statements instead of elif and be asked to identify the output. The trap is that multiple if statements are independent, so multiple blocks can run. The exam expects you to know that elif is exclusive — only one block runs from an if/elif/else chain.

Sixth, the exam tests operator precedence within conditions. For example, the condition if a or b and c is evaluated as if a or (b and c) because 'and' has higher precedence than 'or'. You must use parentheses to make your intentions clear. The exam may present such a condition and ask whether it evaluates to True or False given specific values.

Seventh, the exam tests your ability to trace through a series of conditions manually. Expect questions that give you a code snippet with multiple elif statements and ask what value prints for a given input. You must evaluate each condition in order and stop at the first true condition.

Eighth, the exam tests the 'pass' statement. The pass statement does nothing. It is used as a placeholder when you need a syntactically required block but have no code to put there. For example, if condition: pass. You may see a question about what happens when a block contains only pass.

Common traps include:

Using assignment operator '=' instead of comparison operator '=='. The code if x = 5 will cause a syntax error in Python 3 (or will not work as expected).

Forgetting the colon at the end of the condition line.

Mixing tabs and spaces for indentation.

Incorrectly assuming that elif is short for 'elseif' without a space.

Assuming that an else block is required; it is optional.

Assuming that you can have more than one else in an if/elif chain; you cannot.

Key Takeaways

The if keyword starts a conditional block, and every condition must end with a colon before the indented block of code.

Python evaluates conditions from top to bottom and executes only the first block whose condition is true, then skips the rest of the chain.

An elif branch is only checked if all preceding if and elif conditions are false; it is never checked if any earlier condition was true.

The else branch is optional and runs only if none of the preceding if or elif conditions are true and no error occurred.

Values like 0, empty strings, empty lists, None, and False are treated as False in a condition; all other values are treated as True.

Using multiple separate if statements instead of elif means each condition is evaluated independently and multiple blocks can run.

Indentation (usually four spaces) is the only way Python knows which lines belong to the if, elif, or else block.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Multiple if statements

Each if condition is evaluated independently of the others.

Multiple blocks can execute if more than one condition is true.

There is no default else unless you add one to each if.

if/elif/else chain

Conditions are evaluated in order, and the chain stops at the first true condition.

Only one block ever executes from the entire chain.

A single else at the end covers the case when none are true.

if/else (two branches)

Exactly two possible paths: the if path and the else path.

No intermediate checks. The condition is either true or false.

Suitable for yes/no decisions with a default.

if/elif/else (three+ branches)

Multiple possible paths, one for each elif plus the else.

Each elif adds a new condition to check before the default.

Suitable for grading systems, multi-category classification.

Indentation in Python

Indentation defines which code belongs to the if/elif/else block.

All lines in a block must have the exact same indentation level.

Incorrect indentation causes an IndentationError.

Curly braces in other languages (e.g., C, Java)

Curly braces {} define the block; indentation is optional for correctness.

Lines inside the braces can be at any indentation, even start of line.

Missing brace causes a syntax error, but misaligned indentation is allowed.

if with single condition

Only one boolean expression is evaluated.

No operator precedence concerns (no and/or to manage).

Simple to read and debug.

if with and/or combined condition

Multiple boolean expressions combined with and, or, not.

Operator precedence matters: and binds tighter than or.

Allows complex checks in a single line, but can be harder to read.

Watch Out for These

Mistake

You can use multiple elif blocks as a fallback: if this fails, try the next one, and the next one, etc.

Correct

elif is not a fallback or retry mechanism. Python checks each condition once in order. If the if condition is false, Python moves to the first elif. If that is false, it moves to the next, and so on. But each condition is evaluated exactly once. If you want to retry an action until it succeeds, you need a loop, not elif.

The word 'else' implies a default fallback, and 'elif' sounds like 'else if' which suggests another attempt. New learners often confuse the concept of checking multiple alternatives (which is what elif does) with the concept of repeatedly trying something (which requires a loop).

Mistake

The else block runs if none of the if or elif conditions are true, but it also runs if a condition raises an error.

Correct

If any condition in the if or elif causes an error (for example, referring to a variable that does not exist), Python stops executing the program and raises an exception. The else block never runs. The else block only runs when every condition evaluates to False without error.

Beginners assume that 'else' is a catch-all for 'everything else that could happen', including errors. In reality, an error stops the program completely before any else block can execute.

Mistake

I must always include an else block at the end of my if/elif chain, otherwise the code will not work.

Correct

The else block is completely optional. If you have an if statement with no else, and the condition is false, Python simply skips the if block and continues with the next line after it. Many legitimate patterns intentionally omit the else because you only want to do something under one specific condition.

Teachers and tutorials often use the full if/elif/else structure in examples, which makes beginners think it is mandatory. The word 'else' is also the most intuitive part ('do this, otherwise do that').

Mistake

I can replace every if with elif and the code will still work the same way.

Correct

An elif only works if it follows an if or another elif. You cannot start an else-if chain with elif. The first decision must always be an if. If you write elif as the first conditional statement in your code, Python will throw a SyntaxError.

The prefix 'else' in 'elif' suggests it is a standalone check, but it is not. Beginners who see elif used many times in examples forget that the first one must be if.

Mistake

Indentation does not matter as long as the lines are aligned in a way I can read.

Correct

Indentation is syntactically significant in Python. It defines which block of code belongs to the if, elif, or else. Incorrect indentation causes an IndentationError or changes the logic of the program. Even a single space difference can break the code or make it behave unpredictably.

In many other languages, indentation is only for readability. Curly braces {} define blocks. Python uses indentation instead of braces, so beginners coming from other contexts or those who treat indentation as optional run into errors.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between if, elif, and else in Python?

if checks the first condition. elif adds extra conditions that are checked only if the previous conditions were false. else provides a default action if none of the conditions are true. Only one branch in the chain runs.

Can I have an else without an if?

No. An else must always be paired with an if (or an elif that is ultimately tied to an if). A standalone else will cause a syntax error.

Does Python check all elif conditions even if the first if is true?

No. As soon as Python finds a true condition (the if or any elif), it executes that block and skips all remaining elif and else conditions. This is called short-circuit evaluation for the chain.

What happens if I use multiple if statements instead of elif?

Each if statement is independent. If a value satisfies more than one condition, multiple blocks will execute. This is different from elif where only the first true condition runs.

Is the colon after if, elif, else mandatory?

Yes. The colon is required. It tells Python that an indented block follows. Forgetting the colon causes a SyntaxError.

Can I put an if statement inside another if statement?

Yes. This is called nested conditionals. You can put an if block inside another if block, and each inner if can have its own elif and else. Just make sure the indentation is correct for each level.

Terms Worth Knowing

Keep going

You've finished Conditional Statements: if, elif, else. Continue through the PCEP-30-02 study guide to build a complete picture of the exam.

Done with this chapter?