introduction to python slides · python3 hello_world.py names, functions and methods. names...

117
Introduction to Python Steven Wingett, Babraham Bioinformatics

Upload: others

Post on 10-Jul-2020

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Introduction to PythonSteven Wingett, Babraham Bioinformatics

Page 2: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Why learn Python?

• Arguably now the main bioinformatics programming language• Free• Works on many computers• Nice learning curve• Large community• Much additional bioinformatics / computational biology software• Short development time• BUT, there are faster programming languages

Page 3: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

What the course covers

• Assumes (virtually) no prior knowledge• By the end you have the materials to be competent at Python• Be able to write code of intermediate complexity• This should be at a level to help you with real-word problems• Python 3 (although actually very similar to Python 2)• Learning a programming language is NOT easy – but few things

worthwhile learning are

Page 4: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

How to install Python

• Comes bundled with Thonny• Manual provides details on installation for PC/Mac/Linux• Check if it is installed via command line: python3 --version (or

sometimes py --version)

Page 5: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Python Website

• python.org

• Download

• Documentation

• Community

• News

Page 6: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Getting started with PythonSection 1

Page 7: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

How to write Python code• Python is text, so is Notepad ok?• Vi – preinstalled on Linux, but difficult for the novice• Emacs – Common on Linux, but not so easy for the novice • Notepad++ - Versatile and good, but only on Windows• Sublime Text – Versatile and good and on most systems• Visual Code - Versatile and good and on most systems• PyCharm – A good IDE, but a little complex at first• IDLE – Another IDE, and comes with Python• Jupyter – A great way to share code and results

Getting started with Python

Page 8: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Thonny• Simple IDE

• Linux, Windows and Mac

• https://thonny.org

• Raspberry Pi

• Let’s take a look at Thonny

Scripting window

Interactive window

Getting started with Python

Page 9: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Cheat Sheet

• Chapter 1 exercises

Getting started with Python

Page 10: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Data types and expressionsSection 2

Page 11: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Data types and expressions

• A command which includes a data type and an operator is known as an expression

• 1 + 1 is an expression

• There are different primitive data types in Python: integer, float, boolean and strings

Data types and expressions

Page 12: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: integers• These are the counting numbers:

1, 2, 3, 4, …and 0and the negative numbers -1,-2, -3, -4, …

They do NOT have non-zero digits after the decimal point

Getting started with Python

Page 13: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: integers• Integers can be manipulated with operators:

Let’s have a look at integers using Thonny….

Getting started with Python

Page 14: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: floats• Floats short for “floating point numbers”• Used to represent non-integer numbers (but actually can be used to

represent integers as well)• Floats have two components: the significand and the exponent• Floats may be entered using scientific notation: 3.0E10 is equivalent

to 30000000000.0• Lets look at floats in Thonny…

Getting started with Python

Value Significand Exponent

0.5 5 -1

0.001 1 -3

-10.5 -1.05 1

Page 15: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Integer/float operatorsOperator Action+ Addition- Subtraction* Multiplication/ Division** Raise to a powerFloor division //// Modulus

Getting started with Python

Page 16: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Compound expressions• A single expression may contain many values and operators

• But you may not get an expected results owing to orders of precedence:

>>> 5 + 5 * 320

• Use parenthesis to clarify expression:>>> (5 + 5) * 330

Getting started with Python

Page 17: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

Getting started with Python

Try exercises 2a, 2b, 2cOperator Action+ Addition- Subtraction* Multiplication/ Division** Raise to a powerFloor division //// Modulus

Page 18: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: booleans• Only two values: either True or False• Generated with comparison operator tests• == is not the same as =

Comparison Operator

Description

== If the values of two operands are equal, then the condition is True != If values of two operands are not equal, then condition is True > If the value of left operand is greater than the value of right operand, then condition

is True < If the value of left operand is less than the value of right operand, then condition is

True >= If the value of left operand is greater than or equal to the value of right operand, then

condition is True <= If the value of left operand is less than or equal to the value of right operand, then

condition is True

Getting started with Python

Page 19: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: booleans• Comparison test examples:

>>> 1 == 1True

>>> 1 == 0False

>>> 2 > 5False

Getting started with Python

Page 20: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: booleans• True or False can be evaluated themselves:>>> TrueTrue

>>> FalseFalse

