Python Programming

This tutorial is ideal for:

  • Those who do Python as a part of GCSE Computer Science course- OCR, AQA and Edexcel
  • Those who do Python as a part of AS/A Level Computer Science course - OCR, AQA and Edexcel
  • A complete novice who wants to learn the nitty-gritty of computer programming
  • Those who want a springboard for OOP - Object Oriented Programming
  • Those who want to learn Python quickly on this page - interactively on a real Python Console


Python is an insanely simple programming language to learn, mimic real-life situations and develop high level applications in an elegant manner; it is a language loved by Google too. If you have a passion for programming, this tutorial is a springboard for reaching the ultimate goal, even if you are a complete beginner. If you are a seasoned programmer from another background, this is ideal for a new start.

First of all, here is the link to download the latest Python for a Windows PC: once installed, choose Python IDLE - Integrated DeveLopment Environment or Integrated Development and Learning Environment - from the programmes list. then, follow the instructions in the following animation to write your first piece of code and make it work. Please remember the code you see here will not be part of it!

You will see Python Shell Window, which looks like the following:

python shell

This is also called, interactive mode, because you can write Python commands here, run them by pressing the Enter key and see them at work on the same screen. For instance, in the above animation, I showed how to add, multiply and find the absolute value of a number by using Python commands. Python commands are written next to the primary prompt - >>>. The result is immediately shown just below the primary prompt.

In addition, you can open a Python file, write the commands in it, save it as a .py file and then execute it too - the more professional approach. The file thus saved, can be opened up later to amend the code and re-run it, which is as follows:

Python file

The first part of this tutorial is going to be in the interactive mode - the easier phase.

Programming in Interactive Mode

In interactive mode, Python shell can be turned into a versatile calculator, which is really fun! Here is how:

Let's, for instance, calculate the volume of a cylinder first:

Python interative mode

Here are some examples for you to practise with the interpreter in the interactive mode - in order to be familiar with Python basic operators:

Python operators


It's time to practise interactively; here is the console!


You may experiment with the code samples on this page - or your own - on the console and see the results straightaway. If the screen gets clogged up, please typeclear and hit Enter on the keyboard. It'll clear up the screen.




Variables - the containers in memory!

Python variables

Variables store the information or data in the memory and act as containers. The type of container determines what it can store. The three main types of variables are:

  • str - e.g. "Hello!", for string variables
  • float - e.g. 21.34, for floating point numbers
  • int - e.g. 3, for integers

In addition, there are a few other types: bool - e.g. true/false, Boolean.

In real life, if a sieve is a container, it cannot hold water, but it can hold ice. Exactly in the same way, an integer type cannot hold a string or vice versa. In short, the variable type does matter, when it comes to storing data.

The mechanism of a variable in programming is shown below:

Python variables at work

As you can see, by knowing the exact data type, you can choose the right variable to store and manipulate it inside a programme.

The following animation shows how to determine the variable type by Python's built-in type()function:

Python types

In sieve-water analogy, water cannot be held in a sieve, but ice can be held if water can be turned into ice. In the same way, Python allows us to convert data from one type to another easily and then deal with them. In the following example, an integer is converted into a string and then back into an integer:

Python type conversion

Note: the words followed by # is treated as a comment by Python; so, that part is not executed.


python console link


= means assignment, not equal in programming

The role of the equal sign, =, in programming is a confusing one for beginners. It is an assignment, as shown in the following code:

Python type conversion

In short, = does not behave as the equal sign of an equation, that could lead to a bizarre outcome: a=a+6 => 0=6!

Mathematical Operations Involving Assignment(=)

Here are a few simple mathematical operations that could be done with the assignment sign:

Python operations with assignment

The same can be performed with multiplication - * - and division - / - too.

String Concatenation

In Python, strings can be manipulated to produce the desired outcomes. It is known as string concatenation.

Python string concatenation

In the above example, two words are assigned to the variables, a, and b. When the two variables are added, the string is concatenated to produce the combined phrase we want.


python console link


Sub Programmes

Sometimes, the programming code of the main programme can be very long, which in turn poses certain challenges: the difficulty in maintaining or updating; the repetitive nature of some parts of code. In order to address this issue, sub-programmes come to our rescue. There are two kinds of sub-programmes:

  • ☛ Procedures
  • ☛ Functions


A procedure is something that the main programme can call many times to execute a certain task; it does not return a value.


The following programme uses a procedure, printNumber() to print numbers from 1 - 10, when the main programme calls it.

import time

