Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 1: Python Basics

This chapter covers the parts of Python you will use in every program.

In this chapter you will learn:

  • The basic rules of Python syntax, such as indentation and comments
  • Python’s basic data types: numbers, strings, booleans and None
  • How to convert values from one type to another
  • How to print values and format them with f-strings
  • How to use variables with arithmetic, comparison, logical and bitwise operators

Basic syntax

Python’s syntax is the set of rules for how code is written. Here is a small program that shows the most important rules:

# This is a comment. Python ignores everything after the # sign.
temperature = 25  # This line creates a variable called temperature

if temperature > 20:
    print("It's warm today.")
    print("No coat needed.")
print("Have a nice day!")

# Output:
# It's warm today.
# No coat needed.
# Have a nice day!

These are the rules to remember:

  1. Statements: Each line usually holds one instruction, called a statement. You don’t need a semicolon at the end of a line.
  2. Indentation: Python uses indentation to group lines into blocks. In the example, the two indented print() lines belong to the if statement, so they only run when the condition is true. The last line isn’t indented, so it always runs. Use four spaces for each level of indentation, and don’t mix tabs and spaces. If the indentation is wrong, Python stops with an IndentationError.
  3. Comments: Anything after a # sign on a line is a comment. Python ignores comments, so you can use them to explain your code to other people, and to your future self.
  4. Variables: You create a variable by assigning a value to a name with =. For example, x = 5 creates a variable called x that holds the value 5. You’ll learn more in Variables and operations.
  5. Case sensitivity: Python treats uppercase and lowercase letters as different, so name, Name and NAME are three different names. Keywords such as if and True must be written exactly as shown.
  6. Data types: Python has several built-in data types, including integers, floating-point numbers, strings, and booleans. The next section covers them.
  7. Operators: Python has operators to work with data, including arithmetic operators (+, -, *, /), comparison operators (==, !=, >, <, >=, <=), and logical operators (and, or, not).

Later chapters build on these basics. Chapter 2 covers control structures (if statements, for loops and while loops) and functions, which you define with the def keyword. Exception handling with try and except, which lets your program deal with errors gracefully, comes in Chapter 4. Chapter 5 introduces object-oriented programming with classes and objects, and Chapter 6 covers modules, including Python’s large standard library.

Data types

Every value in Python has a type, which decides what you can do with it. For example, you can add two numbers, but you can’t add a number to a piece of text. You can check the type of any value with the built-in type() function.

This section covers these basic types:

TypeExampleWhat it holds
int42Whole numbers
float3.14Numbers with a decimal point
complex3+4jComplex numbers, with a real and an imaginary part
str"hello"Text
boolTrueTrue or False
NoneTypeNoneNo value at all

It also gives you a first look at the collection types list, tuple, dict and set, which hold many values at once.

Integers

Integers are whole numbers that can be positive, negative, or zero. For example, 0, 1, -2, and 100 are all integers. Python’s type for integers is int, and an integer can be as large as your computer’s memory allows.

# Declaring and using an integer
x = 10
print(x)  # Output: 10

# Checking the type
print(type(x))  # Output: <class 'int'>

# Adding integers
y = 20
z = x + y
print(z)  # Output: 30

# Dividing integers with / always gives a float
a = 10
b = 3
print(a / b)  # Output: 3.3333333333333335
print(10 / 2)  # Output: 5.0

