Quick Overview
An f-string builds one new string in a single pass, evaluating each expression where it appears. Repeated `+` inside a loop allocates a fresh string on every iteration instead.
Create a function concat_name(first_name, last_name) that takes a first and last name and returns a single formatted string as "last_name, first_name".
Formatting display names cleanly is standard requirement across user profiles, invoice PDF generators, and email notifications.
Use Python f-strings (f"{last_name}, {first_name}"):
def concat_name(first_name, last_name):
return f"{last_name}, {first_name}"
# Testing our function
print(concat_name("First", "Last")) # Output: "Last, First"
print(concat_name("John", "Doe")) # Output: "Doe, John"
print(concat_name("Mary", "Jane")) # Output: "Jane, Mary"
Introduced in Python 3.6, f-strings (formatted string literals) are faster, cleaner, and less error-prone than legacy % formatting or " + " string concatenation.
"Last, First" order rather than "First Last".Use f-strings for all string formatting. Next, let's calculate factorials in Python!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.