def printNumber(number): # procedure
   print("This is the number: " + str(number))

count = 0 # main programme
while count<10:
   time.sleep(1) # print with a time gap of 1 second.

The output is as follows:

This is the number: 1
This is the number: 2
This is the number: 3
This is the number: 4
This is the number: 5
This is the number: 6
This is the number: 7
This is the number: 8
This is the number: 9
This is the number: 10

N.B. The procedure must precede the main programme; otherwise, it will throw an error. You may swap the positions around and try it!


Those of us who use calculators know the use of functions quite well: for instance, in order to find the square root of a number, we use the button with the sign, , to invoke the function that gives the square root of the number in question. The number that is entered into the function is called the parameter. The function is said to be returning the value of the number, when pressed. The simplified mechanism is as follows:
square root(number)
inner working hidden from the user
returning the square root as the output

The structure and the working of a function in Python is the same: we see the input and output, with the inner working being hidden from the user, unless you are a programmer. Here are some of the Python built-in functions at work:

Python built-in functions

A Python function to find the average of two numbers can be formed as follows:

Python functions

In the above function, the def keyword defines the function and a and b are the parameters. The function returns the average of the two parameters, when entered into it; please note the indentation of the code, as it is really important in Python.


while loop: The following function shows how a while loop works;

Python while loop

The parameter, a, in the function accepts a number - the seed - and then print the number, increases it by 1 and stops working when the condition of the while is met.

for Loop: The following function shows the use of for loop:

Python for loop

In the first function, range(4) works from 0 to 3. In the second function, range(2,8) works from 2 to 7.

if loop: if loop is illustrated in the following function:

Python if loop

The above function shows how if loop works; please note how python check the equality with two equal signs.




python console link



Pyramid Maker

The following programme prints a triangle of stars, given the number of rows in a function.

n=int(input("How many rows of stars do you want? "))
for i in range(1,n+1):
print ((n-i)*' '+i*'* ')

It uses the simple Python programming trick as follows, in a print statement:
1*'*' = *
2*'*' = **
3*'*' = ***
Here is the output for 15 rows:

Python pyramids


Do you want to practise interactively? Here it is:



More Advanced Functions

☕ Odd_Even_Checker

This is a fairly advanced function that checks whether the user input is odd or even with the aid of if loop.

Python functions odd-even

Here is the full code for the above function:

def odd_even_checker():
if a%2 ==0:
   print("It's an even number.")
   print("It's an odd number.")

☕ Graphics with Python turtle Library

In this case, we have to import a famous Python module called, turtle, which has been especially created for graphics. In order to use the relevant functions, we have to make a reference to the library with the keyword, import, in the code.

Create the function, drawing_square(), inside Python shell as follows:

def drawing_squares():
import turtle # importing the module
trtl = turtle.Turtle() #making a turtle object of Turtle class for drawing
screen=turtle.Screen() #making a canvas for drawing
screen.setup(400,300) #choosing the screen size
screen.bgcolor('black') #making canvas black
trtl.pencolor('red') #making colour of the pen red
trtl.pensize(5) #choosing the size of pen nib
trtl.speed(1) #choosing the speed of drawing
trtl.shape('turtle') #choosing the shape of pen nib
trtl.forward(100) #top line
#turn right through 900 trtl.forward(100) # right vertical line
trtl.forward(100) # bottom line
trtl.forward(100) # left vertical line
# information printing
# pause drawing trtl.setpos(-120,100)
move the pointer to new position trtl.pendown() # restart drawing trtl.pencolor('green')
trtl.write('Square - Vivax Solutions', font=("Arial", 16, "bold"))
# the author informaton trtl.penup() # draw a horizontal line
The above code, if properly run, produces the following image: Python turtle animation

☕ Fibonacci Sequence Generator

The following animation shows how to create a function to generate the famous Fibonacci Sequence in Python. The parameter, f, entered by the user, determines the size of the series.

Python Fibonacci function

The full code is as follows:

def Fibonacci(f):
while b<f:

☕ Quadratic Solver

The following animation shows how to make a simple quadratic solver in Python:

Python quadratic solver

THe complete code of the programme is as follows:

def Quadratic_Solver(a,b,c):
if d>=0:
if d<0:
print ('No real solutions!')
eilf: d==0:
print ('x = ' + str(e))
print ('x = ' + str(e) + ' or '+ str(f))




python console link


☕ Denary to Binary Converter

The following function takes the input of a denary number from a user and gives the output in binary form.

