Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ 3.1415000000000002 >>>

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Python Programming Language
Introduction to Computing Science and Programming I
16-May-15 Sudden Python Drinking from the Fire Hose.
Structured programming
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Python.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
Introduction to Python
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
More on Functions (Part 2) Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Course A201: Introduction to Programming 11/04/2010.
9/16/2015BCHB Edwards Introduction to Python BCHB Lecture 5.
If statements while loop for loop
Working on exercises (a few notes first). Comments Sometimes you want to make a comment in the Python code, to remind you what’s going on. Python ignores.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Built-in Data Structures in Python An Introduction.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
9/14/2015BCHB Edwards Introduction to Python BCHB Lecture 4.
Computing Science 1P Large Group Tutorial: Lab Exam & Class Test Simon Gay Department of Computing Science University of Glasgow 2006/07.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Working on exercises (a few notes first)‏. Comments Sometimes you want to make a comment in the Python code, to remind you what’s going on. Python ignores.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Decisions in Python Boolean functions. A Boolean function This is a function which returns a bool result (True or False). The function can certainly work.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Programming Seminar 2009 Night 0. Why we’re holding this seminar You’re probably not a computer science major – Or even anything remotely close (e.g.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
COSC 1223 Computer Science Concepts I Joe Bryan. What is a function? Like a mini-program that performs a specific task Two types: Built-in functions Functions.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Functions with Arguments and Return Values, Oh My! CS303E: Elements of Computers and Programming.
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.
More on Functions (Part 2) Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
String and Lists Dr. José M. Reyes Álamo.
Introduction to Python
Introduction to Python
Introduction to Python
CISC101 Reminders Assn 3 due tomorrow, 7pm.
String and Lists Dr. José M. Reyes Álamo.
Introduction to Python
G. Pullaiah College of Engineering and Technology
Introduction to Python
Introduction to Python
Introduction to Python
COMPUTER PROGRAMMING SKILLS
“Everything Else”.
Python While Loops.
Class code for pythonroom.com cchsp2cs
def-ining a function A function as an execution control structure
Presentation transcript:

Functions

Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>

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 >>> def hello():... print "Hello, how are you?"... >>> hello()‏ Hello, how are you? >>> This function is named ‘hello’

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 >>> def hello():... print "Hello, how are you?"... >>> hello()‏ Hello, how are you? >>> These are the statements that are run when the function is called. They can be any Python statement (print, assignment, if, for, open,...)‏

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? >>> def hello():... print "Hello, how are you?"... >>> hello()‏ Hello, how are you? >>> Start with the name of the function. In this case the name is “hello”

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

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, >>> def hello(name):... print "Hello", name... >>> hello("Andrew")‏ Hello Andrew >>> Say “Hello” followed by the person’s name In maths we say “the function is parameterized by the person’s name ”

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

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

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

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

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 >>> def subtract(x, y):... print x-y... >>> x = subtract(8, 5)‏ 3 >>> print x None >>> By default, a function returns the special value None

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

Making a function Yes, we’re going to count letters again. 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] A solution yesterday’s #1 (except for the raw_input)‏

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 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] In this example the sequence can change. That makes seq a good choice as a parameter.

Identify the algorithm 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] This is the part of your program which does something.

Identify the output 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] The output will use the data computed by your function...

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]... which helps you identify the return value

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 namesBad names count_bases count_letters countbases do_count count_bases_in_sequence CoUnTbAsEs QPXT

Start with the ‘def’ line def count_bases(seq): The function definition starts with a ‘ def ’ It is named ‘ count_bases ’ I t 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] return counts... >>> count_bases("ATATC")‏ {'A': 2, 'C': 1, 'T': 2} >>> count_bases("ATATCQGAC")‏ {'A': 3, 'Q': 1, 'C': 2, 'T': 2, 'G': 1} >>> count_bases("")‏ {} >>> (I don’t even need a variable name - just use the values directly.)‏

Functions can call functions >>> def gc_content(seq):... counts = count_bases(seq)‏... return (counts["G"] + counts["C"]) / float(len(seq))‏... >>> gc_content("CGAATT")‏ >>>

Functions can be used (almost) anywhere >>> 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 >>> In an ‘if’ statement

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 = = 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 " =", add(5, 9, 10)‏

Exercise C Use the count_bases function defined earlier and ask for a sequence using raw_input then printed the result.