# Floor division with // rounds down to a whole number
print(a // b)  # Output: 3

# The % operator (modulo) gives the remainder of a division
print(a % b)  # Output: 1

# Exponentiation: 10 to the power of 3
print(a ** b)  # Output: 1000

# Underscores make long numbers easier to read
population = 8_000_000_000
print(population)  # Output: 8000000000

Floats

Floats (short for floating-point numbers) are numbers with a decimal point. For example, 0.5, 3.14, and -1.0 are all floats. Python’s type for them is float.

# Declaring and using a float
x = 10.5
print(x)  # Output: 10.5
print(type(x))  # Output: <class 'float'>

# Adding floats
y = 20.7
print(x + y)  # Output: 31.2

# Dividing floats
a = 10.5
b = 3.1
print(a / b)  # Output: 3.3870967741935485

# Exponentiation
print(a ** 2)  # Output: 110.25

# The remainder of a division works with floats too
print(a % b)  # Output: 1.1999999999999997

The last result is 1.1999999999999997 rather than 1.2. That’s not a mistake in your code. Computers store floats in binary, and most decimal numbers, such as 3.1, can’t be stored exactly that way. The tiny errors this causes usually don’t matter, but sometimes they show up in results. Use round() to round a float to a number of decimal places, and be careful when you compare floats with ==:

print(0.1 + 0.2)  # Output: 0.30000000000000004
print(round(0.1 + 0.2, 2))  # Output: 0.3
print(round(10.5 % 3.1, 2))  # Output: 1.2
print(0.1 + 0.2 == 0.3)  # Output: False

Complex numbers

Complex numbers have a real part and an imaginary part. You will rarely need them unless you work with math, science or engineering. Python writes the imaginary part with a j (instead of the i used in math), so 3+4j is a complex number with a real part of 3 and an imaginary part of 4.

You can also use the complex() function to create complex numbers:

# A real part of 3 and an imaginary part of 4
z = complex(3, 4)
print(z)  # Output: (3+4j)
print(type(z))  # Output: <class 'complex'>

# A real part of 2.5 and an imaginary part of -1
print(complex(2.5, -1))  # Output: (2.5-1j)

# A real part of 0 and an imaginary part of 1
print(complex(0, 1))  # Output: 1j

You can do arithmetic with complex numbers just like with other numbers:

a = 3+4j
b = 1+2j

print(a + b)  # Output: (4+6j)
print(a - b)  # Output: (2+2j)
print(a * b)  # Output: (-5+10j)
print(a / b)  # Output: (2.2-0.4j)

The built-in abs() function gives the absolute value of a complex number, which is its distance from 0 in the complex plane. The .real and .imag attributes give its real and imaginary parts. They are attributes, not functions, so you write them without parentheses:

z = 3+4j

print(abs(z))  # Output: 5.0
print(z.real)  # Output: 3.0
print(z.imag)  # Output: 4.0

Strings

Strings are sequences of characters, such as words or sentences. For example, “hello”, “python”, and “The quick brown fox jumps over the lazy dog” are all strings. Python’s type for strings is str.

You write a string inside single or double quotes: 'hello' and "hello" are the same string. To put a quote character inside a string, surround the string with the other kind of quote, as in "It's warm today.". When you print a string, Python shows its characters without the quotes.

# Declaring and using a string
x = "hello"
print(x)  # Output: hello
print(type(x))  # Output: <class 'str'>

# Joining (concatenating) strings with +
y = "world"
print(x + y)  # Output: helloworld
print(x + " " + y)  # Output: hello world

# Getting the length of a string
print(len(x))  # Output: 5

# Accessing individual characters: positions start at 0
print(x[0])  # Output: h
print(x[-1])  # Output: o

# Slicing: characters at positions 1 and 2 (but not 3)
print(x[1:3])  # Output: el

# Repeating a string
print(x * 3)  # Output: hellohellohello

# Checking if a string contains another string
print("he" in x)  # Output: True
print("hi" in x)  # Output: False

# Changing the case of a string
print(x.upper())  # Output: HELLO
print("HeLLo".lower())  # Output: hello

A negative position counts from the end, so x[-1] is the last character. Strings can’t be changed after they are created. Methods such as upper() give you a new string and leave the original as it was.

Booleans

Booleans represent one of two values: True or False. Python’s type for them is bool. Note the capital letters: true and false aren’t valid Python. Comparisons give you a boolean result.

flag = True
print(flag)  # Output: True
print(type(flag))  # Output: <class 'bool'>

# Comparisons give a boolean result
print(5 > 3)  # Output: True
print(5 == 3)  # Output: False

# isinstance() checks whether a value has a given type
is_bool = isinstance(flag, bool)
print(is_bool)  # Output: True

Booleans are what if statements use to decide which code to run. You can combine them with and, or and not, which are covered in Logical operations below.

is_raining = True
has_umbrella = False

if is_raining:
    print("It's raining.")
else:
    print("It's dry.")

# and is True only if both sides are True; not flips True and False
if is_raining and not has_umbrella:
    print("You'll get wet!")

# Output:
# It's raining.
# You'll get wet!

None

None is a special value that means “no value” or “nothing here yet”. Its type is NoneType, and None is the only value of that type. You’ll often use it as a placeholder for a value you don’t know yet.

middle_name = None
print(middle_name)  # Output: None
print(type(middle_name))  # Output: <class 'NoneType'>

# Use "is" to check whether a value is None
print(middle_name is None)  # Output: True

middle_name = "Rose"
print(middle_name is None)  # Output: False

None isn’t the same as 0, False or an empty string "". It is a value of its own. You’ll also see it in Chapter 2: a function that doesn’t return anything gives back None.

Collections at a glance

So far, each value has been a single piece of data. Collections hold many values in one. Python has four main built-in collection types. Here is a quick look at each one.

A list is an ordered collection that you can change:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple

fruits.append("mango")
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'mango']
print(len(fruits))  # Output: 4