• Case sensitive:>>> trueTraceback (most recent call last):File "<pyshell>", line 1, in <module>

NameError: name 'true' is not defined

Getting started with Python

Page 21: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: booleans• Boolean logic with and/or/not:

>>> True and TrueTrue

>>> True and FalseFalse

>>> not TrueFalse

>>> not FalseTrue

Getting started with Python

Page 22: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: booleans• The and, or and not operators can take values other than True/False• 0 or None (another data type) evaluate to False, everything else is True• The value returned is the value when a decision can be first made

>>> 1 and 00

>>> 1 and 22

>>> 1 or 01

>>> 1 or 21

Getting started with Python

Page 23: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: booleans• Exercises 3a and 3b.

Getting started with Python

Page 24: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Primitive data type: Strings

• Store Unicode characters

• Can contain many characters is (i.e. a “string” of characters)

• Useful for manipulating text an sequences (e.g. DNA stored as text)

• May also be manipulated by operators (similar to numbers)

Getting started with Python

Primitive data type: Strings

• Store Unicode characters

• Can contain many characters is (i.e. a “string” of characters)

• Useful for manipulating text an sequences (e.g. DNA stored as text)

• May also be manipulated by operators (similar to numbers)

Getting started with Python

Page 25: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating strings• Single quote:>>> 'abcde12345'

'abcde12345’

• Double quote:>>> "abcde12345"'abcde12345'

• Across lines:>>> print("""line1

line2""")

line1Line2

• Metacharacters:>>> print("line1\nline2")

line1

line2

>>> print("line1\tline2")line1 line2

Note: you need to print the string to display without the metacharacter

• Combining double and single quotes:'You're gonna need a bigger boat'"You're gonna need a bigger boat" 'You\'re going to need a bigger boat'

"You\'re going to need a bigger boat"

Getting started with Python

Page 26: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

String operations• Concatenation:>>> 'Love' + 'Marriage''LoveMarriage'

• Multiplication:>>> 'Go forth ' * 5'Go forth Go forth Go forth Go forth Go forth '

• The in operator:>>> 'Needle' in 'HaystackHaystackNeedleHaystackHaystack'True

>>> 'Elvis' not in 'Building'True

• Case sensitive:>>> 'NEEDLE' in 'HaystackHaystackNeedleHaystackHaystackHaystackHaystack'False

Page 27: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Strings: subscription and splicing (1)

• It is possible to extract characters from a string using a numeric referencing system

BabrahamGetting started with Python

Page 28: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Strings: subscription and splicing (2)

• Each character has a numerical positional reference• Counting starts at 0

Babraham01234567

Getting started with Python

Page 29: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Strings: subscription and splicing (3)

• A reverse (right-to-left numbering system using negative numbers)• “Begins” at -1 (not 0)

Babraham0123456787654321

Getting started with Python

Page 30: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Strings: subscription and splicing (4)

>>> 'Babraham'[1]'a'

>>> 'Babraham'[0]'B'

>>> 'Babraham'[2]'b'

>>> 'Babraham'[-1]'m'

>>> 'Babraham'[-3]'h'

Getting started with Python

Page 31: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Strings: subscription and splicing (5)• Operations can be performed within the brackets:>>> 'Babraham'[100 - 99]'a'

• Slicing:>>> 'Babraham'[1:4]'abr'

>>> 'Babraham'[-4:-2]'ah'

• Shortcuts:>>> 'Babraham'[:3]'Bab'

>>> 'Babraham'[5:]'ham'

>>> 'Babraham'[:]'Babraham'

>>> 'Babraham'[::3]'Bra’

• Impossible splices return empty strings:>>> 'Babraham'[2:1]''>>> 'Babraham'[-1]'m'

>>> 'Babraham'[-3]'h'

Getting started with Python

Page 32: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 4 about Strings

Getting started with Python

Page 33: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Names, functions and methodsSection 3

Page 34: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Writing scripts using Thonny

• For more complex code• Can save scripts• Save with .py extension• Useful coloured code• Can also run from command line:python3 hello_world.py

Names, functions and methods

Page 35: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Names• Names used by Python to represent numbers or characters• Assignment statement• Numbers: a = 1• Strings: b = 'MyString'• Statements, unlike expressions, don’t return values • Thonny: View -> Variables• Can assign names to existing names: c = b• Multiple simultaneous assignment: d = e = f = 'ManyToOne’• Use lowercase letters and underscores (_)