def denaryToBinary(): # function
  nmbr=int(input("Enter the number: ")) # input in denary
     while number>0:
         if number>0:
   return "The number, " + str(nmbr) + ", in binary form = " + string

print(denaryToBinary()) # calling the function

The output is as follows:

Enter the number: 107
The number, 107, in binary form = 1101011

☕ Denary to Hexadecimal Converter

The following function convert decimal numbers - denary - to hexadecimal form:

def denaryToHexa(): #function
  nmbr=int(input("Enter the number: ")) #input in denary
  while number>0:
    if intmed>=0 and intmed<=9:
      string=str(intmed) + string
    elif intmed==10:
    elif intmed==11:
    elif intmed==12:
    elif intmed==13:
    elif intmed==14:
  if number>0:
  return "The number, " + str(nmbr) + ", in hexadecimal form = " + string

print(denaryToHexa()) # calling the function

The output is as follows:

Enter the number: 2018
The number, 2018, in hexadecimal form = 7E2


☕ Solving Equations by Iteration

Here is the code to simulate iteration in Python:

import time
import math
def iterate(): #function
  print("Solving x"+chr(0x00B2)+" - x - 5 = 0 by iteration for GCSE Maths 9-1 by Vivax Solutions\n")
  a=int(input("Enter the initial value, x"+ chr(0x2080) +" : ")) #input x0
    for i in range(0,10):
       string="x" + chr(subs[i])+ "= " + str(a)

This is the code at work:


python math iteration


Password Checker

The following programme checks whether a password contains lowercase, uppercase and numerals.



The programme checks whether the pass password contains at least 8 characters, one uppercase letter and one lowercase letter. Please change the password variable and check it interactively.


Palindrome Checker

A palindrome is a word, a number, a phrase or even a set of characters that reads the same, both forward and backward.


This is a simple Python programme that tests whether a simple word is a palindrome or not.


palindrome code in python 

The process is as follows:

  • The length of the string, the word, is taken.
  • Using the for-loop, the string is reversed and stored in a new variable.
  • Checking whether the two variables are the same.



List is an amazing data type which can store a set of data, separated by commas.Here are two examples:

Cars =['Volvo','BMW','Ford','Citroen','Toyota'];  Integers = [34,56,12,5,6,78]

The data in the list can be referred to by the index of each element: for instance, Cars[0]='Volvo' and Integers[2]=12.

Since list is a flexible data type, there are a few other ways to refer to the elements too. The animation shows most of them.

Python Lists



Tuples are sequences that cannot be updated or changed; the lists, however, can be changed. In addition, the tuples use parenthesis, whereas lists use square brackets.

Subjects = ("physics", "maths", "English", "computing")

The data in the tuple can be referred to by the index of each element: for instance, Subjects[0]='physics' and Subjects[2]='English'.

Bubble Sort

This is an algorithm that arranges a list in ascending order, by comparing each element from the beginning with its adjacent element, until the list is sorted. It's very time consuming and becomes very inefficient, if the list has been almost sorted before being subjected to bubble sort.


Suppose, you are supposed to sort the following list in ascending order:

6, 5, 4, 3, 2, 1

The code for the bubble sort is as follows:

import time # import Python time module to use its sleep() function
def bubble_sort(the_list):
    for i in range(len(the_list)):
      for j in range(i+1, len(the_list)):
        if the_list[j] < the_list[i]:
          the_list[j], the_list[i] = the_list[i], the_list[j] #swapping the two elements
          print (the_list)
          time.sleep(1) #suspend the execution for 1 second to show the progress of the sequence

The following animation shows the progress of the sorting process:


bubble sort



python console link






Resources at Fingertips

There is a significant selection of tutorials here, covering ASP.Net, HTML5, CSS3 and JavaScript. They are categorized clearly for you to access them easily on any device - desktops/laptops, smartphones and laptops.
There are quite a few of them on HTML5 Canvas and CSS3. In addition, there are tutorials on JavaScript and ASP.Net too.

Email: Site email

Stand Out - from the crowd


"There's no such thing as a free lunch."

The best things in nature are free with no strings attached - fresh air, breathtakingly warm sunshine, scene of meadow on the horizon...

Vivax Solutions, while mimicking nature, offers a huge set of tutorials along with interactive tools for free.

Please use them and excel in the sphere of science education.

Everything is free; not even registration is required.



Recommended Reading


The best book to master HTML5 canvas animations. The author tells you how to manipulate the canvas element with JavaScript in a progressive way - starting from the easier to harder worked examples. It is ideal for anyone who wants to be a game developer in HTML5.