Python Basics
Python Basics
org)
Python interpreter
To run Python programs, you will need the Python interpreter and possibly
a graphical editor.
A Python interpreter executes Python code (sometimes called programs).
A program can be one or more Python files. Code files can include other
files or modules. To run a program, you need to specify a parameter when
executing Python.
python file.py
This site contains exercises for the Python programming language. If you
are new to programming, start with running Python code.
A simple program (hello.py) is shown below. The first line indicates that we want to use the
Python interpreter. The 3rd line outputs a line of text “hello wlrd” to the screen.
The text below can be copied into a text editor and save as hello.py. Python works with files
that end in .py.
#!/usr/bin/env python3
print('hello world')
You can use any text editor to create a Python program. I recommend using a text editor that
supports syntax highlighting (text colouring) and line numbers.
You do not need to specify the datatype of a variable, you can simply assign any value to a
variable. Type the program below and start it.
Datatypes
Variables can be of several data types. Python supports integers (numbers), floating point
numbers, booleans (true or false) and strings (text).
Python will determine the datatype based on the value you assign to the variable. If you
create a variable x, x = 3, then Python assumes its an integer. But if you assign x = 1.5 then
Python knows its not an integer but floating point number.
Example
The example below shows you several variables. These can be assigned as you wish. Once
defined you can print them or use arithmetics.
#!/usr/bin/python
x = 3 # a whole number
print(x)
print(f)
print(name)
sum = f + f
print(sum)
python example.py
In the example we have several variables (x,f,name) which are of different data types. Later
in the program we create more variables (combination, sum).
Variables can be defined anywhere in the program. Variable names can be one to n letters.
Naming
A variable name must begin with a letter (upper or lower case) or an underscore. Variables
cannot start with a number and are case sensitive.
If you create two variables x and X, they are different variables.
Camel casing
By convention variables are often camel cased, meaning the first letter is small and the next
words are all capital.
daysInYear = 365
daysInMonth = 30
numberFiles = 5
Once a string is created, you can simply print the string variable directly. You can access
characters using block quotes.
Strings
Define string
Variables can be of the string data type. They can hold characters or text.
If you create string variable x. You can show it on the screen using the print() function.
x = "Hello"
print(x)
String indexing
Individual characters can be accessed using blockquotes, counting starts from zero.
print(x[0])
print(x[1])
The first character starts at zero. This may be a bit counter intuitive, but has historic reasons.
Sub string
By using a colon you can create a substring. If no start or end number is written, Python
assumes you mean the first character or last character.
x = "hello world"
s = x[0:3]
print(s)
s = x[:3]
print(s)
Complete example
This example does a lot of string operations like printing text, numbers, combining strings,
slicing and accessing elements.
x = "Nancy"
print(x)
Can call the string.replace(old, new) method using the string object. This article demonstrates
the replace method.
Not all programming languages have a standard string replace function. Python has a lot of
functionality that comes out of the box.
Example
Replace method
Define a string and call the replace() method. The first parameter is the word to search, the
second parameter specifies the new value.
The output needs to be saved in the string. If you don’t save the output, the string variable
will contain the same contents. Saving output is done using: s = function()
s = "Hello World"
s = s.replace("World","Universe")
print(s)
python app.py
An optional parameter is the number of items that will be replaced. By default its all.
The program below replaces only the first item:
The parameter (1) indicates that the string should be replaced only once.
Combine them into a sentence with the join(sequence) method. The method is called on a
seperator string, which can be anything from a space to a dash.
This is easier than using the plus operator for every word, which would quickly become
tedious with a long list of words.
Example
The join method takes a sequence as argument. The sequence is written as single argument:
you need to add brackets around the sequence.
If you’d like, you can pass a variable holding the sequence as argument. This makes it easier
to read. We’ll use a space a seperator string in the example below.
# define strings
firstname = "Bugs"
lastname = "Bunny"
sequence = (firstname,lastname)
words = ["How","are","you","doing","?"]
sentence = ' '.join(words)
print(sentence)
The find() method searches for a query string and returns the character position if found. If
the string is not found, it returns -1.
In simple English: find out if a string contains another string.
Example
Find method
The find method returns the index if a word is found. If not found, it returns -1. You can add
a starting index and end index: find(query, start, end), but these parameters are optional.
index = s.find("Dusty")
print(index)
The in keyword
You can also use the keyword _in_. The example below shows you how to use the Python in
keyword.
if "Dusty" in s:
print("query found")
The difference is the in keyword returns if the string contains a word, but find returns the
character position.
Control Structures
If Statements Explained
A program sometimes may have to make choices. These choices can execute different code
depending on certain condition.
The if statement may be combined with certain operator such as equality (==), greater than
(>=), smaller than (<=) and not equal (!=). Conditions may be combined using the
keywords or and and.
Introduction
In the example below we show the use if statement, a control structure. An if statement
evaluates data (a condition) and makes a choice.
Lets have al look at a basic if statement. In its basic form it looks like this:
#!/usr/bin/env python3
if <condition>:
<statement>
In this form
Several examples of the if statements are shown below, you can run them in the Python
interpreter:
#!/usr/bin/env python3
>>> x = 3
>>> if x < 10:
... print('x below ten')
...
x below ten
>>> if x > 10:
... print('x is greater than ten')
...
>>> if x > 1 and x < 4:
... print('x is in range')
...
x is in range
>>>
It’s very important to have four spaces for the statements. Every if statement needs a colon.
More than one condition can be combined using the and keyword.
The example below shows a code block with 3 statements (print). A block is seen by Python
as a single entity, that means that if the condition is true, the whole block is executed (every
statement).
#!/usr/bin/env python3
x = 4
if x < 5:
print("x is smaller than five")
print("this means it's not equal to five either")
print("x is an integer")
All programming languages can create blocks, but Python has a unique way of doing it. A
block is defined only by its indention.
A for loop will repeat a code block. Repeation is continued until the stop condition is met. If
the stop condition is not met it will loop infintely.
Example
In the exercise below we will repeat actions on every item of a list.
The first loop will repeat the print functionfor every item of the list.
The second loop will do a calculation on every element of the list num and print the result.
#!/usr/bin/env python3
city = ['Tokyo','New York','Toronto','Hong Kong']
print('Cities loop:')
for x in city:
print('City: ' + x)
print('\n') # newline
num = [1,2,3,4,5,6,7,8,9]
print('x^2 loop:')
for x in num:
y = x * x
print(str(x) + '*' + str(x) + '=' + str(y))
python loopexample.py
A while loop ends if and only if the condition is true, in contrast to a for loop that always has
a finite countable number of steps.
Example
While loop example
The while loop below defines the condition (x < 10) and repeats the instructions until that
condition is true. Type this code:
#!/usr/bin/python
x = 3
Executes the code below until the condition x < 10 is met. Unlike a for loop, the iterator i is increased
in the loop.
Without functions we only have a long list of instructions. Functions can help you organize
code. Functions can also be reused, often they are included in modules.
Example
Functions
Functions can be seen as executable code blocks. A function can be used once or more.
def currentYear():
print('2018')
currentYear()
The function is immediately called in this example. Function definitions always start with the
def keyword.
Functions can be reusable, once created a function can be used in multiple programs. The
print function is an example of that.
In the example below we have parameter x and y. Type this program and save it as
summation.py
#!/usr/bin/env python3
def f(x,y):
return x*y
print(f(3,4))
In this example we have two functions: f(x,y) and print(). The function f(x,y) passed its
output to the print function using the return keyword.
Return variables
Functions can return variables. Sometimes a function makes a calculation or has some output,
this can be given to the program with a return varaible.
result = f(3,4)
print(result)
In this case the program will call the function f with parameters 3 and 4, then save the output
to the variable result.
A list can have any number of elements. They are similar to arrays in other programming
languages. Lists can hold all kinds of variables: integers (whole numbers), floats, characters,
texts and many more.
Example
Empty list
Lets create an empty list. To define an empty list you should use brackets.
Brackets is what tells Python that the object is a list.
list = []
Lists can hold both numbers and text. Regardless of contents, they are accessed in the same
fashion.
To access a list add the id between the brackets, such as list[0], list[1] and so on.
Define list
An empty list was defined above. Lists can contain all kinds of data.
You can create numeric lists like this:
ratings = [ 3,4,6,3,4,6,5 ]
ratings = [ 'A','A','B','A','C','A' ]
print(ratings)
You can access a list item by using brackets and its index. Python starts counting at zero, that
means the first element is zero.
Computer languages used to count from zero. At the time when programming languages were
first created, it made sense to count from zero. These days it would just be strange to change
that tradition.
To get the first item, simply add the brackets and a zero after the list name.
print(rating[0])
Every other element can be accessed by the incremental numbers, to print the second item
you’d use (1), to print the thrid item you’d use (2).
print(rating[1])
List example
#!/usr/bin/python
list2 = [1,3,4,6,4,7,8,2,3]
print(sum(list2))
print(min(list2))
print(max(list2))
print(list2[0])
print(list2[-1])
List operations
Lists can be changed with several methods. What are these methods?
To add items to a list, you can use the append() method. Call the method on the list, the
parameter contains the item to add. Calling append(3) would add 3 to the list. To remove an
item from the end of the list, you can use the pop() method.
Lists can be accessed like traditional arrays, use the block quotes and index to get an item.
Example
Lists can be modified using their methods.
In the example below we create a list and use methods to change the list contents.
x = [3,4,5]
x.append(6)
print(x)
x.append(7)
print(x)
x.pop()
print(x)
Access items
print(x[0])
print(x[1])
print(x[-1])
List operations
Lists can be changed with several methods. What are these methods?
To add items to a list, you can use the append() method. Call the method on the list, the
parameter contains the item to add. Calling append(3) would add 3 to the list. To remove an
item from the end of the list, you can use the pop() method.
Lists can be accessed like traditional arrays, use the block quotes and index to get an item.
Example
Lists can be modified using their methods.
In the example below we create a list and use methods to change the list contents.
x = [3,4,5]
x.append(6)
print(x)
x.append(7)
print(x)
x.pop()
print(x)
Access items
x = [3,4,5]
print(x[0])
print(x[1])
print(x[-1])
How to Sort a List in Python
Sorting a list is pretty easy: Python has built-in support for sorting lists.
Start with some data: Create a list of numbers and then call the sort() method. This method is
directly called on the list object. This will work with any list, including list of pairs.
Sort example
Sort list
We define a list (x) with a bunch of numbers. Then call the sort method on the list object. We
do not need to save the return variable, simply calling the method is enough.
x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
print(x)
Save the program (sort1.py) and run it. This will output all numbers in low to high order.
words = ["Be","Car","Always","Door","Eat" ]
words.sort()
print(words)
By simply calling the .sort() method, you can sort a list with a number of items.
You do not need to use a return variable when doing this, because lists are objects (more on
this later in the OOP section). For now just remember that you can call .sort() on lists.
Reverse order
x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
x = list(reversed(x))
print(x)
words = words[::-1]
The technique of slicing is used on the list. It means slice the list, starting at the first
character, ending at the last character and with step size of -1 (reverse).
In practice you rarely define lists yourself, you either get them from a database, the web or
generate them using range().
range(stop)
But you can define the starting number of the sequence and then step size.
Python starts counting from zero. Now what if you want to count from 1 to 100?
x = list(range(1,101))
print(x)
A third parameter defines the step size, by default its one. Range can be used in a for loop:
for i in range(1,11):
print(i)
Dictionaries in Python
Python dictionaries are another collection. Real word dictionaries are a good analogy to
understand them: they contain a list of items, each item has a key and a value.
In the traditional dictionary, the key is the word and the value is the explanation or
description of it. In Python you can do something similar.
Example
Introduction
For every key in a dictionary, there is a value. Unlike lists, dictionaries do not have an
specific order.
That means if you were to define a dictionary and loop over it, each time the output could be
different because Python neglects the order.
Defintion
Lets type some code! You can create a dictionary with a one liner. A dictionary is defined
with these brackets {}.
words = {}
Beware: This is just two characters different from a list. Making a typo here, would mix it up
with a list.
Then you can create a mapping. A mapping is defined as a key,value pair. First define the key
then the value:
words[key] = value
Dictionary example
In the example below we define some key,value pairs and then print them using their unique
keys.
Type the code below, save it and run it:
#!/usr/bin/python
words = {}
words["BMP"] = "Bitmap"
words["BTW"] = "By The Way"
words["BRB"] = "Be Right Back"
print words["BMP"]
print words["BRB"]
line by line
read block
Write file in Python
Write file functionality is part of the standard module, you don’t need to include any
modules.
Writing files and appending to a file are different in the Python language.
You can open a file for writing using the line
Nested loops
A loop can contain one or more other loops: you can create a loop inside a loop.
This principle is known as nested loops. Nested loops go over two or more loops.
Programmers typically nest 2 or 3 levels deep. Anything higher than that is just confusing.
Example
Lets do a simple example. We create two lists:
If we have a list of persons who like to eat at restaurants, can we make every one of them eat
a certain restaurant?
#!/usr/bin/python
You can get a copy of the variable, which is the whole or a subset of the original variable.
This concept is known as slicing.
Example
Slicing
slice = pizza[0:2]
The variable slice will now contain a copy of pizza, but only part of it. This is expressed
using the brackets, the first number is the start and the number after the colon is the end.
Python starts numbering of string and list elements from zero, not one.
In this case we took a slice from the list pizza, the output is stored into a new variable.
If you want you can pass it directly to the print function.
List slice
Create a list of persons. We’ll use the slicing technique to get the first two persons in the list.
#!/usr/bin/python
persons = [ "John", "Marissa", "Pete", "Dayton" ]
slice = persons[0:2]
print(slice)
String slicing
A string can be sliced too. This is done in exactly the same way, but the main differnece is
that it won’t return a number of items, but simply a new string.
Multiple return
Python functions can return multiple variables. These variables can be stored in variables
directly. A function is not required to return a variable, it can return zero, one, two or more
variables.
This is a unique property of Python, other programming languages such as C++ or Java do
not support this by default.
Variables defined in a function are only known in the function. That’s because of the scope of
the variable. In general that’s not a problem, unless you want to use the function output in
your program.
In that case you can return variables from a function. In the most simple case you can return a
single variable:
def complexfunction(a,b):
sum = a +b
return sum
Call the function with complexfunction(2,3) and its output can be used or saved.
But what if you have multiple variables in a function that you want access to?
Multiple return
Create a function getPerson(). As you already know a function can return a single variable,
but it can also return multiple variables.
We’ll store all of these variables directly from the function call.
#!/usr/bin/env python3
def getPerson():
name = "Leona"
age = 35
country = "UK"
return name,age,country
name,age,country = getPerson()
print(name)
print(age)
print(country)
Sometimes the word scope is used in projects: “its outside the scope of the project”, meaning
not included. Likewise, a variable can be outside the scope of a function.
Example:
Introduction
Scope has to do with where a variable can be used. If you define a variable, it’s not
necessarily usable everywhere in the code. A variable defined in a function is only known in
a function, unless you return it.
def something():
localVar = 1
That means unless you return the variables from a function, they can only be used there. This
is in stark constrast with global variables: global variables can be used anywhere including in
multiple functions and the main code. Global variables are often defined at the top of the
program.
In the program below, balance is a global variable. It can be used anywhere in the code. But
the variable x can only be used inside addAmount.
#!/usr/bin/env python3
balance = 0
def addAmount(x):
global balance
balance = balance + x
addAmount(5)
print(balance)
The time module has all kinds of time related functions. Not all functions exist on all
operating systems.
The time module starts counting from epoch time, which is 1st January 1970.
Example
Current time
In the example below we output the day,month and year followed by the current time.
timenow = time.localtime(time.time())
The function time.time() returns ticks. Ticks are system ticks every computer holds.
timenow = time.localtime(time.time())
As humans we don’t read system ticks, this needs to be converted to actual human time.
The function localtime() converts these ticks into the actual human readable values.
year,month,day,hour,minute = timenow[0:5]
Convert with:
timenow = time.localtime(time.time())
Type the program shown below and run it:
import time
timenow = time.localtime(time.time())
year,month,day,hour,minute = timenow[0:5]
Epoch time
Time in string
The methods asctime() and ctime() return a 24 character string. Without arguments it gets the
current time.
>>> time.asctime()
'Sat Jul 13 13:53:00 2019'
>>> time.ctime()
'Sat Jul 13 13:53:01 2019'
>>>
Sleep
You can make the program hault execution. The program won’t do anything but wait. The
sleep module lets you do that.
import time
print("Hello")
time.sleep(1)
print("World")
time.sleep(1)
Exceptions are errors that happen during execution of the program. Python won’t tell you
about errors like syntax errors (grammar faults), instead it will abruptly stop.
An abrupt exit is bad for both the end user and developer.
Instead of an emergency halt, you can use a try except statement to properly deal with the
problem. An emergency halt will happen if you do not properly handle exceptions.
If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or
the program will crash. To handle exceptions, the try-catch block is used.
Some exceptions you may have seen before
are FileNotFoundError, ZeroDivisionError or ImportError but there are many more.
All exceptions in Python inherit from the class BaseException. If you open the Python
interactive shell and type the following statement it will list all built-in exceptions:
>>> dir(builtins)
The idea of the try-except clause is to handle exceptions (errors at runtime). The syntax of the
try-except block is:
try:
<do something>
except Exception:
<handle the error>
try: the code with the exception(s) to catch. If an exception is raised, it jumps straight
into the except block.
except: this code is only executed if an exception occured in the try block. The except
block is required with a try block, even if it contains only the pass statement.
else: Code in the else block is only executed if no exceptions were raised in the try
block.
finally: The code in the finally block is always executed, regardless of if a an
exception was raised or not.
try:
1 / 0
except ZeroDivisionError:
print('Divided by zero')
After the except block, the program continues. Without a try-except block, the last line
wouldn’t be reached as the program would crash.
$ python3 example.py
Divided by zero
Should reach here
In the above example we catch the specific exception ZeroDivisionError. You can handle any
exception like this:
try:
open("fantasy.txt")
except:
print('Something went wrong')
You can write different logic for each type of exception that happens:
try:
# your code here
except FileNotFoundError:
# handle exception
except IsADirectoryError:
# handle exception
except:
# all other types of exceptions
try-except
Lets take do a real world example of the try-except block.
The program asks for numeric user input. Instead the user types characters in the input box.
The program normally would crash. But with a try-except block it can be handled properly.
The try except statement prevents the program from crashing and properly deals with it.
try:
x = input("Enter number: ")
x = x + 1
print(x)
except:
print("Invalid input")
The try except statement can be extended with the finally keyword, this will be executed if no
exception is thrown:
finally:
print("Valid input.")
There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on.
Sometimes modules define their own exceptions.
def fail():
1 / 0
try:
fail()
except:
print('Exception occured')
print('Program continues')
This outputs:
$ python3 example.py
Exception occured
Program continues
try finally
A try-except block can have the finally clause (optionally). The finally clause is always
executed.
So the general idea is:
try:
<do something>
except Exception:
<handle the error>
finally:
<cleanup>
For instance: if you open a file you’ll want to close it, you can do so in the finally clause.
try:
f = open("test.txt")
except:
print('Could not open file')
finally:
f.close()
print('Program continue')
try else
The else clause is executed if and only if no exception is raised. This is different from the
finally clause that’s always executed.
try:
x = 1
except:
print('Failed to set x')
else:
print('No exception occured')
finally:
print('We always do this')
Output:
No exception occured
We always do this
You can catch many types of exceptions this way, where the else clause is executed only if
no exception happens.
try:
lunch()
except SyntaxError:
print('Fix your syntax')
except TypeError:
print('Oh no! A TypeError has occured')
except ValueError:
print('A ValueError occured!')
except ZeroDivisionError:
print('Did by zero?')
else:
print('No exception')
finally:
print('Ok then')
Raise Exception
Exceptions are raised when an error occurs. But in Python you can also force an exception to
occur with the keyword raise.
Built-in exceptions
A list of Python's Built-in Exceptions is shown below. This list shows the Exception and why it is
thrown (raised).
User-defined Exceptions
Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.
To create a user-defined exception, you have to create a class that inherits from Exception.
class LunchError(Exception):
pass
You made a user-defined exception named LunchError in the above code. You can raise this
new exception if an error occurs.
$ python3 example.py
Traceback (most recent call last):
File “example.py”, line 5, in
raise LunchError(“Programmer went to lunch”)
main.LunchError: Programmer went to lunch
Your program can have many user-defined exceptions. The program below throws exceptions
based on a new projects money:
class NoMoneyException(Exception):
pass
class OutOfBudget(Exception):
pass
$ python3 example.py
Enter a balance: 500
Traceback (most recent call last):
File “example.py”, line 10, in
raise NoMoneyException
main.NoMoneyException
$ python3 example.py
$ python3 example.py
Enter a balance: 100000
Traceback (most recent call last):
File “example.py”, line 12, in
raise OutOfBudget
main.OutOfBudget
A module is code: in the form of functions or objects. You can include this in your program
and build upon it. You could see this as premade parts that you use build your project with.
PyPI is the Python package index, where all the official modules for Python are stored.
Pip
Install pip
Installation of pip is easy. You can install it with the system package manager. If you use
Linux it’s often already installed.
# fedora linux
sudo yum install python3-pip
Install module
Is pip installed? It can install packages from the PyPi repository. It’s the official repository
for python modules.
Software you install with pip is downloaded from the PyPi repo and installed.
This could be any module from the PiPy index, lets take playsound:
Virtualenv
You’d always want to install inside a virtual environment and not globally on your system.
Virtualenv creates an isolated environment, so packages you install won’t affect other python
projects. You can do that in this way:
virtualenv name
cd name
source bin/activate
Then your environment is active and you can install modules with pip,
Search
You can find packages in the PyPi index either online or in the command line.
To search in the command line type the command below, where topic is the word you want to
search for.