Names, functions and methods

Page 36: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Names• Assignments can be made while calculating: g = 10 * 5

• Names may be manipulated as one would manipulate the valuesa = 1b = 2c = a + b

Names, functions and methods

Page 37: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Writing your first script (Exercise 5) • Introducing names (Exercise 6)

Names, functions and methods

Page 38: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

F-strings• F-strings provide a simple yet powerful way to format strings• Literal part in quotes, expression part between curly brackets

>>> user = 'Octavian'>>> f"Hi {user}"'Hi Octavian'

Since they are expressions, they can perform calculations as well:>>> F'Two plus two is {2 + 2}'

'Two plus two is 4'

>>> f'I have £{1000 * 1000}!'

'I have £1000000!'

Names, functions and methods

Page 39: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

F-strings (2)• Number formatting:

>>> f'I have £{1000 * 1000:,}!''I have £1,000,000!'

• Decimals (two decimal places, fixed):>>> f'I have £{1000 * 1000:,.2f}!''I have £1,000,000.00!'

• Percentages:>>> vat = 0.2>>> f'VAT rate: {vat:.1%}''VAT rate: 20.0%'

Names, functions and methods

Page 40: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

F-strings (3)

• Width and alignment:>>> pointer = '<->'

>>> f'Left-aligned{pointer:<50}'

'Left-aligned<-> '

>>> f'Right-aligned{pointer:>50}'

'Right-aligned <->'

>>> f'Centre-aligned{pointer:^50}'

'Centre-aligned <-> '

• F-strings may also encompass multiple lines, as per regular strings

Names, functions and methods

Page 41: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• F-strings

Names, functions and methods

Page 42: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Functions: built-in functions

• Every function returns a value and so a type of expression • A function is a type of expression known as a call• Functions are “called”

print("Hello World!")

Round brackets

Function name Argument

Names, functions and methods

Page 43: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Functions: built-in functions

• More examples:

• len('Supercalifragilisticexpialidocious’)

• min(2, 4, 100, 205.3, -4)

• max(2, 4, 100, 205.3, -4)

Names, functions and methods

Page 44: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

List of built in functionsabs() delattr() hash() memoryview() set()

all() dict() help() min() setattr()

any() dir() hex() next() slice()

ascii() divmod() id() object() sorted()

bin() enumerate() input() oct() staticmethod()

bool() eval() int() open() str()

breakpoint() exec() isinstance() ord() sum()

bytearray() filter() issubclass() pow() super()

bytes() float() iter() print() tuple()

callable() format() len() property() type()

chr() frozenset() list() range() vars()

classmethod() getattr() locals() repr() zip()

compile() globals() map() reversed() __import__()

complex() hasattr() max() round()

• Help() gives you information on these functions and other aspects of Python

Page 45: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Determining and changing data types• Use the type()function to ascertain the datatype of a Python object

• A data type may be changed (where possible) from one to another with the casting functions:• int() - constructs an integer number from an integer, float (rounds down)

or a string (if a number)• float() - constructs an float number from an integer, float (rounds down)

or a string (if a number)• str() - - constructs a string from a wide variety of data types, including

strings, integer literals and float literals

Names, functions and methods

Page 46: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Changing datatypes example

>>>type(378163771)<class 'int'>

>>>type('Hello World!')<class 'str'>

>>>type('378163771')<class 'str'>

>>>int('378163771') - 1378163770

Page 47: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 8 – built-in functions

Page 48: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: general syntaxdef function_name (parameters list):

function code….….….

• def keyword, function name and parameters list (if any)• Colon then 4-space indention• Body of function (the bit that does stuff)

Names, functions and methods

Page 49: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: minimal functiondef minimalist():

pass

minimalist()

Names, functions and methods

Page 50: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: Hello World!

def HelloWorld():print ("Hello World!")

HelloWorld()

>>>Hello World!

Names, functions and methods

Page 51: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: passing argumentsdef HelloUser(name):

print ("Hello " + name)

HelloUser("Bob")

>>>Hello Bob

Names, functions and methods

Page 52: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: passing named argumentsdef HelloUser2(firstname, surname):

print ("Hello " + firstname + ' ' + surname)

HelloUser2("Andy", "Ball")>>Hello Andy Ball

HelloUser2(surname="Ball", firstname="Andy")>>>Hello Andy Ball

Names, functions and methods

Page 53: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: returning values

def percentageCalculator(value, total):percentage = (100 * value / total)return(percentage)

score = percentageCalculator(9, 18)print(score)

>>>50

Names, functions and methods

Page 54: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: documenting functions

#We could write a comment here describing

#our function, but it is more useful to

#enter this information in the docstring

def percentageCalculator(value, total):

"""Takes a value and a total and

returns the percentage value"""

return(100 * value / total)

help(percentageCalculator)

Help on function percentageCalculator in module __main__:

percentageCalculator(value, total)

Takes a value and a total and

returns the percentage value

Names, functions and methods

Page 55: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: default parameter valuesdef calculateVAT(initial, rate=20):

"""Calculates the cost of an item after Value Added Tax.

The function takes an initial value (integer/float) as

input and an optional VAT percentage rate (integer/float),else defaults to 20%."""vat = initial / 100 * rate

new_cost = initial + vatreturn(new_cost)

print(calculateVAT(500, 10))

print(calculateVAT(500))

>>> 550.0

600.0

Names, functions and methods

Page 56: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: assertions

def HelloUser(name):

"""Says hello to the nameduser. Takes a stringinput."""

assert isinstance(name,str), 'The input needs to be a string'

print ("Hello " + name)

HelloUser(1)

>>> %Run functions.pyTraceback (most recent call last):File

"/Users/wingetts/functions.py", line 25, in <module>

HelloUser(1)File

"/Users/wingetts/functions.py", line 22, in HelloUser

assert isinstance(name, str), 'The input needs to be a string'AssertionError: The input needs to be a string

Names, functions and methods

Page 57: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Creating your own functions: passing multiple arguments def accept_multiple_argments(*args):

print(type(args))print(args)

my_list =['a', 'b', 'c']accept_multiple_argments(1,2,3,4, my_list)

>>> <class 'tuple’>(1, 2, 3, 4, ['a', 'b', 'c'])

Names, functions and methods

Page 58: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 9: user-defined functions

Page 59: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Methods

• Methods are the other type of calls• Different data types may have different methods• Uses the dot notation• Methods may take arguments

Example:>>> 'abracadabra'.count('a')5

Names, functions and methods

Page 60: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

String MethodsMethod Purpose

capitalize() Converts the first character to upper case

count() Returns the number of times a specified value occurs in a string

find() Searches the string for a specified value and returns the position of where itwas found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isdecimal() Returns True if all characters in the string are decimals

join() Joins the elements of an iterable to the end of the string

lower() Converts a string into lower case

replace() Returns a string where a specified value is replaced with a specified value

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

strip() Returns a trimmed version of the string

title() Converts the first character of each word to upper case

upper() Converts a string into upper case

Page 61: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 10: Methods

• Exercise 11: Tying it all together

Names, functions and methods

Page 62: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

CollectionsSection 4

Page 63: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Collections

• Compound data types that contain multiple objects

• Sometimes known as containers

• Four groups: sets, sequences, mappings and streams

Collections

Page 64: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets - creation

• Mutable collection of unordered unique elements• To create, either:

set('ABBA'){'B', 'A'}

or

beatles = {'John', 'Paul', 'George', 'Pete'}beatles{'Paul', 'John', 'Pete', 'George'}

Letters are not de-duplicated in second example

Collections

Page 65: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets - editing

Addingbeatles.add('Ringo')beatles{'Ringo', 'Pete', 'John', 'Paul', 'George'}

Removingbeatles.remove('Pete')beatles{'Ringo', 'John', 'Paul', 'George'}

Collections

Page 66: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets – a note on removing entries

• Error if remove not-existent entrybeatles.remove('Stuart')Traceback (most recent call last):File "<pyshell>", line 1, in <module>KeyError: 'Stuart'

• But, not if discard is usedbeatles.discard('Stuart')

Collections

Page 67: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets: combining / comparing

• Python sets can be combined and compared just like the sets we see in Venn Diagrams

• Consider the 2 sets:beatles = {'John', 'Paul', 'George', 'Ringo'}wilburys = {'Bob', 'George', 'Jeff', 'Roy', 'Tom'}

Collections

Page 68: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets: union

beatles | wilburys{'Ringo', 'Roy', 'Bob', 'John', 'Jeff', 'Paul', 'Tom', 'George'}

beatles.union(wilburys){'Ringo', 'Roy', 'Bob', 'John', 'Jeff', 'Paul', 'Tom', 'George'}

B W

Collections

Page 69: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets: intersection

beatles & wilburys{'George'}

beatles.intersection(wilburys){'George'}

Collections

Page 70: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets: difference

beatles - wilburys{'Paul', 'John', 'Ringo'}

>>> beatles.difference(wilburys){'Paul', 'John', 'Ringo'}

Collections

Page 71: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets: symmetric difference

beatles ^ wilburys{'Paul', 'Roy', 'Tom', 'Bob', 'John', 'Ringo', 'Jeff'}

beatles.symmetric_difference(wilburys){'Paul', 'Roy', 'Tom', 'Bob', 'John', 'Ringo', 'Jeff'}

Collections

Page 72: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sets: empty set

empty = set()

Collections

Page 73: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences

• Sequences in Python are an ordered list of elements and, unlike sets, may contain duplicate elements

Collections

Page 74: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: ranges• Ranges contain an ordered list of integers

• Specify stop value:range(3) 0, 1, 2

Note: does not include stop value!

• Specify start and stop:range(100, 111))100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110

