This page provides a set of simple Python 3 examples just to bootstrap you into using this language.
Assuming you’ve had exposure to a high-level programming language, the best way to learn Python is to:
- try a few examples and learn to use online help (this tutorial)
- write some new code on your own
- make mistakes
- goto 2
My plan is to add examples over time, so if you have any requests, please let me know. If you need to install Python 3, you can first follow these instructions.
Last modified: 2 March 2017
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:
Variables, Expressions, and Statements
As with other programming languages, Python has variables, expressions, and statements. 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(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!'
Python has typical operators that can be used in expressions, such as
/, and can be used in expected ways, though note the difference between
// is the floor or integer division operator:
>>> 2+3 5 >>> 2*3 6 >>> 2**3 8 >>> 2/3 0.6666666666666666 >>> 2//3 0
% 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
Python uses a number of comparison operators, all of equal priority, and all result in Boolean
|>=||Greater than or equal to|
|<=||Less than or equal to|
|!=||Not equal to|
|is not||Negated object identity|
Binary Boolean operators include
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
>>> 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
range() function creates a data type known as a Python sequence. Another example Python sequence is a
>>> mylist = [9, 8, 2] >>> mylist.append(4) >>> mylist 4 >>> mylist.sort() >>> len(mylist) 4 >>> mylist [2, 4, 8, 9]
list, a Python set is an unordered collection of distinct items — no duplicates.
A Python dict is essentially a mapping of
key: value pairs
Python Functions, Objects, and Modules
In the Python standard library are a number of
Python built-in functions, such as
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
For example to programmatically list all the files in a directory, you can use the
listdir() function in the
import os os.listdir()
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.
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:
The remaining examples in this tutorial assume you are running them from a Python script file.
Note: Be sure to comment your code! Use the `#` symbol: everything after that symbol will be interpreted as a comment.
Python uses indentation for indicating blocks of code:
if username == "root": print("Hello, " + username + ", would you like to play a game?")
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.
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
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!")
Here’s an example
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")
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 loops iterate over a list of items. Here’s an example
for i in range(1, 10): print("I've had " + str(i) + " cups of coffee today!")
range() creates a sequence of values from some start number to some end–1 number, where you specify
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!")
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:
To print the first character:
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:
In other words, print characters at indices 0 to 2.
To print the characters at indices 10 to 15:
To print the first 5 characters:
To print the last five characters:
Just for fun, to print every other character from the first to tenth:
And, to print the string in reverse: