Python, section 1 of 9, 3h

Variables, strings and numbers

By the end: You can read and write basic Python without looking up syntax.

  • Variables and the basic types
  • Strings: what you can do with them
  • f-strings for building text
  • Numbers, and the two kinds of division
  • None, and what counts as true or false

New to python? A programming language is the set of written instructions a computer will follow, and Python is the one this field settled on. It reads close to English: a line that filters a list of records looks roughly like a sentence describing that filter. Every model provider ships a Python library, and nearly every machine learning tool is written in it. Why it matters

This is the beginning: how to store a value under a name, and the four kinds of value everything else is built out of — text, whole numbers, decimals, and true or false. Most of what you do in Python is done to text, so a good part of this section is what you can do to a string and how to build one out of other values. It assumes you have never written a line of code.

Variables#

A variable is a name for a value. You do not declare a type. Python works it out from what you assign.

name = "Jack"
age = 29
price = 19.99
is_active = True

Those are the four basic types: str for text, int for whole numbers, float for decimals, bool for true or false. You can check any value's type with type().

type(name)        # <class 'str'>
type(age)         # <class 'int'>

Strings#

A string is text. Single or double quotes both work. Use triple quotes when you need several lines.

a = 'hello'
b = "hello"
c = """line one
line two"""

Here are the string operations you will use most often.

s = "Hello World"

len(s)              # 11
s.upper()           # 'HELLO WORLD'
s.lower()           # 'hello world'
s.replace("World", "Python")   # 'Hello Python'
s.split(" ")        # ['Hello', 'World']
s.strip()           # removes spaces at both ends
s.startswith("He")  # True
"World" in s        # True

You can pick out parts of a string by position. Counting starts at 0. This is called slicing.

s = "Python"

s[0]       # 'P'    first character
s[-1]      # 'n'    last character
s[0:3]     # 'Pyt'  characters 0, 1, 2
s[2:]      # 'thon' from position 2 to the end
s[:2]      # 'Py'   up to but not including position 2
s[::-1]    # 'nohtyP'  reversed
The end number is never included. s[0:3] gives you three characters, not four.

Strings cannot be changed

s[0] = 'J' raises an error. Every string method returns a new string instead of changing the old one. So s.upper() on its own does nothing useful. You have to assign it: s = s.upper().

Joining strings together#

You can add strings with +, but join is better when you have many pieces.

first = "Hello"
second = "World"

first + " " + second          # 'Hello World'

words = ["Hello", "World", "again"]
" ".join(words)               # 'Hello World again'
", ".join(words)              # 'Hello, World, again'

Why join is better: each + creates a brand new string and copies everything so far. With 10 pieces you will not notice. With 10,000 pieces in a loop, the program crawls. join builds the result in one pass.

# Slow with many lines
out = ""
for line in lines:
    out = out + line

# Fast
out = "".join(lines)

f-strings#

An f-string lets you put variables directly inside text. Put an f before the quote and wrap the variable in curly braces. This is the normal way to build text in modern Python.

name = "Jack"
tokens = 1250

f"Hello {name}"                 # 'Hello Jack'
f"Used {tokens} tokens"         # 'Used 1250 tokens'
f"Double: {tokens * 2}"         # 'Double: 2500'

You can control how numbers look by adding a colon and a format code.

cost = 0.0374125

f"{cost:.2f}"       # '0.04'     two decimal places
f"{cost:.4f}"       # '0.0374'   four decimal places
f"{1250:,}"         # '1,250'    thousands separator
f"{0.37:.0%}"       # '37%'      as a percentage

A debugging shortcut

Add an equals sign inside the braces and Python prints the name as well as the value. f"{tokens=}" gives 'tokens=1250'. It saves typing the label yourself every time you debug.

Numbers#

Two kinds of division catch people out, so learn them together.

7 / 2       # 3.5    always gives a float
7 // 2      # 3      floor division, drops the remainder
7 % 2       # 1      the remainder
2 ** 10     # 1024   power

round(3.7)        # 4
int("42")         # 42     text to number
str(42)           # '42'   number to text

None, True and False#

None means no value. It is what a function returns when it does not return anything. It is not zero and not an empty string.

Python also treats some values as false when you use them in an if statement. These are all falsy: False, None, 0, empty string, empty list, empty dict.

items = []

if items:
    print("has items")
else:
    print("empty")        # this runs

The trap in that shortcut

if not items is true for an empty list AND for None. Those are different situations: 'the user sent nothing' versus 'the user sent an empty list'. When the difference matters, check explicitly with if items is None.

Where people go wrong

Forgetting that string methods return a new string. Writing s.upper() on its own line changes nothing. You have to assign the result back with s = s.upper().

If this comes up in an interview

What is the difference between a list and a tuple?

A list can be changed after creation, a tuple cannot. Because a tuple cannot change, it can be used as a dictionary key and a list cannot. Use a tuple when the group of values is fixed, like a coordinate pair.

Why use join instead of adding strings in a loop?

Strings are immutable, so each + builds a whole new string and copies everything so far. Over many iterations that repeated copying makes the loop much slower. join does it in one pass.

What is the difference between == and is?

== compares values. is compares whether two names point to the same object in memory. Use is only for None, True and False. Using it on numbers or strings seems to work for small values because Python reuses those objects, then fails on larger ones.

What does s[::-1] do?

It reverses the string. The three parts of a slice are start, stop and step, so a step of -1 walks backwards through the whole thing.

Build this: Write a program that takes a sentence, prints how many words it has, prints it reversed, and prints each word on its own line with its length next to it.

This is one section of Python, 33 hours across 9 sections. Read it in full to get the whole topic in order.

Stop 1 of 50 on the AI Engineer route

0 of 50 topics done · 0h behind you, 603h to go

Next on this routeHTTP & APIsRequests, status codes, retries, rate limits.8h

What you have marked done is stored in this browser only. It does not reach a server, and clearing site data will clear it.