an introduction to python – part ii dr. nancy warter-perez

26
An Introduction to Python – Part II Dr. Nancy Warter-Perez

Post on 18-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: An Introduction to Python – Part II Dr. Nancy Warter-Perez

An Introduction to Python – Part II

Dr. Nancy Warter-Perez

Page 2: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 2

Overview Data Organization

Lists Tuples Dictionaries

Input/Output Programming Workshop #1 If tests Loops

for while

Example amino acid search program Programming Workshop #2

Page 3: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 3

Enclosed in single or double quotesEx: ‘Hello!’ , “Hello!”, “3.5”, “a”, ‘a’

Sequence of characters:mystring=“hello world!”

mystring[0] -> “h” mystring[1] -> “e”

mystring[2] -> “l” mystring[-1] -> “!”

Strings

-1 is last,

-2 next to last, etc…

Page 4: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 4

String operations

mystring = “Hello World!”

Expression Value Purposelen(mystring) 12 number of characters in

mystring

“hello”+“world” “helloworld” Concatenate strings

“%s world”%“hello” “hello world” Format strings (like sprintf)

“world” == “hello”

“world” == “world”

0 or False

1 or True

Test for equality

“a” < “b”

“b” < “a”

1 or True

0 or False

Alphabetical ordering

Page 5: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 5

Strings (2) slicing:mystring = “spoon!”

mystring[2:] -> “oon!”mystring[:3] -> “spo” #note last element is never included!

mystring[1:3]-> “po” Many useful built-in functions

mystring.upper() -> “SPOON!” mystring.replace(‘o’, ‘O’) -> “spOOn!”

Page 6: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 6

Strings (3) “%” operator:

sort of “fill in the blanks” operation:mystring=“%s has %d marbles” % (“John”,35)

mystring -> “John has 35 marbles”

%s replace with string %d,%i replace with integer %f replace with float

Values to put in blanks

“blanks”

Page 7: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 7

Lists

mylist=[“a”,”b”,3.58,”d”,4,0]mylist[0]mylist[2]

a3.58

Indexing

mylist[-1]mylist[-2]

04

Negative indexing (counts from end)

mylist[1:4] [“b”,3.58,”d”] Slicing (like strings)

“b” in mylist“e” not in mylist

1 or True1 or True

mylist.append(8) [“a”,”b”,3.58,”d”,4,0,8]

Add to end of list

Page 8: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 8

Tuples Tuples – sequence of values

like lists, but cannot be changed after it is createdmytuple=(1,”a”,”bc”,3,87.2)mytuple[2] -> “bc”

mytuple[1]=“3” Used when you want to pass several

variables around at once

Error!

Page 9: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 9

Dictionaries Dictionaries – map ‘keys’ to ‘values’

like lists, but indices can be of any type Also, keys are in no particular order Eg:mydict={‘b’:3, ’a’:4, 75:2.85}mydict[‘b’] -> 3mydict[75] -> 2.85mydict[‘a’] -> 4

Page 10: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 10

Dictionaries

mydict={“r”:1,”g”:2,”y”:3.5,8.5:8,9:”nine”}mydict.keys() ['y', 8.5, 'r', 'g', 9] List of the keys

mydict.values() [3.5, 8, 1, 2, 'nine'] List of the values

mydict[“y”] 3.5 Value lookup

mydict.has_key(“r”) True or 1 Check for keys

mydict.update({“a”:75})

{8.5: 8, 'a': 75, 'r': 1, 'g': 2, 'y': 3.5, 9: 'nine'}

Add pairs to dictionary

Page 11: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 11

Dictionaries – other considerations Slicing not allowed Referencing invalid key is an error:>>> mydict={8.5: 8, 'a': 75, 'r': 1, 'g': 2, 'y':

3.5, 9: 'nine'}>>> mydict["red"]Traceback (most recent call last):

File "<interactive input>", line 1, in ?KeyError: 'red‘

Use mydict.get(“red”) instead, it returns None if key is not found

Page 12: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 12

Input/Output Function raw_input() designed to read a line of

input from the user 1 optional argument: string to prompt user If int or float desired, simply convert string:

int(mystring)->convert to int (if possible)

float(mystring)->convert to float (if possible)

>>> mystr=raw_input("Enter a string:")Enter a string:Hello World!>>> mystr'Hello World!'

Page 13: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 13

