Introduction to Python September 26, 2011. 10/10/2015 2 Bioinformatics Languages Low-level, compiled languages: C, C++, Java… Pros: performance Cons:

Slides:



Advertisements
Similar presentations
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Advertisements

Container Types in Python
Python Basics: Statements Expressions Loops Strings Functions.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Python By Steve Wright. What is Python? Simple, powerful, GP scripting language Simple, powerful, GP scripting language Object oriented Object oriented.
Perl Basics A Perl Tutorial NLP Course What is Perl?  Practical Extraction and Report Language  Interpreted Language Optimized for String Manipulation.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Lists in Python.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
H3D API Training  Part 3.1: Python – Quick overview.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
If statements while loop for loop
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Python – May 12 Recap lab Chapter 2 –operators –Strings –Lists –Control structures.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
Python 1 SIGCS 1 Intro to Python March 7, 2012 Presented by Pamela A Moore & Zenia C Bahorski 1.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Python Lists and Sequences Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark List properties What are lists? A list is a mutable.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
String and Lists Dr. José M. Reyes Álamo.
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
Introduction to Python
Containers and Lists CIS 40 – Introduction to Programming in Python
Variables, Expressions, and IO
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Strings Part 1 Taken from notes by Dr. Neil Moore
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Introduction to Python
An Introduction to Python
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CS190/295 Programming in Python for Life Sciences: Lecture 6
String and Lists Dr. José M. Reyes Álamo.
Introduction to Computer Science
Class code for pythonroom.com cchsp2cs
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Introduction to Python September 26, 2011

10/10/ Bioinformatics Languages Low-level, compiled languages: C, C++, Java… Pros: performance Cons: slower programming (harder to both write &read) Statistical languages: R, MATLAB, Octave… Pros: many functions are provided. Cons: limited applicability to non-statistical problems (and some major ones are non-free). Scripting languages: Python, Perl, Ruby... Pros: fast programming. Python is easy to read. Cons: slower run times and larger memory footprint (sometimes by orders of magnitude).

10/10/ Python Started in Currently in version 2.7/3.3 More than most languages – very readable & clear "There should be one – and preferably only one – obvious way to do it." Like most scripting languages: Interpreted Garbage Collected (no need for memory management) High memory usage (wasteful)

10/10/ for x in [0,1,2,3,4]: 2 result = x**2 – 5 3 print result Printing and Loops Suppose we want to evaluate the expression x 2 – 5 for the integers 0 through A built-in Python function. Evaluates to a list of integers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] A Python keyword indicating a loop. Other option for loops is while. Four spaces. In Python, whitespace matters. Shows block structure. A Python list. Like an array in other languages. Indicated by the brackets. Colon shows beginning of block. Single equals sign assigns value to variable A built-in function. Prints to stdout.

10/10/ Running Python Interactively Start the Python interpreter: $ python Enter commands at >>> prompt.

10/10/ A Python Program Structure of a program:

10/10/ A Python Program Write program in editor of your choice. There are many options See

10/10/ def little_function(n): 2 return n**2 – 5 1 for x in [0,1,2,3,4]: 2 result = little_function(x) 3 print result Declaring a function Suppose our goal is similar, but we want to separate the details of the calculation into a function. A Python keyword indicating a new function. The name of the function. A Python keyword indicating the vale to return. We replace our previous expression with a function call. The parameters to the function.

10/10/ Modules and Imports Now suppose instead of finding x 2 -5, we want to find log(x) Python has “batteries included”, meaning it has a broad standard library 1 import math 1 def little_function(n): 2 return math.log(n) 1 for x in [0,1,2,3,4]: 2 result = little_function(x) 3 print result Python keyword at beginning of file to make a module available. The name of the module to import. In this case, we're using math. Other common standard library modules include sys, os, re, datetime, and zlib. Dot is member access/ scope operator in Python

10/10/ Conditional Statements Python uses if/elif/else Suppose we want to print “Less than zero.” or “Zero.” rathen than the value. 1 import math 2 def little_function(n): 3 return math.log(n) 4 for x in [0,1,2,3,4]: 5 result = little_function(x) 6 if result < 0: 7 print “Less than zero.” 8 elif result == 0: 9 print “Zero.” 10 else: 11 print result If blocks use same colon and indent rules as for loops. Elif and else are optional. Double equals tests for equality.

10/10/ Modules and Imports Now suppose instead of finding x 2 -5, we want to find log(x) Python has “batteries included”, meaning it has a broad standard library 1 import math 1 def little_function(n): 2 return math.log(n) 1 for x in [0,1,2,3,4]: 2 result = little_function(x) 3 print result Python keyword at beginning of file to make a module available. The name of the module to import. In this case, we're using math. Other common standard library modules include sys, os, re, datetime, and zlib. Dot is member access/ scope operator in Python