When you print a whole list, Python shows the strings in it with quotes, the way it displays any string inside a collection.

A tuple is an ordered collection that you can’t change after you create it:

point = (3, 4)
print(point)  # Output: (3, 4)
print(point[0])  # Output: 3

A dictionary (dict) stores pairs of keys and values. You look up a value by its key:

person = {"name": "Asha", "age": 30}
print(person["name"])  # Output: Asha

person["age"] = 31
print(person)  # Output: {'name': 'Asha', 'age': 31}

A set is an unordered collection with no duplicate values:

numbers = {3, 1, 2, 3, 1}
print(len(numbers))  # Output: 3
print(2 in numbers)  # Output: True

# Sets have no fixed order, so sort them when you want ordered output
print(sorted(numbers))  # Output: [1, 2, 3]

Chapter 3 covers lists, tuples, dictionaries and sets in detail, along with frozen sets, bytes and byte arrays.

Type conversion

Sometimes you have a value of one type but need another. A common case is text that contains a number. For example, when a user types a number into your program (in a real program this might come from input()), it arrives as a string, and you have to convert it before you can do math with it.

Python’s conversion functions are named after the types they convert to: int() gives you an integer, float() a float, str() a string and bool() a boolean.

# Strings to numbers
age_text = "42"
age = int(age_text)
print(age + 1)  # Output: 43

price = float("19.99")
print(price)  # Output: 19.99

# Between floats and integers
print(int(3.9))  # Output: 3
print(float(7))  # Output: 7.0

# Numbers to strings
count = 3
message = "You have " + str(count) + " new messages"
print(message)  # Output: You have 3 new messages

# Values to booleans
print(bool(0))  # Output: False
print(bool(42))  # Output: True
print(bool(""))  # Output: False
print(bool("hello"))  # Output: True
print(bool(None))  # Output: False

Notice that int() doesn’t round a float: it drops the part after the decimal point, so int(3.9) is 3. Use round() if you want rounding. With bool(), zero, empty strings, empty collections and None count as False, and almost everything else counts as True.

You need str() in the example above because Python won’t join a string and a number with +. If you try, you get a TypeError:

count = 3
try:
    message = "You have " + count + " new messages"
except TypeError as error:
    print(error)  # Output: can only concatenate str (not "int") to str

If a string doesn’t contain a valid number, the conversion fails with a ValueError. Even int("3.5") fails, because “3.5” isn’t a whole number; use float() for that. The examples here use try and except to catch the error and print its message instead of stopping the program. You’ll learn how they work in Chapter 4.

