f strings if.elif
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.
Examples
- 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'}." print(message)
- 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." ) print(message)
- 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." ) print(message)
- 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}")
- 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: print(message)
Additional Practice
For those eager to further hone their skills, here are five additional practice examples:
- Format a string to display whether a number is even or odd.
- Use a variable representing a day of the week to display whether it's a weekday or a weekend.
- Based on a student's age, determine and display which grade they're in (e.g., Kindergarten, 1st grade, etc.).
- Given a temperature in Celsius, classify it as cold (< 10°C), moderate (10-25°C), or hot (> 25°C).
- For a given month (e.g., "January"), display which season it falls under.
Comments
Post a Comment