Random Numbers

Online Courses

Random numbers
The random module can be used to make random numbers in Python. The function random() generates a number between 0 and 1.

Generate a real number between 0 and 1
Simply call the random() method to generate a real (float) number between 0 and 1.

import random
x = random.random()

Generate a number between 0 and 50
We use the randint() method to generate a whole number.

import random
x = random.randint(0,50)

Generate a random number between 1 and 10
Change the parameters of randint() to generate a number between 1 and 10.

import random
x = random.randint(1,10)

List of random numbers
To generate a list of 100 random numbers:

import random

list = []

for i in range(0,100):
    x = random.randint(1,10)


Choosing random items from a list
To get 3 random items from a list:

import random

list = [1,2,3,4,5,6,7,8,9,10]
x = random.sample(list,3)

Strings and Sub-strings

Online Courses

Strings and substrings example
Strings in Python can be defined using quote symbols. An example of a string definition and output below:

s = "Hello World"

Accesing array elements
You may access character elements of a string using the brackets symbol.  Computers start counting from zero, thus  s[0] is the first character:


To print the second character you would write:


String Slicing
You can slice the string into smaller strings. To do so you need to specify either a starting, ending index or both. Let us illustrate that in the Python shell:

>>> s = "Hello World"
>>> s[:3]
>>> s[3:]
'lo World'
>>> s[1:3]

If no number is given, such as in s[:3] it will simply take the beginning or end of teh string. We have accessed the string as if it was an array. If you want to output them from your program, you have to wrap them in the print command. You can store the sliced string as a new string:

slice = s[0:5]

There you have it! String slicing is pretty easy.


Online Courses

Comments example
Comments are little texts that can be added in code. They are created for programmers to read, not computers.  A comment is simply one or more lines of text that is not executed by the computer.

There are two ways to comment in Python: single line and multiline.

Single line comment
A single line comment starts with the number sign (#) character:

# This is a comment

For each line you want to comment, put the number sign (#) in front.

# print('This is not run')

Multiline comment
Multiple lines can be created by repeating the number sign several times:

# This is a comment
# second line
x = 4

but this quickly becomes impractical.  A common way to use comments for multiple lines is to use the (”’) symbol:

''' This is a multiline 
Python comment example.'''
x = 5


Date and Time

Online Courses

Computers handle time using ticks. All computers keep track of time since 12:00am, January 1, 1970, known as epoch time. To get the date or time in Python we need to use the standard time module.

Epoch time
To get the number of ticks, use this program:

import time 

ticks = time.time()
print("Ticks since epoch:", ticks)

The output will be similar to this:

Ticks since epoch: 1450535867.84

Local time
To get the current time on the machine, you can use the function localtime:

import time

timenow = time.localtime(time.time())
print("Current time :", timenow)

The output will not be formatted:

Current time : time.struct_time(tm_year=2015, tm_mon=12, tm_mday=19, tm_hour=15, tm_min=42, tm_sec=0, tm_wday=5, tm_yday=353, tm_isdst=0)

You can access each of the elements of the array:

import time

timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])

and use a combination for your own formatting.  One alternative is to use the asctime function:

import time

timenow = time.asctime(time.localtime(time.time()))

This will show output as:

Sat Dec 19 15:44:40 2015



Online Courses

Modules example
Modules can be used to organize your code.  A module is a Python file with one or more functions and variables.  These functions and variables can be called from your program by importing a module.

A module may be used in your program. In this example we use the math module. This module has many functions such as sine, cosine as well as variables:

import math

x = math.sin(1)

Find available functions and variables in a Python module
To find the available functions in a module, you can use this code:

import math

content = dir(math)

A list will be returned with all functions and variables:

$ python example.py
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Create your own module
First create a Python file with a function. We call this file hello.py and we have one function:

def hello():
    print("Hello World")

Now that we have create a module named hello we can use it in our program test.py

# Import your module
import hello

# Call of function defined in module

Read and Write File

Reading files

Python has built in support for reading and writing files. The function readlines() can be used to read the entire files contents:

#!/usr/bin/env python
filename = "readme.txt"
with open(filename) as fn:
    content = fn.readlines()

Content will contain a list of all strings in the file.

python read file

Writing files

To write files, you can use this code:

!/usr/bin/env python
f = open("output.txt","w")
f.write("Pythonprogramminglanugage.com, \n")
f.write("Example program.")

On the first line we open the file for writing. The parameter “w” tells Python we want to open the file for writing. The write() calls write data into the file. Finally we close the file.

The file created by the Python program.


Online Courses

Dictionary example
A dictionary in Python is a one to one mapping. Every key points to a value, separated by a colon (:). A dictionary is defined using curly brackets. The value left of the colon is called the key, the value right of the colon is called the value. Every (key,value) pair is separated by a comma.

Keys must be unique values, you can not use the same key twice. Values may or may not be unique.


k = { 'EN':'English', 'FR':'French' }

We defined a dictionary named k and access elements using the square brackets you’ve seen before. We use the key [‘EN’] to print the value ‘English’.  A dictionary has no specific order.

Left: the keys ‘EN’ and ‘FR’, right: the values ‘English’ and ‘French’. Thus the dictionary contains the mappings: (‘EN’,’English’), (‘FR’,’French’).

To add a new value to a dictionary you can simply assign a key value pair:

k['DE'] = 'German'

To remove a key/value pair use the del keyword:

k = { 'EN':'English', 'FR':'French' }

del k['FR']


Online Courses

Tuple example
A tuple in Python is a collection that cannot be modified. A tuple is defined using parenthesis.

A tuple with one item ( a comma is needed in the end ):

x = (1,)

A tuple with multiple items:

x = (1,2,3,4)

Accessing tuples

To access individual elements, we use square brackets. To print the first element (Python starts counting from zero):


To print the second element:


To print the last element, you can count from the back using the minus sign.


Command line arguments

Online Courses

Command line arguments
Python programs can be started using command line arguments. For example:

$ python program.py image.bmp

where image.bmp is an argument. You can choose any argument you want in your program.

(You only want to do this with command line programs)

Command line arguments in Python
You can get access to the command line parameters using the sys module.  len(sys.argv) contains the number of arguments.  To print all of the arguments simply execute str(sys.argv)


import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))


$ python3 example.py image.bmp color
Arguments: 3
List: [‘example.py’, ‘image.bmp’, ‘color’]

Storing command line arguments
You can store the arguments given at the start of the program in variables.
For example, an image loader program may start like this:


import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))

if sys.argv < 2:
    print('To few arguments, please specify a filename')

filename = sys.argv[1]
print('Filename:', filename)

Another example:

('Arguments:', 2)
('List:', "['example.py', 'world.png']")
('Filename:', 'world.png')

Line charts

Python Courses

Line chart
You can use Matplotlib to create a line chart with Python. Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension numpy.  This takes only a few lines:

import numpy as np
import matplotlib.pyplot as plt

x = [2,3,4,5,7,9,13,15,17]

In the first two lines we include the numpy and matplotlib library. This contains logical functions to create line charts amongst others. We define a list named x with a few random numbers and we set the x and y label. Finally we call the function show() which will display the line chart. If you do not call the show() function, nothing will be shown on the screen.


by changing the plot function call to:

plt.plot(x, 'ro-')

we create a red graph with dots:

plot python

where the r in ‘ro-‘ indicates red. Changing this to ‘bo-‘ would create a blue dotted line. If you only want to display the dots, use ‘ro’ or ‘bo’ instead.

1 2 3