text = "hello"
try:
    number = int(text)
except ValueError as error:
    print(error)  # Output: invalid literal for int() with base 10: 'hello'

Printing and f-strings

You have already used print() to show values. It has a few more options, and f-strings give you an easy way to build text from values. You’ll see both all through this book.

Printing several values

print() can take several values separated by commas. It prints them on one line with a space between each, and then moves to a new line. The sep argument changes the separator, and end changes what is printed at the end instead of the new line.

name = "Asha"
age = 30
print("Name:", name, "Age:", age)  # Output: Name: Asha Age: 30

print(2026, 10, 20, sep="-")  # Output: 2026-10-20

# end="... " keeps the next print on the same line
print("Loading", end="... ")
print("done")

# Output: Loading... done

f-strings

An f-string is a string with the letter f before the opening quote. Inside it, you can put any variable or expression in curly braces {}, and Python replaces it with its value. This is easier than joining strings with +, and you don’t need str().

name = "Asha"
price = 4.5
quantity = 3

print(f"Hello, {name}!")  # Output: Hello, Asha!
print(f"{quantity} apples cost {price * quantity}")  # Output: 3 apples cost 13.5

After the value, you can add a colon and a format specification to control how the value looks. The most useful one is .2f, which shows a number with exactly two digits after the decimal point:

total = 4.5 * 3
print(f"Total: {total}")  # Output: Total: 13.5
print(f"Total: {total:.2f}")  # Output: Total: 13.50
print(f"Pi is about {3.14159:.2f}")  # Output: Pi is about 3.14

Adding !r after a value shows it the way you would write it in Python code. For a string, that means with quotes, which helps you spot extra spaces when you’re tracking down a bug:

user_name = "Asha "
print(f"Hello, {user_name}!")  # Output: Hello, Asha !
print(f"Hello, {user_name!r}!")  # Output: Hello, 'Asha '!

Variables and operations

Variables are names that refer to values. You create one by assigning a value to a name with =. You can give a variable a new value later by assigning to it again, and you can use a variable anywhere you would use its value.

x = 10
y = 20

# Reassigning values to variables
x = 30
y = 40

# Using variables in expressions
z = x + y
print(z)  # Output: 70

The = sign means “assign this value to this name”. It doesn’t mean “is equal to”: to check whether two values are equal, you use ==.

A few rules and conventions for naming variables:

  • Names can contain letters, digits and underscores, but can’t start with a digit. total2 is fine, 2total isn’t.
  • Names are case-sensitive: score and Score are different variables.
  • You can’t use Python’s keywords, such as if, for or class, as names.
  • By convention, Python programmers write variable names in lowercase with underscores between words, like first_name. Choose names that say what the value means: price is clearer than p.

Python supports several kinds of operations, including arithmetic, comparison, logical and bitwise operations. Here are a few examples of each.

Arithmetic operations

x = 10
y = 20

# Addition
print(x + y)  # Output: 30

# Subtraction
print(x - y)  # Output: -10

# Multiplication
print(x * y)  # Output: 200

# Division
print(x / y)  # Output: 0.5

# Modulus (remainder)
print(x % y)  # Output: 10

# Exponentiation
print(x ** y)  # Output: 100000000000000000000

