f strings if.elif

Using f-strings with Conditional Statements in Python

The introduction of f-strings in Python 3.6 has made string formatting more readable and concise. In this article, we'll explore how to combine f-strings with conditional statements to create dynamic strings based on variable values. Let's dive in!

Using f-strings with Conditional Statements in Python

Basic Understanding

F-strings, also known as formatted string literals, allow for embedding expressions inside string literals, using {}. When combined with conditional statements, they offer a compact way to embed logic directly within a string.


  1. Basic if/else with a Single Variable:
    x = 1
    message = f"The number is {'greater than zero' if x > 0 else 'not greater than zero'}."
  2. Using if/elif/else with a Single Variable:
    y = 0
    message = (
        f"The number is positive." if y > 0 else 
        f"The number is negative." if y < 0 else 
        f"The number is zero."
  3. Using Nested Conditional Expressions:
    age = 35
    is_student = True
    message = (
        f"Discount applied: Senior citizen." if age > 65 else 
        f"Discount applied: Student." if is_student else 
        f"No discount applied."
  4. Multiple Variables in Conditions:
    weight = 75
    height = 1.7
    bmi = weight / (height ** 2)
    category = (
        f"You are underweight." if bmi < 18.5 else 
        f"You are normal weight." if 18.5 <= bmi < 24.9 else 
        f"You are overweight." if 24.9 <= bmi < 30 else 
        f"You are obese."
    print(f"Your BMI is {bmi:.2f}. {category}")
  5. Complex Logic with List Comprehension:
    grades = [85, 92, 78, 63, 88, 90]
    messages = [
        f"Student {index + 1}: "
        f"{'Excellent' if grade > 90 else 'Good' if grade > 80 else 'Average' if grade > 70 else 'Poor'}"
        for index, grade in enumerate(grades)
    for message in messages:

Additional Practice

For those eager to further hone their skills, here are five additional practice examples:

  1. Format a string to display whether a number is even or odd.
  2. Use a variable representing a day of the week to display whether it's a weekday or a weekend.
  3. Based on a student's age, determine and display which grade they're in (e.g., Kindergarten, 1st grade, etc.).
  4. Given a temperature in Celsius, classify it as cold (< 10°C), moderate (10-25°C), or hot (> 25°C).
  5. For a given month (e.g., "January"), display which season it falls under.

Documenting my journey as I enhance my Python skills. Stay tuned for more insights and tips! Google Colab Example


Popular posts from this blog

Drawing Tables with ReportLab: A Comprehensive Example

Blog Topics

DataFrame groupby agg style bar