Output Function print

Prints each argument, followed by space

After all arguments, prints newline

Put comma after last arg to prevent newline

“add” strings to avoid spaces

print “a”,”b”,”c”a b c

print “a”,”b”,”c”,a b c

print “a”+”b”+”c”abc

Newline!

No Newline!

No spaces!

Page 14: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 14

Output Example>>> print "hello","world";print "hello","again"

hello world

hello again

>>> print "hello","world",;print "hello","again"

hello world hello again

>>> print "hello %s world" % "cold and cruel"

hello cold and cruel world

>>> print "hello","cold"+ " " + "and","cruel","world"

hello cold and cruel world

Page 15: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 15

Programming Workshop #1

Write a Python program to compute the hydrophobicity of an amino acid

Program will prompt the user for an amino acid and will display the hydrophobicity

Page 16: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 16

Solution to Programming Workshop 1 Write a Python program to compute the hydrophobicity of

an amino acid# Program to compute the hydrophobicity of an amino acid# (solution only includes first 3 amino acids)# Written by: Prof. Warter-Perez# Date created: April 15, 2004# Last modified:

hydro = {"A":1.8,"C":2.5,"D":-3.5}aa = raw_input ("Please enter amino acid: ")print "The hydrophobicity of %s is %f."% (aa, hydro[aa])

Page 17: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 17

Make solution case insensitive

# Program to compute the hydrophobicity of an amino acid

# Written by: Prof. Warter-Perez

# Date created: April 15, 2004

# Last modified: April 20, 2004 - made script case insensitive for

# amino acids

hydro = {"A":1.8,"C":2.5,"D":-3.5}

aa = raw_input ("Please enter amino acid: ")

aa = aa.upper()

print "The hydrophobicity of %s is %f."% (aa, hydro[aa])

Page 18: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 18

Python Basics – Relational and Logical Operators

Relational operators== equal!= not equal>greater than>= greater

than or equal

<less than<= less than or

equal

Logical operatorsand andor ornot not

Page 19: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 19

if Statement if expression:

actionExample:

a1 = 'A‘; a2 = 'C';match = 0;if (a1 == a2) :

match+=1;

Page 20: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 20

if-elif-else Statement if expression:

action 1elif expression:

action 2else :

action 3

Example:a1 = 'A‘; a2 = 'C';match = 0; gap = 0;if (a1 == a2) :

match+=1;elif (a1 > a2):

else:gap+=1;

Page 21: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 21

for Statementfor var in list:

action Sets var to each item

in list and performs action

range() function generates lists of numbers: range (5) -> [0,1,2,3,4]

Examplemylist=[“hello”,”hi”,”hey”

,”!”];for i in mylist:

print i

Iteration 1 prints: hello

Iteration 2 prints: hi

Iteration 3 prints: hey

Iteration 4 prints: !

Page 22: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 22

while Statement

while expression:action

Examplex = 0;while x != 3:

x = x + 1

Iteration 1: x=0+1=1Iteration 2: x=1+1=2Iteration 3: x=2+1=3Iteration 4: don’t exec

/ 2Infinite loop!

Page 23: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 23

Example: Amino Acid Search Write a program to count the number

of occurrences of an amino acid in a sequence. The program should prompt the user for

A sequence of amino acids (seq) The search amino acid (aa)

The program should display the number of times the search amino acid (aa) occurred in the sequence (seq)

Page 24: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 24

Example: Amino Acid Search (2)#this program will calculate the number of occurrences of an amino acid in a

#sequence

#by Bryce Ready

done=0

while (not done):

sequence=raw_input("Please enter a sequence:");

aa=raw_input("Please enter the amino acid to look for:");

Page 25: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 25

Example: Amino Acid Search (3) #compute the number of occurrences using for loop

cnt=0

for i in sequence:

if i == aa:

cnt+=1

if cnt == 1:

print "%s occurs in that sequence once" % aa

else:

print "%s occurs in that sequence %d times" % (aa, cnt)

answer=raw_input("try again? [yn]")

if answer == "n" or answer == "N":

done = 1

Page 26: An Introduction to Python – Part II Dr. Nancy Warter-Perez

Introduction to Python – Part II 26

Programming Workshop #2

Write a sliding window program to compute the %GC in a sequence of nucleotides. The program should prompt the user for

The DNA sequence The window size (assume the window increment is 1)