# Floor division (quotient without the remainder)
print(x // y)  # Output: 0

Python follows the usual order of operations from math: ** first, then *, /, // and %, and finally + and -. Use parentheses to change the order, or just to make it clearer:

print(2 + 3 * 4)  # Output: 14
print((2 + 3) * 4)  # Output: 20

To update a variable based on its current value, you can use a shortcut such as +=. Writing score += 5 does the same as score = score + 5. The other arithmetic operators have shortcuts too, such as -=, *= and /=.

score = 10
score += 5
print(score)  # Output: 15

score -= 3
print(score)  # Output: 12

score *= 2
print(score)  # Output: 24

Comparison operations

Comparison operators compare two values and give True or False.

x = 10
y = 20

# Equal to
print(x == y)  # Output: False

# Not equal to
print(x != y)  # Output: True

# Greater than
print(x > y)  # Output: False

# Less than
print(x < y)  # Output: True

# Greater than or equal to
print(x >= y)  # Output: False

# Less than or equal to
print(x <= y)  # Output: True

Logical operations

Logical operators combine booleans. and is True only if both sides are True, or is True if at least one side is True, and not flips True to False and back.

x = True
y = False

# AND
print(x and y)  # Output: False

# OR
print(x or y)  # Output: True

# NOT
print(not x)  # Output: False

You’ll often use them together with comparisons:

age = 25
print(age >= 18 and age < 65)  # Output: True
print(age < 13 or age > 64)  # Output: False

Bitwise operations

Bitwise operators work on the individual bits (binary digits) of integers. You won’t need them often as a beginner, but it helps to recognize them. The bin() function shows the binary form of a number, starting with 0b.

x = 10  # Binary: 01010
y = 20  # Binary: 10100

print(bin(x))  # Output: 0b1010
print(bin(y))  # Output: 0b10100

# AND: 1 only where both bits are 1 (01010 & 10100 = 00000)
print(x & y)  # Output: 0

# OR: 1 where either bit is 1 (01010 | 10100 = 11110)
print(x | y)  # Output: 30

# XOR: 1 where exactly one bit is 1 (01010 ^ 10100 = 11110)
print(x ^ y)  # Output: 30

# NOT: flips all the bits; for integers, ~x is the same as -(x + 1)
print(~x)  # Output: -11

# Left shift: moves the bits one place left, which doubles the number
print(x << 1)  # Output: 20

# Right shift: moves the bits one place right, which halves the number
print(y >> 1)  # Output: 10

Key takeaways

  • Python uses indentation, usually four spaces, to group code into blocks, and # starts a comment.
  • The basic data types are int, float, complex, str, bool and NoneType. Use type() to check a value’s type.
  • / always gives a float, while // and % give the whole-number quotient and the remainder. Floats can have tiny rounding errors.
  • Convert between types with int(), float(), str() and bool(). Converting text that isn’t a valid number raises a ValueError.
  • f-strings such as f"Total: {total:.2f}" are the easiest way to put values into text.
  • = assigns a value to a variable, while == checks whether two values are equal.

Practice

Exercise 1: Temperature converter

Store a temperature of 21.5 degrees Celsius in a variable. Convert it to Fahrenheit with the formula celsius * 9 / 5 + 32, and print the result with one digit after the decimal point, like this: 21.5 degrees Celsius is 70.7 degrees Fahrenheit.

Solution
celsius = 21.5
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius} degrees Celsius is {fahrenheit:.1f} degrees Fahrenheit")

# Output:
# 21.5 degrees Celsius is 70.7 degrees Fahrenheit

Exercise 2: Minutes to hours

A movie is 135 minutes long. Use // and % to work out how many whole hours and leftover minutes that is, and print: 135 minutes is 2 hours and 15 minutes.

Solution
total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes is {hours} hours and {minutes} minutes")

# Output:
# 135 minutes is 2 hours and 15 minutes

Exercise 3: Order total from text

Values that a user types arrive as text. Start with price_text = "4.75" and quantity_text = "3". Convert them to numbers, work out the total, and print it with two decimal places: Total: 14.25. Then set quantity_text to "three", try to convert it, and use try and except ValueError to print the error message instead of crashing.

Solution
price_text = "4.75"
quantity_text = "3"

price = float(price_text)
quantity = int(quantity_text)
total = price * quantity
print(f"Total: {total:.2f}")

# Text that isn't a number raises a ValueError
quantity_text = "three"
try:
    quantity = int(quantity_text)
except ValueError as error:
    print(error)

# Output:
# Total: 14.25
# invalid literal for int() with base 10: 'three'