10/10/ Strings 1 s = 'Hello' 2 print s[0] 3 print s[4] 4 print s[-1] 5 print s[1:3] 6 print s[2:] 7 print s[:3] 8 print s[::2] 9 print s[::-1] 10 print len(s) Single or double quotes denote a string Brackets access characters of the string by index: “Slices” can be taken with indices separated by a colon Third term in slice determines step size. 'H' 'o' 'el' 'llo' 'Hel' 'Hlo' 'olleH' 5 len() gives length of string.

10/10/ String Methods s.lower(), s.upper() -- returns the lowercase or uppercase version of the string s.strip() -- returns a string with whitespace removed from the start and end s.isalpha()/s.isdigit()/s.isspace() tests if all the string chars are in the various character classes s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new' s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars. s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

10/10/ Practice Write a function that takes a string and returns another string consisting of the first two and last two characters of the input string. If the input string has fewer than two characters, return an empty string. Write a function that takes two strings and returns the number of times the second string appears in the first.

10/10/ Lists Lists in Python are similar to arrays in other languages 1 z = [17,19, 23, 29, 31] 2 print z[0] 3 print z[4] 4 print z[-1] 5 print z[-3] 6 print z[1:3] 7 print z[2:] 8 print z[:3] 9 print z[::-1] 10 print range(5) Square brackets indicate list. Brackets also access elements in the list. Note they are 0-indexed. Negative index starts from end. Colon inidicates “slice” from list. Idiom for reversing a list [19, 23] [23, 29, 31] [17, 19, 23] [31, 29, 23, 19, 17] [0, 1, 2, 3, 4] range(n) return a list of integers

10/10/ List Methods list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right. list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError). list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present) list.sort() -- sorts the list in place (does not return it). (The sorted() function shown below is preferred.) list.reverse() -- reverses the list in place (does not return it) list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

10/10/ Practice Write a function that takes a list of strings, return a list with the strings in sorted order, except group all the strings that begin with 'x' first. Write a function that takes a list of numbers and returns a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3].

10/10/ Dictionaries Python's key/value hash table is called a dictionary 1 d = {} 2 d['a'] = 'alpha' 3 d['g'] = 'gamma' 4 print d['a'] 5 print d['z'] 6 if 'z' in d: 7 print d['z'] 8 print d.keys() 9 print d.values() 10 print d.items() Curly braces indicate a dictionary Associate keys with values Retrieve values associated with keys 'alpha' KeyError Check if key in dictionary. ['a', 'g'] ['alpha', 'gamma'] [('a', 'alpha'), ('g', 'gamma')]

10/10/ Files 1 f = open('file.txt', 'r') 2 outf = open('output.txt', 'w') 3 for line in f: 4 print line 5 outf.write(line) 6 f.close() 7 outf.close() 8 wholefile = file('file.txt').read() 9 oneline = file('file.txt').readline() Files in Python are generally handled line by line open returns a file object The second argument to open sets the mode. 'r' means read, 'w' means write. Note the write mode completely overwrites an existing file. You can iterate through lines in a file using a for loop. The write method of a file object in write mode writes a string to the file. You can use the shorter file(filename) syntax to get a file object in read mode. The read method with no arguments returns the contents of the whole file. The readline() method returns a single line from a file object.

10/10/ Command Line Arguments The sys module has a list called argv that contains the arguments used at the command line. 1 import sys 2 3 def main(word_to_print): 4 print word_to_print 1 if __name__ == '__main__': 2 print sys.argv 3 main(sys.argv[1]) ['scriptname.py', 'argument1', 'argument2',...] Here select the second element of the list since we don't care about the name of the script.

10/10/ Practice Sequencing data comes in files in the FASTQ format: Write a program that reads a FASTQ file and writes only the reversed sequences to another file. The names of in input and output files should be passed as command line GATTTGGGGTTCAAAGCAGTATCGATCAAATAGTAAATCCATTTGTTCAACTCACAGTTT + AGTGCGGGAAATATCACCGTACATTCATCGCCCCCCTGAACAATACCCATAGATCACTT + !''*((((***+))%%++)(%%).1***-+*''))**55CCF>>>>>>CCCCCCC65...

10/10/ Getting Help Python has an online tutorial and reference at The “help” command gives help in interactive mode: Google “python” + your question For windows users: -on-xp-7-minutes-to-hello-world/ help(len) len(...) len(object) -> integer Return the number of items of a sequence or mapping.