Last modified: 2 June 2021
This page provides a set of simple Python 3 (since Python 2 has reached end-of-life, I don’t recommend Python 2!) examples to help bootstrap you into using this language. Resources at the end of the page provide more details and examples you can consult if you want to dig deeper.
Assuming you’ve had exposure to a high-level programming language, the best way to learn Python is to:
- learn about a new technique or topic
- write some new code on your own
- make mistakes
- fix mistakes
- goto 1
My plan is to add examples over time, so if you have any requests, please let me know.
Interactive Mode and Language Basics
You can run the Python interpreter in Interactive Mode by just calling the name of the interpreter. Similar to a terminal or command line window, for Python the prompt is >>>
. You can then enter expressions interactively, for example to use Python as a calculator:
The interpreter is fine for simple things, like multiplying together a couple of numbers or something, but for any significant tasks you will want to run your code by calling a script from the command line, such as python foo.py
. See Python Programs below.
Variables, Expressions, and Statements
As with other programming languages, Python has variables, expressions, and statements. Python is object-oriented, in that variable types have their own member functions you can used. Also, you do not need to declare a Python variable before using it or even declare its type, unlike statically-typed programming languages. Any value is one of several data types, such as integer, and string. You can identify the data type of a value using the type()
function:
>>> type(3)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("3")
<class 'str'>
>>> type(True)
<class 'bool'>
Also note that the meaning of an operator can change depending on the data types being used. For example, if you use +
between two integers, the result is integer addition. If you use +
between two strings, the result is string concatenation:
>>> 3 + .1415
3.1415
>>> "3" + ".1415"
'3.1415'
Variable names are case-sensitive and there some rules regarding possible variable names. For example, you cannot use hyphens or spaces, you cannot begin a variable name with a number, and you can’t use special characters (like $
). Also, there are a number of Python keywords that cannot be used as variable names, such as
>>> True = 9 * 9
File "<stdin>", line 1
SyntaxError: can't assign to keyword
Here is an assignment statement:
>>> message = "Hello World!"
>>> message
'Hello World!'
Note that in Python you can assign values to multiple variables at the same time:
>>> foo, bar = 7, 2
>>> print(foo, bar)
Python has typical operators that can be used in expressions, such as +
, -
, /
, and can be used in expected ways, though note the difference between /
and //
— //
is the floor or integer division operator:
>>> 2+3
5
>>> 2*3
6
>>> 2**3
8
>>> 2/3
0.6666666666666666
>>> 2//3
0
Note: %
is the modulus operator:
>>> 12 / 7
1.7142857142857142
>>> 12 // 7
1
>>> 12 % 7
5
With precedence, parentheses have the highest precedence, followed by exponentiation, modulus, floor, multiplication and division, and addition and subtraction. Operators with the same level of precedence — eg multiplication and division, are evaluated left-to-right. It’s better to use parentheses to make clear your intent.
>>> 2**3*4+1
33
>>> 2**3*(4+1)
40
Comparisons
Python uses a number of comparison operators, all of equal priority, and all result in Boolean True
or False
:
< | Less than |
> | Greater than |
== | Equal to |
>= | Greater than or equal to |
<= | Less than or equal to |
!= | Not equal to |
is | Object identity |
is not | Negated object identity |
Binary Boolean operators include and
, or
, and not
and work as expected when comparing Boolean values or expressions.
Input and Output
You can ask for input from the user with the input() function. Note that the input()
function returns a string, so if you want to use the value as an int or float, etc., you will need to convert the data type using type converter functions such as int()
, float()
, and str()
:
>>> num = input("Enter an integer between 1 and 10, inclusive:")
Enter an integer between 1 and 10, inclusive:3
>>> num
'3'
>>> num = int(input("Enter an integer between 1 and 10, inclusive:"))
Enter an integer between 1 and 10, inclusive:3
>>> num
3
You can compose output messages using the print()
function, and you can combine multiple expressions together by giving the output of one function as the input to another:
>>> num = int(input("Enter an integer between 1 and 10, inclusive:"))
Enter an integer between 1 and 10, inclusive:3
>>> print("The integer you entered is:", num)
The integer you entered is: 3
Exiting Interactive Mode
You can exit the Interactive Mode by typing exit()
or pressing CTRL-d
:
Data Structures
The range()
function creates a data type known as a Python sequence:
>>> for x in range(7):
... print(x)
...
0
1
2
3
4
5
6
List
Another example Python sequence is a list
:
>>> mylist = [9, 8, 2]
>>> mylist.append(4)
>>> mylist[3]
4
>>> mylist.sort()
>>> len(mylist)
4
>>> mylist
[2, 4, 8, 9]
>>> for x in mylist:
... print(x)
Note: you will get an error if you try to index a list item that does not exist–eg continuing the above example:
>>> print(mylist[9])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
One key feature of lists is the ability to “slice” them–access desired sub-elements from the list without having to iterate through a for
loop:
>>> foo = [1, 2, 3, 4, 5, 6, 7, 8]
>>> foo[3:6]
[4, 5, 6]
>>> foo[4:]
[5, 6, 7, 8]
>>> foo[2:7:2]
[3, 5, 7]
>>> foo[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]
And you can initialize an empty list:
>>> bar = []
>>> type(bar)
<class 'list'>
>>> len(bar)
0
Set
Unlike a list
, a Python set is an unordered collection of distinct items — no duplicates.
Dict
A Python dict is essentially a mapping of key: value
pairs. Think of an English word dictionary that you use to look up word definitions: the word entries listed in the dictionary are unique, though the definitions may not be. Similarly with a Python dict
: the keys are unique, though the values need not be.
For example, to create a dictionary of id# (key) and name (value):
>>> foo = {82734: 'John', 38423: 'Mary', 23984: 'John', 22345: 'Susan'}
>>> len(foo)
4
>>> foo[82734]
'John'
>>> foo[22345]
'Susan'
>>> foo[12345]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 12345
>>> print(foo)
{82734: 'John', 38423: 'Mary', 23984: 'John', 22345: 'Susan'}
>>> foo.keys()
dict_keys([82734, 38423, 23984, 22345])
>>> foo.items()
dict_items([(82734, 'John'), (38423, 'Mary'), (23984, 'John'), (22345, 'Susan')])
>>> foo.values()
dict_values(['John', 'Mary', 'John', 'Susan'])
>>> foo[12345] = 'Sam'
>>> foo.items()
dict_items([(82734, 'John'), (38423, 'Mary'), (23984, 'John'), (22345, 'Susan'), (12345, 'Sam')])
Dicts are very fast data structures that allow you access to the keys quickly. You can quickly tell if a key exists:
if(12345 in foo):
# do something if 12345 is an existing key
You can also use dict.get(key)
which returns the value or None
if that key is not in the dict
.
Note that in this example, the keys were integers and the values were strings. Keys can be strings, numbers, and tuples, whereas the values can be any type.
You can create an empty dictionary with empty braces:
>>> foo = {}
>>> type(foo)
<class 'dict'>
>>> foo = {82734: 'John', 38423: 'Mary', 23984: 'John', 22345: 'Susan'}
>>> for key in foo: # for key in foo.keys(): works as well
... print("Key: ", str(key), " Value: ", foo[key] )
...
Key: 82734 Value: John
Key: 38423 Value: Mary
Key: 23984 Value: John
Key: 22345 Value: Susan
Note that the keys are not guaranteed to be in sorted order. If that is the behavior you want, you should use sorted(dict.keys)
.
Python Functions, Objects, and Modules
In the Python standard library are a number of
Python built-in functions, such as input()
, print()
, and exit()
. There are also a number of modules — collections of related functions. Examples include numeric and math modules, file and directory access modules, file format modules, and cryptographic modules.
You must first import
the module before you can use the functions in the module. In general, place the import
statements at the top of your .py
file.
For example to programmatically list all the files in a directory, you can use the listdir()
function in the os
module:
import os
os.listdir()
The listdir()
function takes a pathname and returns a list
of the directory contents. Note that to tell Python to use the listdir()
function in the os module, as opposed to another function called listdir()
elsewhere, you type module_name.function_name.
Python Programs
For the most part, you are better off creating and running Python programs rather than entering commands in Interactive Mode. So, rather than enter your lines of code one-by-one in the Python interpreter, enter all your lines of code in a text file, and save that text file as some_name.py.
Now you can run those lines of code all at once as: python some_name.py
:
The remaining examples in this tutorial assume you are running them from a Python script file. Verify you can do this!
Note: Be sure to comment your code. Use the `#` symbol: everything after that symbol will be interpreted as a comment.
Flow Control
Python uses indentation for indicating blocks of code:
if username == "root":
print("Hello, " + username + ", would you like to play a game?")
You may have used other programming languages that used curly braces {
instead–Python uses indentation instead. You can indent blocks of code with tabs or spaces, but pick one or the other. It is suggested you use 4 spaces to indent lines of code.
if
So you’ve just seen the if
keyword, which evaluates a condition. Note that the line must end with a :
and the next line starts an indented block of code.
Here’s another example with elif
and else
:
if username == "root":
print("Hello, " + username + ", would you like to play a game?")
elif username == "Kendall":
print("Hello, " + username + ", do you need more coffee?")
else:
print(username + ": get back to work!")
while
Here’s an example while
loop:
count = 0
while count < 10:
print("I've had " + str(count) + " cups of coffee today!")
count = count + 1
Note that the break
statement can be used to break out of a flow control block:
count = 0
while count < 10:
print("I've had " + str(count) + " cups of coffee today!")
count = count + 1
if count == 5:
print("testing")
break
print("OK, that's enough coffee")
The continue
statement is similar, though it is used to immediately advance to the start of the loop.
Also, note that if your program ever enters into an infinite loop, you can press CTRL-c
to stop execution.
for
For loops iterate over a list of items. Here’s an example for
loop:
for i in range(1, 10):
print("I've had " + str(i) + " cups of coffee today!")
Note that range()
creates a sequence of values from some start number to some end–1 number, where you specify range(start, end)
.
Creating Functions
You can create your own functions using the def
keyword and appropriate blocking:
def guessPassword(guess):
if guess == "mysecretpassword":
flag = 1
else:
flag = 0
return flag
correct = 0
while correct == 0:
guess = input("Guess my password: ")
correct = guessPassword(guess)
if correct == 0:
print(" Keep trying!")
print("\nCongratulations!")
Strings
Python strings are sequences of characters. Each string has an index, starting at 0.
foo = "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, ‘and what is the use of a book,’ thought Alice ‘without pictures or conversations?’"
You can access certain characters or ranges of characters by specifying desired character indexes in brackets separated by a colon. The first number is the starting index (inclusive) and the second number is the ending index (exclusive). If one of the numbers is left blank, then that acts as a wildcard.
To print the entire string:
foo[:]
To print the first character:
foo[0:1]
Note the ending index is exclusive, whereas the starting index is inclusive. So in this example, this is saying, “Select the character at the 0 index all the way up to, but not including, the character at the 1 index.”
To print the first three characters:
foo[0:3]
In other words, print characters at indices 0 to 2.
To print the characters at indices 10 to 15:
foo[10:16]
To print the first 5 characters:
foo[:5]
To print the last five characters:
foo[-5:]
Just for fun, to print every other character from the first to tenth:
foo[0:10:2]
And, to print the string in reverse:
foo[::-1]
If you have a string and want to break it up based on some splitting character, you can use the built-in split
function:
>>> foo = "Dicts are very fast data structures that allow you access to the keys quickly"
>>> print(foo)
Dicts are very fast data structures that allow you access to the keys quickly
>>> bar = foo.split(" ")
>>> type(bar)
<class 'list'>
>>> bar
['Dicts', 'are', 'very', 'fast', 'data', 'structures', 'that', 'allow', 'you', 'access', 'to', 'the', 'keys', 'quickly']
>>> print(bar[2])
very
Here we split on the space, " “, but you could split on a different character if you choose. But the point is that bar
is now a list
of the words (in this case) from the string
foo
.
Extra Resources
- Here is a more comprehensive Python tutorial.
- Here is a Python beginner’s guide
- Here is the Python 3 Documentation
- Learn Python!