Conditional Statements

if Statement

  • Used to modify the flow of code execution based on a condition
  • Different code blocks can be executed based on whether the condition is true or false
  • Indentation (4 spaces / 1 tab) defines the scope of code block
  • Syntax / Examples:
    1. if condition:{expression} else:{expression}
    2. age = 18 if age >= 18:print("You are an adult.") else:print("You are a minor.")

if else ladder

  • Used to check multiple conditions sequentially
  • If condition is met, it's corresponding block is executed skipping further checks.
  • If condition isn't met, next condition is checked sequentially until a true condition is found or else block is reached
  • Syntax:
    1. if condition1:{expression} elif condition2:{expression} .. .. else:{expression}

if-else examples

  • marks = 85 if marks >= 90:print("Grade: A") elif marks >= 80:print("Grade: B") else:print("Grade: F")
  • file_name = "report.pdf" if file_name.endswith(".pdf"):print("This is a PDF file.") elif file_name.endswith(".docx"):print("This is a Word document.") else:print("Unknown file type.")