Python:Python If...Else Conditional Statements with Examples
Python•Conditionals

Python If...Else Conditional Statements with Examples

Conditional statements evaluate truth expressions and branch execution. Python uses strict indentation rather than braces to define nested blocks.

Syntax

if condition1: # block 1 elif condition2: # block 2 else: # fallback block

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
conditionBoolean ExpressionExpression evaluated as True or False.
elif (optional)Chained BranchSecondary check tested if previous condition fails.
else (optional)Fallback BranchExecuted if all prior conditions evaluate to False.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Python If...Elif...Else Grading System
score = 88

if score >= 90:
    grade = "A (Exceptional)"
elif score >= 80:
    grade = "B (Good standing)"
elif score >= 70:
    grade = "C (Satisfactory)"
else:
    grade = "F (Needs improvement)"

# Ternary conditional expression
status = "Passed" if score >= 70 else "Failed"

print(f"Final Score: {score}")
print(f"Awarded Grade: {grade}")
print(f"Course Status: {status}")
Expected Output:
Final Score: 88
Awarded Grade: B (Good standing)
Course Status: Passed

How It Works: Step-by-Step

  • Lines 4-12: Evaluates score hierarchically from top to bottom.
  • Line 15: Uses Python ternary conditional: value_if_true if condition else value_if_false.

Key Concepts

  • elif branches are skipped as soon as any preceding condition succeeds.
  • The final else executes only if all checks evaluate to False.
  • Ternary expressions provide a concise 1-line syntax for variable assignment.

Common Mistake: Forgetting the colon : at the end of if/elif/else statements

Python requires a colon after every compound statement header.

❌ Incorrect
if score >= 80
    print("Good job") # SyntaxError: expected ':'
✅ Correct
if score >= 80:
    print("Good job")

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler