Why Is My Python f-String Printing Curly Braces?
Your output contains {name} instead of the value of name. Diagnose the missing f prefix, then learn when doubled braces are actually needed.
COMMON PYTHON FIXES
Search a symptom, inspect broken code, and follow a full guide or a quick answer. Each guide explains the failure, its cause, the fix, and how to verify it.
Showing fixes from . Show all problems
65 results
No matches yet. Try another term or topic.
Your output contains {name} instead of the value of name. Diagnose the missing f prefix, then learn when doubled braces are actually needed.
A function tries to read a counter before its local assignment has given it a value. Trace the scope rule, then pass the current value in and return the update.
The item was added, yet the variable assigned from append() contains None. See exactly which object changed and choose the right pattern for your program.
A default list is created when the function is defined, so later calls can reuse it. Trace that shared object, then create a fresh list when the caller omits the argument.
The right-hand side produces more values than the assignment has targets. Count the fields, then choose the targets or a starred remainder that fits the data contract.
A list cannot be a set member or dictionary key because it is mutable and unhashable. Convert fixed coordinate values to tuples, then test duplicates and nested values.
Dividing by zero stops a calculation. Trace where the divisor came from, decide what zero means for your program, and test that rule instead of hiding the error.
The code runs, but the historical claim is false.
print("Python was named after a snake.")print("Python was named after Monty Python.")A program can run successfully and still print incorrect information. Check the fact as well as the syntax.
The code runs, but it confuses two milestones.
print("Python 3.0 was first shared in 1991.")print("Python was public in 1991; Python 3.0 arrived in 2008.")Python's first public sharing and the Python 3.0 release happened at different times.
NameError: Python looks for a variable named Hello.
print(Hello)print("Hello")Put literal text inside quotes so Python treats it as a string.
SyntaxError in Python 3.
print "Hello"print("Hello")print is a function, so its argument goes inside parentheses.
NameError because Name and name are different names.
name = "Maya"
print(Name)name = "Maya"
print(name)Use exactly the same spelling and capitalization each time.
TypeError when joining a string and an integer.
age = 12
print("Age: " + age)age = 12
print("Age: " + str(age))Convert the number to a string before concatenating it with text.
IndexError because the only valid positive indexes are 0 and 1.
items = ["a", "b"]
print(items[2])items = ["a", "b"]
print(items[1])The final positive index is len(items) - 1.
The variable becomes None.
items = [1, 2]
items = items.append(3)
print(items)items = [1, 2]
items.append(3)
print(items)Call append without assigning its return value.
It prints 1 because ^ is bitwise XOR.
print(2 ^ 3)print(2 ** 3)Python's exponentiation operator is **.
ZeroDivisionError.
print(10 / 0)print(10 / 2)The divisor must be nonzero.
The literal text Hi, {name} is displayed.
name = "Maya"
print("Hi, {name}")name = "Maya"
print(f"Hi, {name}")Add f before the opening quote to evaluate placeholders.
NameError because username has not been defined.
name = "Maya"
print(f"Hi, {username}")name = "Maya"
print(f"Hi, {name}")A placeholder must refer to a defined name or valid expression.
IndexError because valid positive indexes are 0, 1, and 2.
word = "cat"
print(word[3])word = "cat"
print(word[2])The last positive index is one less than the string length.
TypeError because strings cannot be changed in place.
word = "cat"
word[0] = "b"word = "cat"
word = "b" + word[1:]
print(word)Construct a new string and assign it to the variable.
SyntaxError on the if line.
score = 75
if score >= 60
print("Passed")score = 75
if score >= 60:
print("Passed")End the if header with a colon.
IndentationError after the if header.
score = 75
if score >= 60:
print("Passed")score = 75
if score >= 60:
print("Passed")Indent statements that belong to the branch.
The condition stays true, so the loop keeps printing 0.
count = 0
while count < 3:
print(count)count = 0
while count < 3:
print(count)
count += 1Update the value tested by the condition.
Only 1, 2, and 3 appear.
for n in range(1, 4):
print(n)
# Expecting 1, 2, 3, 4for n in range(1, 5):
print(n)range excludes its stop argument.
The function prints 8, but result is None.
def double(value):
print(value * 2)
result = double(4)
print(result)def double(value):
return value * 2
result = double(4)
print(result)Use return when callers need to store or reuse the calculated value.
TypeError because name was not supplied.
def greet(name):
print(f"Hi, {name}")
greet()def greet(name):
print(f"Hi, {name}")
greet("Maya")Provide one argument for each required parameter.
TypeError because Python passes the instance automatically.
class Book:
def summary():
return "A book"
book = Book()
print(book.summary())class Book:
def summary(self):
return "A book"
book = Book()
print(book.summary())Instance methods need self as their first parameter.
AttributeError because no title attribute was stored on the object.
class Book:
def __init__(self, title):
title = title
book = Book("Python Notes")
print(book.title)class Book:
def __init__(self, title):
self.title = title
book = Book("Python Notes")
print(book.title)Assign to self.title to save the value on the instance.
KeyError for score.
learner = {"name": "Maya"}
print(learner["score"])learner = {"name": "Maya"}
print(learner.get("score", 0))Use get with a fallback if the key may be absent.
KeyError because 0 is not a key.
learner = {"name": "Maya"}
print(learner[0])learner = {"name": "Maya"}
print(learner["name"])Dictionary lookup uses keys, not numeric positions.
NameError if math has not been imported in this run.
print(math.sqrt(9))import math
print(math.sqrt(9))Import the module before using its name.
AttributeError because math now refers to the integer 4.
import math
math = 4
print(math.sqrt(9))import math
number = 4
print(math.sqrt(9))Avoid reusing an imported module's name for another value.
TypeError because entered_age is text.
entered_age = "17"
print(entered_age + 1)entered_age = "17"
print(int(entered_age) + 1)Convert numeric text before arithmetic.
ValueError because the text is not a valid integer.
entered_age = "seventeen"
print(int(entered_age))entered_age = "17"
print(int(entered_age))int accepts text that represents a valid whole number.
A 20% tip on 40 becomes 800 instead of 8.
tip = bill * 20tip = bill * 20 / 100Convert a percent to a fraction before multiplying.
The whole tip is charged to every person.
each = bill / people + tipeach = (bill + tip) / peopleAdd the tip once to the whole bill, then split the total.
SyntaxError because = is assignment, not comparison.
if guess = secret:
print('Correct')if guess == secret:
print('Correct')Use == when asking whether two values are equal.
The player receives a misleading hint.
if guess < secret:
return 'Too high'if guess < secret:
return 'Too low'Compare the guessed number to the secret from the player's perspective.
'red blue' reports eight characters instead of two words.
word_count = len(text)word_count = len(text.split())Split the text first when you want a word count.
'Code' and 'code' become separate dictionary keys.
words = text.split()words = text.lower().split()Normalize case before counting for a case-insensitive report.
It prints False because a set has only two distinct values.
print(len(set([1, 1, 2])) == 3)print(len(set([1, 1, 2])) == 2)A set keeps one copy of each equal value.
AttributeError: a dictionary has no add method.
items = {}
items.add('python')items = set()
items.add('python')Construct an empty set with set().
ZeroDivisionError still stops the program.
try:
print(4 / 0)
except ValueError:
print('Bad number')try:
print(4 / 0)
except ZeroDivisionError:
print('Cannot divide by zero')The except type must match the error that may be raised.
Unrelated bugs are hidden behind a vague message.
try:
risky_code()
except:
print('Something failed')try:
number = float('bad')
except ValueError:
print('Invalid number')Catch an expected error by name so other failures remain visible.
FileNotFoundError if the virtual file has not been created in this run.
with open('new_note.txt', 'r', encoding='utf-8') as file:
print(file.read())with open('new_note.txt', 'w', encoding='utf-8') as file:
file.write('Ready')
with open('new_note.txt', 'r', encoding='utf-8') as file:
print(file.read())Create the file before trying to read it in a fresh exercise run.
The old file contents disappear.
with open('note.txt', 'w', encoding='utf-8') as file:
file.write('second')with open('note.txt', 'a', encoding='utf-8') as file:
file.write('second')Choose a only when the new text should be added at the end.
SyntaxError in the browser editor: this is a shell command.
python -m venv .venvimport sys
print(sys.version_info.major)Use the browser editor for Python statements and a local terminal for setup commands.
The claim may be false because the browser runtime is separate.
print('My laptop uses Python 3.13')import sys
print(sys.version_info.major, sys.version_info.minor)Inspect each interpreter in its own environment rather than assuming they match.
The result contains doubled odd values, such as [2, 6] for [1, 2, 3, 4].
[n * 2 for n in numbers if n % 2][n * 2 for n in numbers if n % 2 == 0]The remainder is 1 for odd numbers, which is truthy. Compare explicitly with zero for even values.
SyntaxError: expected else after the conditional expression.
[n * 2 if n % 2 == 0 for n in numbers][n * 2 for n in numbers if n % 2 == 0]A trailing if filters items. An if before for is a different expression form and needs an else branch.
AttributeError because topic is the integer index.
for topic, number in enumerate(['loops'], start=1):
print(topic.upper())for number, topic in enumerate(['loops'], start=1):
print(topic.upper())enumerate gives index first, item second. Name the unpacked values in that order.
The second score is lost and no exception explains the mismatch.
list(zip(['Ada'], [8, 5]))list(zip(['Ada'], [8, 5], strict=True))Use strict=True when both sequences must have matching lengths; consume the iterator to trigger the check.
The result is a set of words with no lengths.
lengths = {word for word in ['cat', 'go']}lengths = {word: len(word) for word in ['cat', 'go']}Include key: value before for when the result should be a dictionary.
AttributeError: 'dict' object has no attribute 'add'.
seen = {}
seen.add('Ada')seen = set()
seen.add('Ada')Python reserves empty braces for a dictionary. Use set() for an empty set.
The terminal shows a value, but a wrong value does not fail a repeatable test.
print(double(4))assert double(4) == 8State the expected value explicitly so a regression fails when the test runs.
An implementation that always returns value passes even though it fails outside the range.
assert clamp(5, 0, 10) == 5assert clamp(5, 0, 10) == 5
assert clamp(-1, 0, 10) == 0
assert clamp(11, 0, 10) == 10Choose inputs that exercise each branch, including boundaries and errors.
It prints an invalid February 30 instead of crossing into March.
start = '2024-02-28'
print(start[:-2] + str(int(start[-2:]) + 2))start = date.fromisoformat('2024-02-28')
print((start + timedelta(days=2)).isoformat())Calendar arithmetic handles the length of each month and leap years.
TypeError because a date cannot be added to a bare integer.
date.fromisoformat('2024-02-28') + 1date.fromisoformat('2024-02-28') + timedelta(days=1)Wrap the offset in a timedelta to state its unit and meaning.
The result is the text 12.503.00, not a money total.
total = "12.50" + "3.00"total = Decimal("12.50") + Decimal("3.00")Convert each string to Decimal before adding it. Build Decimal from the source text to keep decimal values exact.
A quoted category such as Food, snacks is split into too many pieces.
category, amount = line.split(",")for row in csv.DictReader(StringIO(csv_text)):
category = row["category"]The csv module understands quoted fields and uses the header names.
A second Food row hides the first Food expense.
totals[category] = amounttotals[category] = totals.get(category, Decimal("0")) + amountUse the previous total as the starting point when a category appears again.
Searching for ADA LOVELACE misses an existing contact.
book[name.strip().casefold()] = record
found = book.get(search_name)book[name.strip().casefold()] = record
found = book.get(search_name.strip().casefold())Apply the same rule to both the saved and searched name.
The program raises KeyError instead of reporting a missing contact.
record = book["missing person"]record = book.get("missing person")get returns None for an absent key, allowing the caller to show a friendly result.
Adding a second person with the same name overwrites the first.
book[person_name] = email # two people can share this name# For real data, use a separate stable contact ID as the key.Normalized names are convenient for this exercise but cannot serve as reliable unique identifiers in a real address book.
Follow the course from the basics and check your work in the browser console.
Explore Learn Python