Great question! F-strings are surprisingly powerful. They don't just handle variables; they can evaluate almost any valid Python expression inside the curly braces {}.
Here is how f-strings handle complex expressions:
1. Mathematical Calculations
You can perform arithmetic directly inside the string. Python evaluates the math first and then places the result into the string.
price = 19.99
quantity = 3
print(f"Total cost: ${price * quantity}")
# Output: Total cost: $59.97
2. Method Calls and Functions
You can call string methods or any function inside the braces.
name = "labby"
print(f"Shouting: {name.upper()}")
# Output: Shouting: LABBY
3. Conditional (Ternary) Logic
You can even put small "if-else" statements inside an f-string to change the output based on a condition.
age = 20
print(f"Status: {'Adult' if age >= 18 else 'Minor'}")
# Output: Status: Adult
4. Formatting Numbers
F-strings are excellent for controlling how numbers look (like rounding decimals or adding commas). This uses a colon : inside the braces.
pi = 3.14159265
print(f"Pi rounded to two decimal places: {pi:.2f}")
# Output: Pi rounded to two decimal places: 3.14
Important Rule:
While f-strings are powerful, the expression inside {} must be simple enough to read. If the expression gets too long or complex, it's usually better practice to calculate the value in a separate variable first (like you did with years_to_100 in your lab) and then put that variable in the f-string. This keeps your code clean!
Would you like to try adding a decimal rounding or a name formatting expression to your user_info.py file?