Back to Blog

Python Conditionals Explained - if, elif, else, and, or, not | Beginner Tutorial #6

Sandy LaneSandy Lane

Video: Python Conditionals Explained - if, elif, else, and, or, not | Beginner Tutorial #6 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Python Conditionals Explained - if, elif, else, and, or, not

Understanding conditionals is essential for controlling the flow of your Python programs. This tutorial covers how to use comparison operators to evaluate expressions, apply branching logic with if, elif, and else, and combine conditions using logical operators like and, or, and not. You'll also see how Boolean values can be used in expressions and formatted strings, culminating in a simple quiz game that tracks the user's score.

Code

# Comparison operators and logical operators example
score = 0

# Ask a question
answer = input("What is the capital of France? ").strip().lower()

# Check the answer using conditionals and logical operators
if answer == "paris":
  print("Correct!")
  score += 1
elif answer == "lyon" or answer == "marseille":
  print("Close, but not the capital.")
else:
  print("Incorrect.")

# Another question demonstrating 'not' operator
answer2 = input("Is Python a programming language? (yes/no) ").strip().lower()

if not (answer2 == "yes"):
  print("Actually, Python is a programming language.")
else:
  print("Correct!")

# Display final score using a Boolean expression in an f-string
print(f"Your final score is {score} out of 1. Well done!" if score == 1 else f"Your final score is {score}. Keep practicing!")

Key Points

  • Comparison operators like ==, <, and > evaluate conditions to True or False.
  • if, elif, and else statements control program flow based on conditions.
  • Logical operators and, or, and not combine or invert Boolean expressions.
  • Boolean values can be used directly in expressions and formatted strings for dynamic output.
  • Building simple interactive projects like quiz games helps reinforce conditional logic concepts.