Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

Similar documents
Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Decisions, Decisions. Testing, testing C H A P T E R 7

Programming with Python

Python for Non-programmers

Text Input and Conditionals

Flow Control: Branches and loops

TUPLES AND RECURSIVE LISTS 5

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Exercise 6 - Addressing a Message

Introduction to Python (All the Basic Stuff)

CS1 Lecture 3 Jan. 22, 2018

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Testing. UW CSE 160 Winter 2016

Lecture Transcript While and Do While Statements in C++

An Introduction to Python

Unit E Step-by-Step: Programming with Python

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

CS1 Lecture 3 Jan. 18, 2019

4.2 Function definitions the basics

Lab 7: OCaml 12:00 PM, Oct 22, 2017

6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

7. (2 pts) str( str( b ) ) str '4' will not compile (single, double, or triple quotes

The Big Python Guide

PROGRAMMING FUNDAMENTALS

Eulerian Tours and Fleury s Algorithm

BCH339N Systems Biology/Bioinformatics Spring 2018 Marcotte A Python programming primer

If Statements, For Loops, Functions

CMSC 201 Computer Science I for Majors

Introduction to Bioinformatics

Downloaded from Chapter 2. Functions

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

CS 1110 Prelim 1 October 4th, 2012

CMSC 201 Spring 2017 Lab 12 Recursion

APPM 2460 Matlab Basics

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Final thoughts on functions F E B 2 5 T H

9.2 Linux Essentials Exam Objectives

Lecture 3. Strings, Functions, & Modules

Python for Non-programmers

Introduction to: Computers & Programming: Review prior to 1 st Midterm

COMP 364: Functions II

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Invent Your Own Computer Games with Python

Quiz. Introduction: Python. In this project, you ll make a quiz game to challenge your friends. Activity Checklist.

Using IDLE for

Lab 4 Fruitful Functions

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CMSC 201 Spring 2019 Lab 06 Lists

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

Com S 127x - Lab 6 1. READING FLOWCHARTS WITH CONDITIONAL ACTIONS!

Intro. Scheme Basics. scm> 5 5. scm>

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

The Mathcad Workspace 7

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Python a modern scripting PL. Python

S206E Lecture 19, 5/24/2016, Python an overview

Conditional Expressions and Decision Statements

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

61A Lecture 2. Friday, August 28, 2015

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

61A Lecture 2. Wednesday, September 4, 2013

Introduction to Programming in Python (2)

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

How Do Robots Find Their Way?

Python lab session 1

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

YCL Session 4 Lesson Plan

Intermediate Excel 2013

Name & Recitation Section:

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Your First Windows Form

Math Day 2 Programming: How to make computers do math for you

Errors. And How to Handle Them

Python 1: Intro! Max Dougherty Andrew Schmitt

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Section 0.3 The Order of Operations

CMSC 341 Lecture 7 Lists

In this project, you ll learn how to create your own webpage to tell a story, joke or poem. Think about the story you want to tell.

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

CSC148H Week 3. Sadia Sharmin. May 24, /20

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Get comfortable using computers

MIT AITI Python Software Development

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Key Differences Between Python and Java

Variables, expressions and statements

CMSC 201 Fall 2018 Lab 04 While Loops

The Dynamic Typing Interlude

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

Python: common syntax

Exception Handling. Genome 559

roboturtle Documentation

CS1 Lecture 4 Jan. 23, 2019

QWEST VOICE MAIL INSTRUCTION GUIDE EASY ACCESS. Just press * from your home phone to get your messages! David, Qwest Sales Consultant

Transcription:

Functions

Built-in functions You ve used several functions already len("atggtca") 7 abs(-6) 6 float("3.1415") 3.1415000000000002

What are functions? A function is a code block with a name def hello(): print "Hello, how are you?" hello() Hello, how are you?

Functions start with def def hello(): print "Hello, how are you?" hello() Hello, how are you?

Then the name This function is named hello def hello(): print "Hello, how are you?" hello() Hello, how are you?

The list of parameters The parameters are always listed in parenthesis. There are no parameters in this function so the parameter list is empty. def hello(): print "Hello, how are you?" hello() Hello, how are you? (I ll cover parameters in more detail soon)

A colon A function definition starts a new code block. The definition line must end with a colon (the : ) Just like the if, and for statements. def hello(): print "Hello, how are you?" hello() Hello, how are you?

The code block These are the statements that are run when the function is called. They can be any Python statement (print, assignment, if, for, open, ) def hello(): print "Hello, how are you?" hello() Hello, how are you?

Calling the function When you call a function you ask Python to execute the statements in the code block for that function. def hello(): print "Hello, how are you?" hello() Hello, how are you?

Which function to call? Start with the name of the function. In this case the name is hello def hello(): print "Hello, how are you?" hello() Hello, how are you?

List any parameters The parameters are always listed in parenthesis. There are no parameters for this function so the parameter list is empty. def hello(): print "Hello, how are you?" hello() Hello, how are you?

And the function runs def hello(): print "Hello, how are you?" hello() Hello, how are you?

Arguments and Parameters (Two sides of the same idea) Most of the time you don t want the function to do the same thing over and over. You want it to run the same algorithm using different data.

Hello, <insert name here> Say Hello followed by the person s name In maths we say the function is parameterized by the person s name def hello(name): print "Hello", name hello("andrew") Hello Andrew

Change the function definition The function now takes one parameter. When the function is called this parameter will be accessible using the variable named name def hello(name): print "Hello", name hello("andrew") Hello Andrew

Calling the function The function call now needs one argument. Here I ll use the string Andrew. def hello(name): print "Hello", name hello("andrew") Hello Andrew

And the function runs The function call assigns the string Andrew to the variable name then does the statements in the code block def hello(name): print "Hello", name hello("andrew") Hello Andrew

Multiple parameters Here s a function which takes two parameters and subtracts the second from the first. Two parameters in the definition def subtract(x, y): print x-y subtract(8, 5) 3 Two parameters in the call

Returning values Rarely do functions only print. More often the function does something and the results of that are used by something else. For example, len computes the length of a string or list then returns that value to the caller.

subtract doesn t return anything By default, a function returns the special value None def subtract(x, y): print x-y x = subtract(8, 5) 3 print x None

The return statement The return statement tells Python to exit the function and return a given object. def subtract(x, y): return x-y x = subtract(8, 5) print x 3 You can return anything (list, string, number, dictionary, even a function).

Making a function Yes, we re going to count letters again. A solution yesterday s #1 (except for the raw_input) seq = "ATGCATGATGCATGAAAGGTCG" counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 for base in counts: print base, =, counts[base]

Identify the function I m going to make a function which counts bases. What s the best part to turn into a function? seq = "ATGCATGATGCATGAAAGGTCG" counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 for base in counts: print base, =, counts[base]

Identify the input In this example the sequence can change. That makes seq a good choice as a parameter. seq = "ATGCATGATGCATGAAAGGTCG" counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 for base in counts: print base, =, counts[base]

Identify the algorithm This is the part of your program which does something. seq = "ATGCATGATGCATGAAAGGTCG" counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 for base in counts: print base, =, counts[base]

Identify the output The output will use the data computed by your function seq = "ATGCATGATGCATGAAAGGTCG" counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 for base in counts: print base, =, counts[base]

Identify the return value which helps you identify the return value seq = "ATGCATGATGCATGAAAGGTCG" counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 for base in counts: print base, =, counts[base]

Name the function First, come up with a good name for your function. It should be descriptive so that when you or someone else sees the name then they have an idea of what it does. Good names count_bases count_letters countbases Bad names do_count count_bases_in_sequence CoUnTbAsEs QPXT

Start with the def line The function definition starts with a def def count_bases(seq): It is named count_bases It takes one parameter, which will be accessed using the variable named seq Remember, the def line ends with a colon

Add the code block def count_bases(seq): counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1

Return the results def count_bases(seq): counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 return counts

Use the function def count_bases(seq): counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 return counts input_seq = ATGCATGATGCATGAAAGGTCG results = count_bases(input_seq) for base in results: print base, =, counts[base]

Use the function def count_bases(seq): counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 return counts input_seq = ATGCATGATGCATGAAAGGTCG results = count_bases(input_seq) for base in results: print base, =, counts[base] Notice that the variables for the parameters and the return value don t need to be the same

Interactively def count_bases(seq): counts = {} for base in seq: if base not in counts: counts[base] = 1 else: counts[base] = counts[base] + 1 return counts (I don t even need a variable name - just use the values directly.) count_bases("atatc") {'A': 2, 'C': 1, 'T': 2} count_bases("atatcqgac") {'A': 3, 'Q': 1, 'C': 2, 'T': 2, 'G': 1} count_bases("") {}

Functions can call functions def gc_content(seq): counts = count_bases(seq) return (counts["g"] + counts["c"]) / float(len(seq)) gc_content("cgaatt") 0.333333333333

Functions can be used (almost) anywhere In an if statement def polya_tail(seq): if seq.endswith("aaaaaa"): return True else: return False if polya_tail("atgctgtcgatgaaaaaaa"): print "Has a poly-a tail" Has a poly-a tail

Functions can be used (almost) anywhere In an for statement def split_into_codons(seq): codons = [] for i in range(0, len(seq)-len(seq)%3, 3): codons.append(seq[i:i+3]) return codons for codon in split_into_codons("atgcatgcatgcatgcatgc"): print "Codon", codon Codon ATG Codon CAT Codon GCA Codon TGC Codon ATG Codon CAT

Exercise A Make a function to add two numbers. Use the following as a template for your program def add(a, b): # your function body goes here print "2+3 =", add(2, 3) print "5+9 =", add(5, 9) The output from your program should be 2+3 = 5 5+9 = 14

Exercise B Modify your program from Exercise A to add three numbers. Use the following as a template for your new program def add3 # you must finish this line # then fill in the body print "2+3+4 =", add(2, 3, 4) print "5+9+10 =", add(5, 9, 10)

Exercise C Use the count_bases function defined earlier to reimplement Exercise 1 from yesterday. (That was the one which asked for a sequence using raw_input then printed the result.)

Exercise D Use the count_bases function defined earlier to reimplement Exercise 2 from yesterday. (That was the one which printed count statistics for every sequence in a data file.)

Exercise E Last Friday s Exercise 5 ( if and files ) asked you to write a program which counts the number of sequences with certain properties (eg, the number of sequences with length > 2000 and %GC > 50%). Redo that exercise but this time use a function for each of the tests. The code should look something like: define the functions first num_over_1000 = 0 # initialize counters for line in open(): seq = line.rstrip() if is_over_1000(seq): num_over_1000 = num_over_1000 + 1 other if cases print the results

Exercise F Look at your DNA to protein translation program. Identify the parts that could be turned into a function. Modify your program accordingly. When finished, ask me to review what you did.