Skip to main content
Let’s dive into Python by exploring its interactive interpreter as a calculator, working with text, and manipulating lists.
In the examples below, input and output are distinguished by the presence or absence of prompts (>>> and ...). To try these examples, type everything after the prompt.

Using Python as a Calculator

Numbers

The interpreter acts as a simple calculator. You can type expressions and get results:
Integer division and remainder:
Powers:

Variables

Use the equal sign (=) to assign values:
Trying to use an undefined variable raises a NameError:

The Special _ Variable

In interactive mode, the last printed expression is assigned to _:
Treat _ as read-only. Don’t assign to it explicitly, as this creates a new local variable that masks the built-in behavior.

Text (Strings)

Python can manipulate text using the str type. Strings can be enclosed in single or double quotes:

Escaping Quotes

To include quotes in strings, escape them with \ or use the other quote type:

Special Characters

The print() function produces more readable output:

Raw Strings

Use raw strings (prefix with r) to prevent backslash interpretation:

Multi-line Strings

Use triple quotes for strings spanning multiple lines:

String Operations

Concatenation and repetition:
Automatic concatenation of literals:
This only works with literals, not variables:

Indexing and Slicing

Strings can be indexed (subscripted):
Slicing to get substrings:
Visual representation:

String Immutability

Strings cannot be changed (they’re immutable):
Create a new string instead:

String Length

Lists

Lists are compound data types that group together values:

Indexing and Slicing Lists

Like strings, lists support indexing and slicing:

List Concatenation

List Mutability

Unlike strings, lists are mutable:

Adding Items

Assignment and References

Assignment doesn’t copy data. Multiple variables can refer to the same list. Use slicing to create a copy.
Use slicing to create a copy:

Modifying Lists

Assignment to slices:

Nested Lists

First Steps Towards Programming

Let’s write a Fibonacci series using a while loop:
Key features demonstrated:
  1. Multiple assignment: a, b = 0, 1 assigns simultaneously
  2. While loop: Executes as long as the condition is true
  3. Indentation: Python uses indentation to group statements
  4. Print function: Writes output to the screen

Customizing Print Output

Control the line ending with the end parameter:

Next Steps

Now that you understand Python basics, explore Control Flow Tools to learn about if statements, for loops, and functions.