Introduction to Programming in Python 3

What is Python?

  • A programming language
    • Set of commands that can be interpreted by a piece of software
  • Python is also the name of the software that interprets the commands (3 is a version)
  • Python can be installed on any computer (running Windows, Mac, linux OS) like any other piece of software

FREE!! Graphical User Interface (GUI)

Anaconda - Download and installation https://www.continuum.io/downloads

Pycharm – Download and installation https://www.jetbrains.com/pycharm/

  • PYTHON 2.7

    • Not supported but still popular
  • PYTHON 3.5

    • Latest version and supported
  • There are differences in the code and you need to be careful!

  • We will use PYTHON 3.4 of higher in this module.
![title](Anaconda.png)

Python Shells/Consoles

  • Friendly test zone
  • For testing code

  • OPEN CONSOLE ->

Python will evaluate Expressions that it is given


In [1]:
3+5


Out[1]:
8

In [2]:
5.5 -3.2


Out[2]:
2.3

In [3]:
3*5


Out[3]:
15

In [4]:
5>4


Out[4]:
True

If Python can't evaluate an expression error


In [5]:
3 / 0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-2b706ee9dd8e> in <module>()
----> 1 3 / 0

ZeroDivisionError: division by zero

In python you can save values as variables using the = sign This variable can be used instead of the full value expressions are evaluated before being stored


In [ ]:
a=3
a

In [ ]:
a*2

In [ ]:
b=5*2
b

In [ ]:
c =a+b
c

Virtually everything in python is an Object.

Objects come in different types here are some examples:

  • bool (short for boolean) is a True or False
  • int (short for integer) is a whole number
  • str (short for string) is text
  • float is a number with a decimal point.

Python will automatically assign a type but you can and should override this when needed.


In [ ]:
Operations on variables

In [ ]:
first_name = "Alistair"
last_name = "Darby"
fullname = first_name + last_name
print (fullname)

When used with strings the '+' operator will concatenate them

When used with numbers '+' will behave as you would expect


In [ ]:
aphids = 5
beetles = 12
total_insects = aphids + beetles
print ("Number of insects = ", total_insects)

In [ ]:
aphids = 5
beetles = 12
total_insects = Aphids + Beetles
total_insects_string = str(total_insects)
print("Number of insects = " + total_insects_string)

The str() function will attempt to convert a value into a human-readable string (e.g. 1 becomes “1”) which can then be concatenated. In this case it is only necessary to convert to a string because we are using concatenate (+) in the print statement. When using the normal (,) print will automatically interpret the variable.


In [ ]:
aphids = "5"
plants = "12"
total_insects = aphids * plants
print("Number of insects = ", total_insects)

In [ ]:
aphids = "5"
plants = "12"
total_insects = int(aphids) * int(plants)
print("Number of aphids = " , total_insects)

The int() function will attempt to convert a value into integer (e.g. “1” becomes 1) which can then be used in mathematical operations

Functions in Python

A function is some Python code that has been pre-written to do something useful (you will learn how to write your own later)

Some simple functions are built in:

  • print() prints out a string to the screen
  • len() returns the length (e.g. characters in a string)
  • str() attempts to convert a value to a string
  • int() attempts to convert a value to an integer
  • float() attempts to convert a value to a floating-point

Functions can also be associated with certain types of value. These are known as methods (more about these later!)

  • str.upper() converts a string to upper case

Using some Python functions


In [ ]:
some_dna = "atcgacgtacgtg"
dna_length = len(some_dna)
big_dna = str.upper(some_dna)
print ("The length of " , big_dna ,  " is " , dna_length , "\n")

Special characters in Strings

Strings can contain non-text characters with special meanings Most useful are:

\n newline (end of line character) \t tab


In [ ]:
print("Hello, World!\n")    # adds a new line at the end
print("Hello\tWorld!")       # puts a tab character in

Comments and documentation

Very important to document your scripts Add useful comments to explain purpose Makes it easier for you and easier for someone else to re-use or understand what you’re doing

‘#’ makes the program ignore everything that follows it on that line

For example…


In [ ]:
# This code demonstrates some basic string operations
some_dna = "atcgacgtacgtg" # define the dna string

# the following section contains the string operations
dna_length = len(some_dna) # return the string length
big_dna = str.upper(some_dna) # convert the string to uppercase

# print the outputs and convert dna_length to a string
print("The length of " , big_dna ,  " is " , str(dna_length) , "\n")

Getting user input

The input() function makes the program wait for the user to input something on the keyboard and hit enter before continuing


In [ ]:
name = input()

You can also add an input prompt

name = input("What is your name?") print("Hello ", name, "!")

Incorporating input


In [ ]:
# This script calculates the number of cats you need
rooms = input("How many rooms do you have? ")
cats = input("How many cats fit in a room? ")
Total_cats = int(rooms) * int(cats)
print("You require " , Total_cats , " cats")

Modules in Python

  • There is no need to re-invent the wheel - unless you’re learning!
  • Modules are pre-written pieces of code (such as useful functions) that are designed for specific tasks
  • You need to call these at the top of the script
  • Before you use a module you have to reference it in your script like this:

In [ ]:
from math import *
  • math is the name of the module
  • An asterisk in this context means ‘everything in the module’. Alternatively you can put the specific function you want to use here

In [ ]:
from math import *
a = log10(1000000)
print(str(a))

An asterisk in this context means ‘everything in the module’.


In [ ]:
from math import log10
a = log10(1000000)
print(str(a))

Alternatively you can put the specific function you want to load here.


In [ ]:
# Regular expressions
  • These are incredibly useful (topic of a later lecture)
    • Way of matching and manipulating strings e.g. “Find and replace” operation
  • One example is sub()
    • Substitutes one pattern in a string for another

In [ ]:
from re import sub
string = "Al Darbi"
string_mod1 = sub('l','C',string)
string_mod2 = sub('i','y',string_mod1)
print(string)
print(string_mod2)

You will hear lots more about regular expressions later on, but there is just one example included here, in case you’re interested in reading more about them (might also be useful for the part of the assignment...)

Making errors / refining scripts

  • Scripts almost never work first time
  • Usually require fixing small mistakes:
    • Syntax (i.e. Python gives an error when you try to run)
    • Runtime (something goes wrong while it is running)
    • Logic (script doesn’t behave as you expect)
  • Often error messages are not very informative
    • Takes a bit of practice to work out what might be causing an error

Tip: One way to check for syntax errors is to read each line of code from the end to the beginning. This forces you to look at each line without attaching meaning.

Syntax Errors

Most syntax errors are due to incorrect formatting like: Missing matching quotes


In [ ]:
name = "Darby
print(name)

Missing brackets


In [ ]:
x = (y + z

Variable name spelling or capitalisation Indentation (covered in a later lecture)

Runtime errors


In [ ]:
x = 6
y = 0
z = x / y
print (z)

logic errors

  • Logic errors are harder to identify
    • May cause unintended behaviour rather than a crash
    • Example: ordering of math operations

In [ ]:
x = 3
y = 7
average = x + y / 2
print(average)

Note: Knowing how to fix errors in the logic comes with practice, good commenting of your code and planning your code before you write it (e.g. Draw a flow diagram)


In [ ]:
x = 3
y = 7
average = (x + y) / 2
print(average)

Summary

  • Brief intro to Python and the shell
  • Variables
  • Operations on variables
  • Variable types and type setting
  • Built-in Functions
  • User input
  • Fixing basic errors

Now you have to try these out for yourself...


In [ ]: