Python for beginners comes down to eight ideas: variables, numbers, strings, lists, dictionaries, if statements, loops and functions. This page explains each one with a short example, using the behavior described in the official Python 3 tutorial.
Examples marked >>> are what you would type at the interactive prompt, which you start by running python (or py on Windows) in a terminal. If Python is not installed yet, see how to install Python on Windows, then run your first program. Everything below is Python 3.
Variables and comments
A variable is a name that points to a value. You create it by assigning with =. There is no declaration step.
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
A comment starts with # and runs to the end of the line. A # inside a string is just a character, not a comment:
spam = 1 # this is a comment
text = "# This is not a comment because it's inside quotes."
Numbers and division operators
The usual operators work: +, -, *, and parentheses for grouping. Division is where beginners get surprised, because Python has three related operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
/ | Division, always returns a float | 17 / 3 | 5.666666666666667 |
// | Floor division, drops the fraction | 17 // 3 | 5 |
% | Remainder | 17 % 3 | 2 |
** | Power | 2 ** 7 | 128 |
Note that / returns a float even when the answer is whole: (50 - 5*6) / 4 gives 5.0, not 5. Also, ** binds tighter than a minus sign in front of it, so -3**2 is -9 and (-3)**2 is 9.
Strings
A string is text in single or double quotes. Both produce the same result, so pick whichever lets you avoid escaping:
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
len() returns the length, and square brackets pick out a character by position. Positions start at 0, and negative numbers count from the right:
>>> word = 'Python'
>>> word[0]
'P'
>>> word[-1]
'n'
>>> len(word)
6
Strings are immutable: you cannot change a character in place. Assigning to word[0] fails with TypeError: 'str' object does not support item assignment. Build a new string instead, for example 'J' + word[1:], which gives 'Jython'. To put variables inside text, use an f-string, covered in Python f-strings.
Lists
A list holds an ordered sequence of items in square brackets. Unlike strings, lists are mutable. Indexing works the same way as for strings, and a slice returns a new list:
>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64
>>> cubes.append(216)
>>> cubes
[1, 8, 27, 64, 125, 216]
>>> cubes[-3:]
[64, 125, 216]
>>> cubes.pop()
216
append adds an item to the end. pop removes an item and returns it; with no argument it takes the last one. sort sorts the list in place and returns nothing.
Tuples and sets
A tuple, written (1, 2, 3), is like a list that cannot change. Assigning to an item raises TypeError: 'tuple' object does not support item assignment. A set, written {'apple', 'pear'}, is an unordered collection with no duplicates, so it is the quick way to remove repeated values. Because sets are unordered, printing one can show the items in a different order than you typed them.
Dictionaries
A dictionary stores key and value pairs. Keys must be unique, and storing a value under a key that already exists replaces the old value:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['irv']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'irv'
>>> print(tel.get('irv'))
None
Reading a missing key with tel['irv'] raises KeyError. The get() method returns None instead, or a default you pass as a second argument.
Making decisions with if, elif and else
An if statement runs a block only when its condition is true. The header line ends with a colon, and the block below it is indented. You can chain any number of elif parts, and else is optional:
x = 1
if x < 0:
print('Negative')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
With x = 1 this prints Single. Use == to compare and = to assign; mixing them up is a common first error. A missing colon or inconsistent indentation produces an error before the program runs.
Repeating work with for loops and range
A for loop goes through the items of a sequence, such as a list or a string, in order:
words = ['cat', 'window', 'defenestrate']
for word in words:
print(word, len(word))
Example output:
cat 3
window 6
defenestrate 12
To repeat something a set number of times, loop over range(). The end point is never part of the sequence, so range(5) produces 0, 1, 2, 3, 4. Two arguments set the start (range(5, 10) gives 5 to 9) and a third sets the step (range(0, 10, 3) gives 0, 3, 6, 9).
Functions
A function packages code you want to reuse. The keyword def starts it, and the body is indented. return sends a value back to the caller:
def area(width, height=1):
return width * height
print(area(4, 5))
print(area(4))
The first call prints 20. The second prints 4, because height has a default value and can be left out. A function that reaches its end without a return value gives back None.
One trap worth knowing early: a default value is evaluated only once, when the function is defined. If the default is a mutable object such as [], every call shares the same list. The tutorial's fix is to default to None and create the list inside the function:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
What to learn next
Once the pieces above feel familiar, two topics will stop most beginner scripts from breaking. The first is handling errors without crashing: see Python try and except. The second is keeping each project's packages separate with a virtual environment. Beyond that, the best practice is to write small programs: a script that counts words in a text, a unit converter, a number guessing game. Each one uses variables, a loop, a condition and a function, which is the whole list above.
Frequently asked questions
- How long does it take to learn Python basics?
- There is no reliable figure, because it depends on how much time you practise and what you already know. A practical test: when you can write a short program that reads input, uses a loop, an if statement and a function without copying, you have the basics covered. Typing out and changing the examples yourself speeds this up more than reading does.
- Should I learn Python 2 or Python 3?
- Python 3. The official tutorial and documentation at docs.python.org/3 describe Python 3, and the examples in this article use Python 3 syntax. Install a current Python 3 release and ignore guides that use print as a statement without parentheses.
- What is the difference between a list and a tuple?
- A list can be changed after it is created, with methods such as append and pop or by assigning to an index. A tuple cannot: assigning to one of its items raises TypeError: 'tuple' object does not support item assignment. Use a tuple for a fixed group of values and a list for a collection that grows or changes.
- Why does Python care about indentation?
- Python uses indentation to mark which lines belong to a block, such as the body of an if statement, a loop or a function. The block header ends with a colon, and every line of the body must be indented consistently. There are no braces to fall back on.