Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –
Structured programming
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.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Parsing data records. >sp|P31946|1433B_HUMAN protein beta/alpha OS=Homo sapiens MTMDKSELVQKAKLAEQAERYDDMAAAMKAVTEQGHELSNEERNLLSVAYKNVVGARRSS WRVISSIEQKTERNEKKQQMGKEYREKIEAELQDICNDVLELLDKYLIPNATQPESKVFY.
Introduction to Python
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introduction to Computational Linguistics Programming I.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Input, Output, and Processing
Chapter 6: User-Defined Functions
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
If statements while loop for loop
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Built-in Data Structures in Python An Introduction.
Functions Chapter 4 Python for Informatics: Exploring Information
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
5 1 Data Files CGI/Perl Programming By Diane Zak.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Shell Scripting – Putting it All Together. Agenda Escaping Characters Wildcards Redirecting Output Chaining and Conditional Chaining Unnamed and Named.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
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.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)
Computer Program Flow Control structures determine the order of instruction execution: 1. sequential, where instructions are executed in order 2. conditional,
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
Python’s Modules Noah Black.
Topics Introduction to Functions Defining and Calling a Void Function
CSc 120 Introduction to Computer Programing II
JavaScript: Functions
Functions CIS 40 – Introduction to Programming in Python
JavaScript: Functions.
CHAPTER FOUR Functions.
Topics Introduction to File Input and Output
T. Jumana Abu Shmais – AOU - Riyadh
Introduction to Python: Day Three
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
COMPUTER PROGRAMMING SKILLS
Topics Introduction to File Input and Output
Lists Like tuples, but mutable. Formed with brackets: Assignment: >>> a = [1,2,3] Or with a constructor function: a = list(some_other_container) Subscription.
def-ining a function A function as an execution control structure
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Presentation transcript:

Builtins, namespaces, functions

There are objects that are predefined in Python Python built-ins When you use something without defining it, it means that you are using a built-in object Statements: for,in,import,… Numbers: 3, 16.2,… Strings: ‘AUG’ Functions: dir(), lower(),…

Namespaces The collection of object names defined in a module represents the global namespace of that module The same name (e.g. src) in two different modules (e.g. module_1.py and module_2.py), indicates two distinct objects and the dot syntax makes it possible to avoid confusion between the namespaces of the two modules Each module defines its own namespace Module_1.srcModule_2.srcis NOT the same as

What actually happens when the command import is executed?

The code written in the imported module is entirely interpreted and the module global namespace is imported as well

Where the Python interpreter searches a module when you import it? Where do you have to save a module in order the interpreter can find it? The module can be saved in the same directory of the script importing it The module path can be added to the list of directories where the Python interpreter automatically search things (this list is contained in the variable path of the special module sys)

>>> import sys >>> sys.path ['','/System/Library/Frameworks/Python.frame work/Versions/2.5/lib/python25.zip','/System /Library/Frameworks/Python.framework/Version s/2.5/Extras/lib/python','/Library/Python/2. 5/site-packages'] >>>

The built-in function dir() dir() returns a list of the names defined in the namespace of an object

Functions A block of code that performs a specific task They are useful to organise your script, in particular if you need to repeat actions (e.g. a complex calculation) several times A function can be accessed from different parts of a script or even from different scripts

In order to use a function, you have first to define it and then to call it def MyFunction(arg1, arg2,…): “ documentation ” MyFunction(3,5,…) definition arguments (optional) optional may or may not include a return statement call

def triangle_area(b, h): A = (b*h)/2.0 return A print triangle_area(2.28, 3.55) function body def triangle_area(b, h): return (b*h)/2.0 print triangle_area(2.28, 3.55)

The statement to define a function is def A function must be defined and called using brackets The body of a function is a block of code that is initiated by a colon character followed by indented instructions The last indented statement marks the end of a function definition General remarks

You can insert in the body of a function a documentation string in quotation marks. This string can be retrieved using the __doc__ attribute of the function object You can pass arguments to a function A function may or may not return a value General remarks

Exercise 1 1) Define a function with two arguments: get_values(arg1, arg2) that returns the sum, the difference, and the product of arg1 and arg2.

def get_values(arg1, arg2): s = arg1 + arg2 d = arg1 - arg2 p = arg1 * arg2 return s, d, p print get_values(15, 8)

The statement return exits a function, optionally passing back a value to the caller. A return statement with no arguments is the same as returning None. The returned value can be assigned to a variable >>> def j(x,y):... return x + y... >>> s = j(1, 100) >>> print s 101 >>>

Function arguments >>> def increment(x):... return x >>> def print_arg(y):... print y... >>> print_arg(increment(5)) 6 >>> Every Python object can be passed as argument to a function. A function call can be the argument of a function too.

>>> def print_funct(num, seq):... print num, seq... return... >>> print_funct(10, "ACCTGGCACAA") 10 ACCTGGCACAA >>> Multiple parameters can be passed to a function. In this case, the order of the arguments in the caller must be exactly the same as that in the function definition

The sequence of arguments passed to a function is a tuple Functions return multiple values in the form of tuples as well AND

tuples A tuple is an immutable sequence of object This means that, once you have defined it, you cannot change/replace its elements

tuples Brackets are optional, i.e. you can use either: Tuple = (1,2,3) or Tuple = 1,2,3 variabile = (item1, item2, item3,…) Tuple = (1,) or Tuple = 1, A tuple of a single item must be written either:

>>> my_tuple = (1,2,3) >>> my_tuple[0]#indexing 1 >>> my_tuple[:]#slicing (1, 2, 3) >>> my_tuple[2:]#slicing (3, )

>>> my_tuple[0] = 0 #re-assigning (Forbidden) Traceback (most recent call last): File " ", line 1, in TypeError: 'tuple' object does not support item assignment >>> BUT

def f(a,b): return a + b, a*b, a – b sum, prod, diff = f(20, 2) print sum result = f(20, 2) print result Print result[0]

It is possible to assign a name to the arguments of a function. In this case, the order is not important >>> def print_funct(num, seq):... print num, seq... return... >>> print_funct(seq = "ACCTGGCACAA", num = 10) 10 ACCTGGCACAA >>>

It is also possible to use default arguments (optional). These optional arguments must be placed in the last position(s) of the function definition def print_funct(num, seq = "A"): print num, seq return print_funct(10, "ACCTGGCACAA") print_funct(10)

Summary - def F(x,y): - F(3,’codon’) - function arguments - return

2) Write a function that : Takes as input a file name (of a FASTA file). Opens the file. Returns the header of the sequence record. Print the header. Exercise 2

def return_header(filename): fasta = open(filename) for line in fasta: if line[0] == '>': return line print return_header('SingleSeq.fasta')

Exercise 3 3) Insert the function call in a for loop running on a list of 3 sequence file names.

def return_header(filename): fasta = open(filename) for line in fasta: if line[0] == '>': return line filenames = ['SingleSeq1.fasta', 'SingleSeq2.fasta', 'SingleSeq3.fasta'] for name in filenames: print return_header(name)

Exercise 4 4) Consider two output schemes for exercise 3): All the the headers are written to the same output file Each header is written in a separate output file

def return_header(filename): fasta = open(filename) for line in fasta: if line[0] == '>': return line filenames = ['SingleSeq1.fasta', 'SingleSeq2.fasta', 'SingleSeq3.fasta'] output = open("headers.txt", "w") for name in filenames: output.write(return_header(name) + '\n') output.close()

def return_header(filename): fasta = open(filename) for line in fasta: if line[0] == '>': return line filenames = ['SingleSeq1.fasta', 'SingleSeq2.fasta', 'SingleSeq3.fasta'] n = 0 for name in filenames: n = n + 1 output = open("header" + str(n) + ".txt", "w") output.write(return_header(name)) output.close()

Exercise 5 5) Write a function that takes as argument a Genbank record and returns the nucleotide sequence in FASTA format.

def genbank2fasta(filename): name = filename.split('.')[0] InputFile = open(filename) OutputFile = open(name + ".fasta","w") flag = 0 for line in InputFile: if line[0:9] == 'ACCESSION': AC = line.split()[1].strip() OutputFile.write('>'+AC+'\n') if line[0:6] == 'ORIGIN': flag = 1 continue if flag == 1: fields = line.split() if fields != []: seq = ''.join(fields[1:]) OutputFile.write(seq +'\n') OutputFile.close() filename = "ap gbk" genbank2fasta(filename)

Exercise 6 6) Write a function that takes as arguments two points [x1, y1, z1] and [x2, y2, z2] and returns the distance between the two points.

import math def distance(p1, p2): dist = math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2) return dist p1 = (43.64, 30.72, 88.95) p2 = (45.83, 31.11, 92.04) print "Distance:", distance(p1, p2)

Python uses dynamical namespaces: when a function is called, its namespace is automatically created The variables defined in the body of a function live in its local namespace and not in the script (or module) global namespace Local objects can be made global using the global statement When a function is called, names of the objects used in its body are first searched in the function namespace and subsequently, if they are not found in the function body, they are searched in the script (module) global namespace. General remarks

>>> def f():... x = return x... >>> print x Traceback (most recent call last): File " ", line 1, in NameError: name 'x' is not defined >>> f() 100 >>> print x Traceback (most recent call last): File " ", line 1, in NameError: name 'x' is not defined >>> x is a local name of the function f() namespace and it is not recognised by the “print” statement in the main script even after the function call

>>> def g():... global x... x = return x... >>> print x Traceback (most recent call last): File " ", line 1, in NameError: name 'x' is not defined >>> g() 200 >>> print x 200 >>> The variable x, defined in the body of the g() function, is made global using the “global” statement but is recognised by the “print” statement in the main script only after the function call

>>> y = "ACCTGGCACAA" >>> def h():... print y... >>> h() 'ACCTGGCACAA' y is recognised when h() is called as it is a global name.

The number of arguments can be variable (i.e. can change from one function call to the other); in this case, you can use * or ** symbols. 1 st case(*args) => tuple of arguments 2 nd case(**args)=> dictionary of arguments >>> def print_args(*args):... print args... return... >>> print_args(1,2,3,4,5) (1, 2, 3, 4, 5) >>> print_args("Hello world!") (‘Hello world!’,) >>> print_args(100, 200, "ACCTGGCACAA") (100, 200, ‘ACCTGGCACAA’) >>> def print_args2(**args):... print args... return... >>> print_args2(num = 100, num2 = 200, seq = "ACCTGGCACAA") {'num': 100, 'seq': 'ACCTGGCACAA', 'num2': 200}