• Specify start, stop and step:range(2, 10, 2)2, 3, 6, 8

Collections

Page 75: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: ranges (2)

• If you choose an end value equal or less than the start value then the range will but empty

• If you choose a negative step value, then stop will need to be less than then start:

range(3, -3, -1)-2, -1, 0, 1, 2, 3

Collections

Page 76: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Tuples

• Tuples are sequences that contain any type of element and may contain duplicates• Tuples are ordered and immutable• To create a tuple, simply specify a comma-separated list of the

elements of the tuple:my_tuple = (1, 2, 3)

Omitting the brackets will still work (tuple packing)turtles = 'Leonardo', 'Michelangelo', 'Donatello', 'Raphael'

Collections

Page 77: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Tuples (2)

• Empty tuple:nothing = ()

One element tuple needs a trailing comma:alone = ('Crusoe', )

To avoid ambiguity:ambiguous = (10 * 10) # not a tuplenot_ambiguous = (10 * 10,) # tuple

Collections

Page 78: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

as a related aside…

it is possible to assign multiple values to multiple names in a single expression using comma-separated lists:batman, robin = 'Bruce', 'Dick'

Collections

Page 79: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Tuples (3)

• There is a tuple() function:tuple('Leonardo')('L', 'e', 'o', 'n', 'a', 'r', 'd', 'o')

It separates letters, similar to the sets() function

Tuples have two methods Method Purposecount() Returns the number of times a specified value

occurs in a tuple

Index() Searches the tuple for a specified value andreturns the position of where it was found

Page 80: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 12: Sets• Exercise 13: Ranges • Exercise 14: Tuples

Collections

Page 81: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Lists

• Lists are similar to tuples since are a sequence of any type of element

• BUT are mutable

• BUT use square brackets to create a list:b = [1, 2, 3]type(b)<class 'list'>

Collections

Page 82: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Lists (2)

• Let’s replace Pete with Ringo:beatles = ['John', 'Paul', 'George', 'Pete']beatles[3] = 'Ringo'beatles['John', 'Paul', 'George', 'Ringo']

• Replacing elements in a list using another collection:temps = ('Jimmy', 'Eric')beatles[3:4] = tempsbeatles['John', 'Paul', 'George', 'Jimmy', 'Eric']

Collections

Page 83: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Lists (3)

• The are many list methods, so we can only given a brief overview of how lists can be manipulated. Anyway, here are some list methods:

beatles.reverse()beatles['Eric', 'Jimmy', 'George', 'Paul', 'John']

beatles.sort()beatles['Eric', 'George', 'Jimmy', 'John', 'Paul']

• Note that calling the method modifies the list immediately i.e. we do not :beatles = beatles.sort()

Collections

Page 84: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Sequences: Lists (4)Method Purpose

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Collections

Page 85: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Mappings• Mutable structures with “key/value” pairs• Dictionaries (dict) are the only Python mapping object• Keys unique, but contents need not be• A chest of drawers make a good analogy

Drawer A

Drawer B

Drawer C

Drawer D

Collections

Page 86: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Mappings: Dictionaries• Creating:

