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
47 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.
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.
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.
Follow the course from the basics and check your work in the browser console.
Explore Learn Python