Python for AIPython for AI
Python Basics

f-strings

Put variables inside text the easy way

You will build a lot of text in AI programs: prompts, messages, and answers. f-strings are the cleanest way to mix your variables into that text.

What is an f-string?

An f-string is a normal string with the letter f in front of the opening quote. Inside it, anything you put between curly braces { } is replaced by its value.

python
name = "Priya"
age = 28

message = f"My name is {name} and I am {age} years old."
print(message)
# My name is Priya and I am 28 years old.
The f stands for "formatted". Forgetting it is the most common mistake: without it, Python prints the braces literally.

Why not just use +?

You can join strings with +, but you have to convert numbers with str() and keep track of every space. f-strings do the conversion for you.

FeatureUsing +Using f-string
Code"Age: " + str(age)f"Age: {age}"
Needs str() for numbersYesNo
Easy to readNoYes
Same result, but the f-string is shorter and easier to read.

Expressions inside braces

You are not limited to variable names. Any Python expression works inside the braces.

python
price = 20
quantity = 3

print(f"Total: {price * quantity}")
print(f"Shouting: {'hello'.upper()}")

Formatting numbers

Add a colon after the value to control how it is shown. This is handy for prices, scores, and percentages.

python
score = 0.87654
cost = 1234.5

print(f"Score: {score:.2f}")      # 2 decimal places -> 0.88
print(f"Accuracy: {score:.1%}")   # as a percent -> 87.7%
print(f"Cost: {cost:,.2f}")       # thousands separator -> 1,234.50

f-strings in AI programs

This is where f-strings really shine. When you talk to a language model, you usually build the prompt from pieces of data.

python
topic = "black holes"
level = "a 10-year-old"

prompt = f"Explain {topic} to {level} in three short sentences."
print(prompt)

For long prompts, use triple quotes. f-strings work there too.

python
user_name = "Sam"
question = "What is a list?"

prompt = f"""You are a friendly Python tutor.
The student's name is {user_name}.
Answer this question: {question}"""
print(prompt)

Common mistakes

  • Forgetting the f: "Hi {name}" prints the braces as text.
  • Using the same quote type inside the braces as outside. Use ' inside if the f-string uses ".
  • Writing a literal brace: use double braces {{ }} if you want a real { in the output.

What's next?

Next you'll learn how to grab individual characters and pieces of a string with indexing and slicing.