a_team = {'Hannibal': 'Lieutenant Colonel John Hannibal Smith’, 'Face': 'Lieutenant Templeton Arthur Peck’, 'BA': 'Sergeant Bosco Albert Baracus’, 'Murdock': 'Captain H.M. Murdock’}

• ora_team = dict((('Hannibal', 'Lieutenant Colonel John Hannibal Smith'),('Face', 'Lieutenant Templeton Arthur Peck'),('BA', 'Sergeant Bosco Albert Baracus'),('Murdock', 'Captain H.M. Murdock')))

• Retrieving:a_team['Face']'Lieutenant Templeton Arthur Peck'

• Entering a key that does not exist will result in an errora_team['Jaffo']

Traceback (most recent call last):File "<pyshell>", line 1, in <module>

KeyError: 'Jaffo' Collections

Page 87: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Mappings: Dictionaries (2)

• Add new entry:a_team['Amy'] = 'Amy Allen'

Same notation to replace existing value:a_team['Murdock'] = 'Captain Murdock'

Delete entry:del(a_team['BA’])

Collections

Page 88: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Mappings: Dictionaries (3)• Can use built in methods e.g.

a_team.get('Face')'Lieutenant Templeton Arthur Peck‘

Method Purposeclear() Removes all the elements from the dictionarycopy() Returns a copy of the dictionaryfromkeys() Returns a dictionary with the specified keys and valuesget() Returns the value of the specified keyitems() Returns a list containing a tuple for each key value pairkeys() Returns a list containing the dictionary's keyspop() Removes the element with the specified keypopitem() Removes the last inserted key-value pairsetdefault() Returns the value of the specified key. If the key does not exist: insert the

key, with the specified valueupdate() Updates the dictionary with the specified key-value pairsvalues() Returns a list of all the values in the dictionary

Collections

Page 89: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Copying collections

• Remember for primitive values:

string1 = 'A'string2 = string1string2 = 'B'

print(string1)print(string2)

>>>AB

Collections

Page 90: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Copying collections (2)

• Different for collections!list1 = ['A', 'B', 'C']list2 = list1

print(list1)print(list2)print()

list2.append('D')

print(list1)print(list2)

>>>['A', 'B', 'C']['A', 'B', 'C']

['A', 'B', 'C', 'D']['A', 'B', 'C', 'D']

Collections

Page 91: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Copying collections (3)• Use copy()methodlist1 = ['A', 'B', 'C']list2 = list1list3 = list1.copy()

print(list1)print(list2)print(list3)print()

list2.append('D')list3.append('E')print(list1)print(list2)print(list3)>>>['A', 'B', 'C']['A', 'B', 'C']['A', 'B', 'C']['A', 'B', 'C', 'D']['A', 'B', 'C', 'D']['A', 'B', 'C', 'E']

print(id(list1))print(id(list2))print(id(list3))

>>>609376406093764065185072

Collections

Page 92: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 15 – Lists

• Exercise 16 - Dictionaries

Collections

Page 93: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Streams

• Flow of data (but similar to flow of water) from source to sink

Collections

Page 94: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Streams: Files

with open('/Users/wingetts/Desktop/Poetry.txt', 'r') as anthology:print(anthology.readlines())

open – opens file specified by pathwith – optional, but ensure files closes in event of erroranthology – file objectreadlines()– method reads all lines in file (but takes arguments to specify number of lines to read)

Collections

Page 95: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Streams: Files

with open('wordless.txt', 'w') as out:out.writelines(cloud_text)

open – creates file specified by pathwith – optional, but ensure files closes in event of errorout – file objectwritelines()– method writes all lines in file

Collections

Page 96: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Streams: Generators

• A generator is an object that creates a stream of values. • Makes new values de novo as many times as is required. • Preferable to alternatives strategies e.g. keeping a very large list in

memory, and then selecting a value from the list as required• Discuss in more detail later in the course

Collections

Page 97: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

The key parameter

• Now we’ve covered collections, let’s discuss the key parameter

• Problem:managers = ['Ferguson', 'Wenger', 'de Boer', 'Ancelotti']managers.sort() #Sorts the list in placeprint(managers)>>>

['Ancelotti', 'Ferguson', 'Wenger', 'de Boer']

• That’s not quite what we wanted!

Collections

Page 98: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

The key parameter (2)

• Consider:managers = ['Ferguson', 'Wenger', 'de Boer', 'Ancelotti']managers.sort(key=len) #Sorts the list in placeprint(managers)

>>>['Wenger', 'de Boer', 'Ferguson', 'Ancelotti']

• That’s fine, but how does that help?

Collections

Page 99: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

The key parameter (3)

• Solution:def to_lowercase(my_string):

return my_string.lower()

managers = ['Ferguson', 'Wenger', 'de Boer', 'Ancelotti']managers.sort(key=to_lowercase) print(managers)

>>> ['Ancelotti', 'de Boer', 'Ferguson', 'Wenger']

Collections

Page 100: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

The key parameter (4)

• Let’s make the previous code more concise• Anonymous functions (the lambda function)• Lambda function syntax: lambda arguments : expression

managers = ['Ferguson', 'Wenger', 'de Boer', 'Ancelotti']managers.sort(key=lambda s: s.lower())

print(managers)

>>>

['Ancelotti', 'de Boer', 'Ferguson', 'Wenger']

Collections

Page 101: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

Exercise 17 – FilesExercise 18 – Lambda Function

Collections

Page 102: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Conditionals and loopsSection 5

Page 103: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Conditionals

• A central concept in computing is the capability to evaluate a particular value, or set of values, and then make a “decision” based on this input

Is it is it before midday?

Stay in bed Get up

If true If false

Conditionals and loops

Page 104: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Conditionals (2)

• See this simple conditional expression:if 1==1:

print('One is equal to one')

One is equal to one

Conditionals and loops

Page 105: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Conditionals (3)

• A one-alternative conditional:

if (2 + 2 == 5):print('Two plus two is five')

else:print('Two plus two is not equal to five')

Two plus two is not equal to five

Conditionals and loops

Page 106: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Conditionals (4)

• A multi-alternative conditional:

ball = 22

if(ball == 13):print('Unlucky for some')

elif(ball == 14):print('Lawnmower')

elif(ball == 22):print('Two little ducks!')

else:print(ball)

Two little ducks!

Conditionals and loops

Page 107: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 19 – Conditionals

Page 108: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

While Loops

while True

Do something

• Loop allow us repeat the same bloc of code, over and over• Keep looping while this is true:

Conditionals and loops

Page 109: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

While Loops (2)

• Example:x = 1 while(x < 5):

print(x)x += 1

• Infinite loop example:x = 1 while(x < 5):

print(x)

Conditionals and loops

Page 110: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

While Loops (3)• You may append an else statement to your while loop which will be executed when the loop condition

evaluates to false

x = 1 while(x < 5):

print(x)x += 1

else:print("Not less than 5")

1234Not less than 5

Conditionals and loops

Page 111: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

While Loops (4)

Previous Examplex = 1 while(x < 5):

print(x)x += 1

Breaking out of a loopx = 1 while(1):

print(x)x += 1if(x >= 5):

break

Conditionals and loops

Page 112: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

While Loops (5)

• The command continue causes the program to continue to the next loop, but importantly does not break out of the loop

• Let’s print the even numbers from 2 to 10:

x = 0

while(x < 10):x += 1

if x % 2:continue

print(x)

24

68

10

Conditionals and loops

Page 113: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

While Loops (6)

• Loops are useful to evaluate data received when reading a file:• Let’s print every 10th line:

with open(filename) as file:line = file.readline()count = 1while line:

count += 1line = file.readline()if (count % 10 == 0):

print(line)

Conditionals and loops

Page 114: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Exercises

• Exercise 20 – While Loops

Page 115: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Concluding remarks• We have covered a lot of material !

• You should now be familiar with the Python datatypes, understand concepts such as functions and methods and how programs are controlled using loops and conditional operators

• We strongly recommend that you go out of your way to find reasons to write code over the next few weeks – else you will forget!

• There is always our Advanced Python Course

• Learning Python is akin to learning a foreign language

Page 116: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

Resources

www.python.org – the homepage of Python. This should often be your first port of call for Python-related queries.

Also, don’t forget the Babraham Bioinformatics pages listing available courses and providing training materials: https://www.bioinformatics.babraham.ac.uk/training

Page 117: Introduction to Python Slides · python3 hello_world.py Names, functions and methods. Names •Names used by Python to represent numbers or characters •Assignment statement •Numbers:

How do you get to Carnegie Hall? Practice, practice, practice.

Happy coding!The Babraham Bioinformatics Team