Step 03 of 10
Values, variables & types
Store values in variables, work with numbers, text and booleans, convert between types, and format output with f-strings.
Every program works with data: a price, a name, whether a user is logged in. In this lesson you'll learn how programs remember data in variables, the basic types of data Python has, how to convert between them, and how to turn values into nicely formatted text. These are the atoms every later lesson builds on.
Variables: names for values
A variable is a name that refers to a value. You create one with =:
price = 12.5
quantity = 3
total = price * quantity
print(total) # 37.5Read = as "now refers to", not "equals". total = price * quantity means: work out the right-hand side, then make the name total refer to the result.
Because of that, a variable can be reassigned, and the right-hand side can even use the variable's old value:
score = 10
score = score + 5 # take the old score, add 5, store it back
print(score) # 15
score += 5 # shorthand for the same thing
print(score) # 20+=, -=, *= and /= all work the same way.
Code runs top to bottom. A variable must be assigned before it's used:
print(greeting) # NameError: name 'greeting' is not defined
greeting = "hi"Naming variables
Names can contain letters, digits and underscores, can't start with a digit, and are case-sensitive (Total and total are different). Python style uses snake_case: lowercase words joined by underscores.
The rule that matters most: name things for what they mean. Compare:
x = 49.99 * 3 * 1.2unit_price = 49.99
quantity = 3
tax_rate = 1.2
order_total = unit_price * quantity * tax_rateBoth calculate the same number. Only the second tells the reader what's going on.
The basic types
Every value has a type, which decides what you can do with it. type() tells you:
| Type | Name | Examples | Used for |
|---|---|---|---|
| Integer | int | 0, 42, -7, 1_000_000 | Counting, whole quantities |
| Floating-point number | float | 3.14, 0.1, -2.0 | Measurements, fractions |
| String | str | "hello", 'Sam', "" | Text |
| Boolean | bool | True, False | Yes/no facts |
print(type(42)) # <class 'int'>
print(type(4.2)) # <class 'float'>
print(type("42")) # <class 'str'>
print(type(True)) # <class 'bool'>42 and "42" look similar but are completely different things: one is a number you can do maths with, the other is two characters of text.
Numbers
Arithmetic works as in maths, with the usual order of operations (use parentheses to be explicit):
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
print(7 / 2) # 3.5 (/ always gives a float)
print(7 // 2) # 3 (whole-number division)
print(7 % 2) # 1 (remainder: useful for "is it even?")Floats are stored in binary, so some decimal values can't be represented exactly:
print(0.1 + 0.2) # 0.30000000000000004
print(round(0.1 + 0.2, 2)) # 0.3That's normal in every programming language. Round when you display, and for money, either count in whole cents (1999 instead of 19.99) or use Python's decimal module.
Booleans and comparisons
Comparisons produce booleans:
age = 20
print(age >= 18) # True
print(age == 30) # False (== compares; = assigns)
print(age != 30) # True (not equal)Combine them with and, or and not:
has_ticket = True
print(age >= 18 and has_ticket) # True
print(not has_ticket) # FalseBooleans become essential in the next lesson, where they decide which code runs.
Working with text
Strings can use single or double quotes; pick one style and stick to it. Some things you can do with them:
first = "Ada"
last = "Lovelace"
full = first + " " + last # joining (concatenation)
print(full) # Ada Lovelace
print(len(full)) # 12 (number of characters, including the space)
print(full.upper()) # ADA LOVELACE
print(full.lower()) # ada lovelace
print(" padded ".strip()) # padded (removes spaces at both ends)
print(full.replace("Ada", "Augusta")) # Augusta Lovelace
print("love" in full.lower()) # True.upper() and friends are methods: functions that belong to a value, called with a dot. Strings never change in place; methods return a new string, so you must store the result if you want to keep it:
name = " sam "
name.strip() # this result is thrown away
name = name.strip() # this keeps itEach character has a position (an index) starting from 0:
word = "Python"
print(word[0]) # P
print(word[-1]) # n (negative counts from the end)
print(word[0:3]) # Pyt (from index 0 up to, but not including, 3)Converting between types
Mixing types often fails, because Python refuses to guess what you meant:
age = 30
print("You are " + age)TypeError: can only concatenate str (not "int") to strConvert explicitly:
print("You are " + str(age)) # str() turns a value into text
print(int("42") + 1) # 43: int() turns text into a whole number
print(float("2.5") * 2) # 5.0
print(int(3.99)) # 3: int() on a float cuts off the decimalsRemember from the last lesson: input() always returns a string, so user input that should be a number needs int() or float().
f-strings: building text from values
Joining strings with + and str() gets messy quickly. f-strings are the modern, readable way. Put f before the opening quote, and put any expression inside {}:
name = "Sam"
items = 3
total = 37.5
print(f"{name} bought {items} items for ${total}")
# Sam bought 3 items for $37.5Add a format specifier after a colon to control how a value is shown:
price = 1234.5
print(f"{price:.2f}") # 1234.50 two decimal places
print(f"{price:,.2f}") # 1,234.50 with thousands separators
print(f"{0.256:.1%}") # 25.6% as a percentage
print(f"{'left':<10}|") # left | padded to 10 characters
print(f"{7:03}") # 007 padded with zeros.2f is the one you'll use constantly: always show prices with exactly two decimals.
Practice
Write tip.py, a tip calculator:
- Ask for the bill amount (it may have decimals), the tip percentage (a whole number such as 15), and the number of people splitting the bill.
- Calculate the tip, the total, and how much each person pays.
- Print a neat summary with all money shown to two decimal places, like the example below.
Bill amount: 84.60
Tip percentage: 15
Number of people: 3
Tip: $12.69
Total: $97.29
Per person: $32.43Show solution
# tip.py
bill = float(input("Bill amount: "))
tip_percent = int(input("Tip percentage: "))
people = int(input("Number of people: "))
tip = bill * tip_percent / 100
total = bill + tip
per_person = total / people
print()
print(f"Tip: ${tip:.2f}")
print(f"Total: ${total:.2f}")
print(f"Per person: ${per_person:.2f}")The bill uses float because it can have cents; the percentage and the number of people use int because they're whole numbers. print() with no arguments prints an empty line. The per-person amount is 97.29 / 3 = 32.43, which :.2f rounds for display; the variable itself still holds the unrounded value, which is exactly what you want while calculating.
Key takeaways
- A variable is a name that refers to a value;
=assigns, and code runs top to bottom. - The basic types are
int,float,strandbool;type()tells you which you have. - Comparisons (
==,!=,<,>=) produce booleans, combined withand,orandnot. - Strings have methods that return new strings, support indexing from 0, and never change in place.
- Convert explicitly with
int(),float()andstr(), and format output with f-strings such asf"{total:.2f}".
Check yourself
Quiz
0/4 correct · 4 left
1.What does this print? count = 5; count = count * 2; print(count)
2.What is the result of "7" + "3"?
3.name = " Ana "; name.strip(); print(len(name)). What is printed?
4.Which f-string shows 3.14159 as 3.14?
Finished reading?
Mark it complete to fill in your roadmap.