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
- if condition:{expression} else:{expression}
age = 18if age >= 18:print("You are an adult.")else:print("You are a minor.")
Syntax / Examples:
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
- if condition1:{expression} elif condition2:{expression} .. .. else:{expression}
Syntax:
if-else examples
marks = 85if 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.")
