introduction mein 50010: python - bioinf.ucd.ie addressable unit of memory ... floating point number...
TRANSCRIPT
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
MEIN 50010: Python – Introduction
Fabian Sievers
Higgins Lab, Conway Institute
University College Dublin
Wednesday, 2017-10-04
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Outline
Goals
Teach basic programming concepts
Apply these concepts using Python
Use Python Packages and libraries
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
What is Computer Programming?
Writing software
Multistep process to solve a problem• Formulate the problem
• Generate set of steps to solve problem⇒ Algorithm
• Verify Algorithm⇒ Correctness, resource requirements
• Implementation⇒ Write code in programming language
• Testing/Debugging⇒ Coverage
• Distribution/Documentation/Maintenance
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Purpose of Programming
Generate sequence of instructions that solve a problemor automate a task• Excellent practice of critical/logical thinking• Modern biology is data intensive• Everyday life is IT intensive → good skill to have
Implement in a programming language• C/C++• Java• Perl• PHP• Python• and many, many more . . .
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Python
High level language, handles grunt work• Clean, concise, unambiguous syntax• Rapid application development
Interpreted language, Open source, Flexible, Scalable
Many resources (libraries, tutorials, forums)• https://docs.python.org• https://stackoverflow.com/questions/tagged/python• http://www.diveintopython3.net/ (book)
Large communityofficial Google languageincreasing bioinfo usage...
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Interpreted vs Compiled
Python (looks like English):print("Hello World!")
C (needs to be compiled):include <stdio.h>
int main(int argc, char *argv[]){
printf("Hello World!\n");
return 0;
}
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Low Level Language
Assembly (what the computer likes):.model tiny
.data
message db ’Hello, World!’
.code
org 100h
start:
mov ah,9
mov dx,offset message
int 21h
ret
end start
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
A Bit about Bits
There are 10 kinds of peopleThose who understand binaryAnd those who don’t
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
What is a Bit?
Computer microprocessor (CPU) composed of manyswitches called bits
Two configurations for a switch• ’on’ or ’off’• ’true’ or ’false’• ’0’ or ’1’
Combine/manipulate bits with Boolean algebra• and ∧, or ∨, not ¬• build up other operations with these
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
What is a Byte?Usually, 1 Byte = 8 bits
Smallest addressable unit of memoryRepresent integers (base 10) by their powers of 2• 010 = 000000002 →
0×27+0×26+0×25+0×24+0×23+0×22+0×21+0×20
• 110 = 000000012 →0×128+0×64+0×32+0×16+0×8+0×4+0×2+1×1
• 210 = 000000102 →0×128+0×64+0×32+0×16+0×8+0×4+1×2+0×1
• 310 = 000000112 →0×128+0×64+0×32+0×16+0×8+0×4+1×2+1×1
•...
• 25510 = 111111112 →1×128+1×64+1×32+1×16+1×8+1×4+1×2+1×1
Floating Point Number• binary expansion of 0.1 doesn’t terminate, same as
decimal expansion of 1/3 (0.333 . . .)0.110 = 0/2 + 0/4 + 0/8 + 1/16 + 1/32 + 0/64 +0/128 + 1/256 + 1/512 . . .10 = 0.000110011 . . .2
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Variables
A Variable is an object that stores data which canchange
Program can’t do anything useful without variablescan only do one thing, no flexibility
Declare it (name it)• name refers to location in memory• name can be whatever you like (should be descriptive,
reflect scope, conform to local standards)• in Python name must begin with letter• in Python name cannot be reserved (key) word
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Data Types
integer: number of sheep = 39
maximum value (depending on platform)231 − 1 = 2, 147, 483, 647 (32-bit) or263 − 1 ≈ 9.2× 1018 (64-bit)
float: weight = 75.4
maximum value ≈ 1.8× 10308
Boolean: Answer = False
complex: phase = 3+2j
String: greeting = ’Hello World!’
a sequence of characters surrounded by (single, doubleor triple) quotes
Collection of variablesList: elements = [’H’, ’He’, ’Li’, ’Be’]
Dictionary: GerEng = {’Hund’:’dog’,
’Katze’:’cat’}
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Dynamic Typing
Python uses dynamic typing model for variables
• Variables don’t need to be declared in advance• Variables don’t have a type associated with them,
values do>>>x = 2 # x refers to an integer>>>x = ’Hello’ # now x refers to a string>>>x = True # and now to a Boolean
Python uses strong dynamic typing• Applying operations to incompatible types is not
permitted>>>1 + ’hello’
Traceback (most recent call last):
File ‘‘<stdin>’’, line 1, in <module>
TypeError: unsupported operand type(s) for
+: ’int’ and ’str’
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Basic Operators
Can’t do anything with varibles unless we haveoperators
Operators are tokens which carry out ’operations’ ondata/variables
Assign a value with the assignment operator ’=’a=5
Mathematical operators+ - * / ** % //
Comparison operators== != > < >= <=
String operatorsconcatenate +, repeat *, slice [:]
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Basic Operators
Addition: +
>>>2+3 ⇒ 5
Subtraction: -
>>>2-3 ⇒ -1
Multiplication: * (asterisk)>>>2*3 ⇒ 6
Division: /
>>>2/3 ⇒ 0.6666666666666666
Exponent: **
>>>2**3 ⇒ 8
>>>2**0.5 ⇒ 1.4142135623730951
Modulo: % (remainder)>>>14%4 ⇒ 2 (14 = 3 * 4 + 2)
Integer Division: //
>>>14//4 ⇒ 3 (14 = 3 * 4 + 2)
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Boolean Expressions
Equal to: == (note double-equal sign)>>>2 == 3 ⇒ False
>>>3 == 3 ⇒ True
Not equal to: !=
>>>2 != 3 ⇒ True
>>>3 != 3 ⇒ False
Less than: <
>>>2 < 3 ⇒ True
>>>3 < 3 ⇒ False
Less than or equal: <=
>>>2 <= 3 ⇒ True
>>>3 <= 3 ⇒ True
>>>4 <= 3 ⇒ False
Greater / Greater or equal: > / >=
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Boolean Expressions
Test multiple conditions with and
Only true if both conditions met>>>(1 < 2) and (3 < 4) ⇒ True
>>>(1 < 2) and (3 < 3) ⇒ False
Test multiple conditions with or
True if either condition met>>>(1 < 2) or (3 < 3) ⇒ True
>>>(1 > 2) or (3 > 4) ⇒ False
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Operator precedence
In mathematics multiplication before addition1 + 2× 3 = 1 + (2× 3) = 7 6= (1 + 2)× 3 = 9
Same precedence in Python (and other languages)
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Functions
A function performs specific task on data stored invariable
Main purpose of this course is to learn how to writeyour own functions
Python has ’built-in’ functions
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Functions
abs(x) – Return the absolute value of a number
bin(x) – Convert an integer number to a binary string
input([prompt]) – Write prompt to standard output,then read a line from input
len(s) – Return the length (the number of items) ofan object
open(file, mode) – Open file and return file object
print(objects, file) – Print objects to the textstream file...
Sometimes you will see object.method(arg), e.g.,’Hello World’.find(’W’) – essentially same asfunction
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Counting
Computer scientists use zero based counting>>>’Hello World’.find(’H’)
0
Slice index goes from start index up to but notincluding end index>>>’Hello World’[1:4]
’ell’
>>>’Hello World’[:4]
’Hell’
>>>’Hello World’[7:]
’orld’
Slice from end using negative index>>>’Hello World’[-1]
’d’
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Using Python
Python can be used in 2 ways:
Interactive Python Interpreter• Write-as-you-go mode, useful for learning and testing
small programs• Typed statements are evaluated immediately
Write and run script files• Create script file with list of Python commands• Use plain text editor to create/modify script• Contents of script are evaluated line by line as script is
run
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
The Python InterpreterStarting the Python Interpreter
Linux/Unix• Open terminal window (gnome, konsole, xterm) and
type python3
Mac OSX• Open terminal and type python3
Windows• From Start Menu search for cmd• Type python
We are using Python 3 not 2.6/2.7
Line starting with >>> (or ...) are printed by interpreter
Line not starting with >>> is output
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Using Python interactively
Exit interpreter with quit()
alternatively• Mac/Linux: Control-D• Windows: Control-Z followed by return
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Using Python ScriptsSecond way to use PythonCreate script file with list of Python commandsUse plain text editor to create file• Linux: GEdit, Emacs, Vi, . . .• Mac OSX: TextEdit, TextWrangler, Vi, . . .• Windows: Notepad++• Python inbuilt: IDLE
• Windows: All Programs → Python3.X → IDLE• IDLE displays Python interpreter window• to begin script, choose menu File → New Window• start typing script, when done, menue File → Save• to execute, choose menu Run → Run Module• output written to interpreter window
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Python + Command Prompt
Python scripts can be run from Windows commandprompt
Select Programs → Accessories → Command Prompt(or search for cmd)
You may need to tell Wndows where to find PythonC:\> set path=%path%;C:\Python34
Change to directory containing your Python scriptC:\> cd mein50010
Run script by passing filename as argumentC:\mein50010\> python hello.py
Mac & Linux work similarly
MEIN 50010
Introduction
Variables
Operators
Functions
Indexing
Interpreter
Scripts
Credits
Credits
Interpreted vs Compiled figure – Peadar O’Gaora lectureGENE 30040
Assembly version ’Hello World’ –www.codecodex.com/wiki/Hello world
Python keywords –docs.python.org/3/reference/lexical analysis.html
Operator precedence –docs.python.org/3/reference/expressions.html
Built-in functions –docs.python.org/3/library/functions.html
Truth table – en.wikipedia.org/wiki/Boolean algebra
Colm Ryan – COMP50050