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.

16 min 7 sections

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 =:

python
price = 12.5
quantity = 3
total = price * quantity
print(total)   # 37.5

Read = 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:

python
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:

python
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:

python
x = 49.99 * 3 * 1.2
python
unit_price = 49.99
quantity = 3
tax_rate = 1.2
order_total = unit_price * quantity * tax_rate

Both 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:

TypeNameExamplesUsed for
Integerint0, 42, -7, 1_000_000Counting, whole quantities
Floating-point numberfloat3.14, 0.1, -2.0Measurements, fractions
Stringstr"hello", 'Sam', ""Text
BooleanboolTrue, FalseYes/no facts
python
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):

python
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:

python
print(0.1 + 0.2)      # 0.30000000000000004
print(round(0.1 + 0.2, 2))   # 0.3

That'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:

python
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:

python
has_ticket = True
print(age >= 18 and has_ticket)   # True
print(not has_ticket)             # False

Booleans 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:

python
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:

python
name = "  sam "
name.strip()          # this result is thrown away
name = name.strip()   # this keeps it

Each character has a position (an index) starting from 0:

python
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:

python
age = 30
print("You are " + age)
text
TypeError: can only concatenate str (not "int") to str

Convert explicitly:

python
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 decimals

Remember 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 {}:

python
name = "Sam"
items = 3
total = 37.5

print(f"{name} bought {items} items for ${total}")
# Sam bought 3 items for $37.5

Add a format specifier after a colon to control how a value is shown:

python
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:

  1. 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.
  2. Calculate the tip, the total, and how much each person pays.
  3. Print a neat summary with all money shown to two decimal places, like the example below.
text
Bill amount: 84.60
Tip percentage: 15
Number of people: 3

Tip:        $12.69
Total:      $97.29
Per person: $32.43
Show solution
python
# 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, str and bool; type() tells you which you have.
  • Comparisons (==, !=, <, >=) produce booleans, combined with and, or and not.
  • Strings have methods that return new strings, support indexing from 0, and never change in place.
  • Convert explicitly with int(), float() and str(), and format output with f-strings such as f"{total:.2f}".

Check yourself

Quiz

0/4 correct · 4 left

  1. 1.What does this print? count = 5; count = count * 2; print(count)

  2. 2.What is the result of "7" + "3"?

  3. 3.name = " Ana "; name.strip(); print(len(name)). What is printed?

  4. 4.Which f-string shows 3.14159 as 3.14?

Finished reading?

Mark it complete to fill in your roadmap.