Store values in variables, convert between numbers and text, and format output with f-strings.
Why it matters
Almost every program takes in some values, transforms them and reports a result: a price and a quantity become a total, a list of readings becomes an average, a name becomes a personalised message. Variables hold those values, and knowing the difference between numbers and text saves you from the most common beginner bugs.
Variables are names for values
course = "Python Fundamentals"
lessons = 15
hours = 12.5
Each line stores a value under a name. You can change what a name points to later, and the old value is simply replaced:
lessons = 15
lessons = lessons + 1 # take the current value, add 1, store it back
print(lessons) # 16
That pattern is so common that Python has a shortcut: lessons += 1.
Naming rules: names can contain letters, digits and underscores, cannot start with a digit, and are case-sensitive (Total and total are different). The Python convention is snake_case: lowercase words joined by underscores, such as max_temperature. Pick names that say what the value means; price_per_item is far easier to read later than p or x2.
The basic types
Every value has a type. You can ask Python with type(...):
print(type(15)) # <class 'int'> whole number
print(type(12.5)) # <class 'float'> decimal number
print(type("15")) # <class 'str'> text (a string)
print(type(True)) # <class 'bool'> True or False
The type decides what operations make sense. 15 + 1 is 16, but "15" + "1" is "151", because + joins strings together. And "15" + 1 is an error: Python refuses to guess whether you meant maths or joining.
Converting between types
Text that arrives from a file, a web form or a sensor is a string, even when it looks like a number. Convert it before doing maths:
quantity_text = "4"
quantity = int(quantity_text) # 4 (an int)
price = float("3.50") # 3.5 (a float)
label = str(quantity) # "4" (back to text)
int("3.5") fails, because "3.5" is not a whole number. Use float for decimals, then round or int if you need a whole number.
A note on decimals: computers store floats in binary, so some values are tiny approximations. 0.1 + 0.2 prints 0.30000000000000004. This is normal in every language. Round when you display results, and compare floats with a small tolerance rather than ==.
Working with strings
Strings come with many built-in methods, which you call with a dot:
name = " ada lovelace "
print(name.strip()) # "ada lovelace" (remove surrounding spaces)
print(name.strip().title()) # "Ada Lovelace"
print(name.upper()) # " ADA LOVELACE "
print(len("Python")) # 6 (number of characters)
print("ace" in "Lovelace") # True
print("a,b,c".split(",")) # ['a', 'b', 'c']
print("data.csv".replace(".csv", ".txt")) # "data.txt"
Methods return a new string; the original is unchanged. name.upper() on its own does nothing useful unless you store or print the result.
You can pick out characters by position, counting from 0:
word = "Python"
print(word[0]) # "P"
print(word[-1]) # "n" (negative numbers count from the end)
Formatting output with f-strings
To build a message from values, put an f before the opening quote and write expressions inside {}:
item = "notebook"
price = 3.5
quantity = 4
total = price * quantity
print(f"{quantity} x {item} = ${total:.2f}")
# 4 x notebook = $14.00
The part after the colon is a format spec. A few useful ones:
value = 1234.5678
print(f"{value:.2f}") # 1234.57 two decimal places
print(f"{value:,.1f}") # 1,234.6 thousands separator
print(f"{0.256:.1%}") # 25.6% as a percentage
print(f"{7:03d}") # 007 pad with zeros to width 3
f-strings are the modern, readable way to format text. You will still see older styles such as "Total: " + str(total) or "{}".format(total) in existing code; they do the same job.
A worked example
A lab records a sample as text: "sample-07,23.456". Report it nicely:
record = "sample-07,23.456"
parts = record.split(",") # ['sample-07', '23.456']
sample_id = parts[0].upper() # 'SAMPLE-07'
mass_g = float(parts[1]) # 23.456
print(f"{sample_id}: {mass_g:.1f} g")
# SAMPLE-07: 23.5 g
Split, convert, format: you will use this pattern constantly.
Common mistakes
- Doing maths on text.
"4" * 2is"44". Convert withint()orfloat()first. - Forgetting the
f."{total}"prints the braces literally. It must bef"{total}". - Expecting methods to change the original. Strings are immutable; store the result:
name = name.strip(). - Using
=when you mean "equals".=stores;==compares (next lesson). - Comparing floats exactly. Prefer
abs(a - b) < 1e-9orround(a, 2) == b.
Quick recap
name = valuestores a value;snake_casenames that describe the value.- Main types:
int,float,str,bool.type()tells you which. - Convert with
int(),float(),str(); input text is always a string. - String methods (
strip,upper,split,replace) return new strings. - f-strings (
f"{value:.2f}") format numbers and text in one readable line.
Try it
In the Do tab you will turn a quantity stored as text into a number, calculate a total and format a receipt line.