: Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-04
Outline Goals Teach basic programming concepts Apply these concepts using Python Use Python Packages and libraries
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
Purpose of Programming Generate sequence of instructions that solve a problem or 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...
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 community official Google language increasing bioinfo usage.
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; }
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
A Bit about Bits There are 10 kinds of people Those who understand binary And those who don t
What is a Bit? Computer microprocessor (CPU) composed of many switches 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
What is a Byte? Usually, 1 Byte = 8 bits Smallest addressable unit of memory Represent integers (base 10) by their powers of 2 0 10 = 00000000 2 0 2 7 +0 2 6 +0 2 5 +0 2 4 +0 2 3 +0 2 2 +0 2 1 +0 2 0 1 10 = 00000001 2 0 128+0 64+0 32+0 16+0 8+0 4+0 2+1 1 2 10 = 00000010 2 0 128+0 64+0 32+0 16+0 8+0 4+1 2+0 1 3 10 = 00000011 2 0 128+0 64+0 32+0 16+0 8+0 4+1 2+1 1. 255 10 = 11111111 2 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.1 10 = 0/2 + 0/4 + 0/8 + 1/16 + 1/32 + 0/64 + 0/128 + 1/256 + 1/512... 10 = 0.000110011... 2
A Variable is an object that stores data which can change Program can t do anything useful without variables can 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
Data Types integer: number of sheep = 39 maximum value (depending on platform) 2 31 1 = 2, 147, 483, 647 (32-bit) or 2 63 1 9.2 10 18 (64-bit) float: weight = 75.4 maximum value 1.8 10 308 Boolean: Answer = False complex: phase = 3+2j String: greeting = Hello World! a sequence of characters surrounded by (single, double or triple) quotes Collection of variables List: elements = [ H, He, Li, Be ] Dictionary: GerEng = { Hund : dog, Katze : cat }
Dynamic Typing Python uses dynamic typing model for variables don t need to be declared in advance 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
Basic Can t do anything with varibles unless we have operators are tokens which carry out operations on data/variables Assign a value with the assignment operator = a=5 Mathematical operators + - * / ** % // Comparison operators ==!= > < >= <= String operators concatenate +, repeat *, slice [:]
Basic 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)
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: > / >=
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
Operator precedence In mathematics multiplication before addition 1 + 2 3 = 1 + (2 3) = 7 (1 + 2) 3 = 9 Same precedence in Python (and other languages)
A function performs specific task on data stored in variable Main purpose of this course is to learn how to write your own functions Python has built-in 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) of an object open(file, mode) Open file and return file object print(objects, file) Print objects to the text stream file. Sometimes you will see object.method(arg), e.g., Hello World.find( W ) essentially same as function
Counting Computer scientists use zero based counting >>> Hello World.find( H ) 0 Slice index goes from start index up to but not including 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
Using Python Python can be used in 2 ways: Interactive Python 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
The Python Starting the Python 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
Using Python interactively Exit interpreter with quit() alternatively Mac/Linux: Control-D Windows: Control-Z followed by return
Using Python Second way to use Python Create script file with list of Python commands Use 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
Python + Command Prompt Python scripts can be run from Windows command prompt Select Programs Accessories Command Prompt (or search for cmd) You may need to tell Wndows where to find Python C:\> set path=%path%;c:\python34 Change to directory containing your Python script C:\> cd mein50010 Run script by passing filename as argument C:\mein50010\> python hello.py Mac & Linux work similarly
Interpreted vs Compiled figure Peadar O Gaora lecture GENE 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