Concatenate First and Last Name into Full Name
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.
Deep Dive
1. The Challenge: Name Formatting
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".
2. Why It Matters
Formatting display names cleanly is standard requirement across user profiles, invoice PDF generators, and email notifications.
3. The Python Solution
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"
4. Why f-Strings are Best Practice
Introduced in Python 3.6, f-strings (formatted string literals) are faster, cleaner, and less error-prone than legacy % formatting or " + " string concatenation.
5. Common Mistakes
- Wrong Order: Pay close attention to prompt requirements! Here the challenge requires
"Last, First"order rather than"First Last".
6. Next Steps
Use f-strings for all string formatting. Next, let's calculate factorials in Python!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
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.
Convert Minutes into Seconds
`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.
Calculate the Area of a Triangle
`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.