350 likes | 536 Views
Names, Functions and Modules. Chapter 2. Names. A Python name consists of an arbitrary number of letters, underscores and digits, where the first character is not a digit Wouldn’t want Python to think you were trying to specify an integer!
E N D
Names, Functions and Modules Chapter 2
Names • A Python name consists of an arbitrary number of letters, underscores and digits, where the first character is not a digit • Wouldn’t want Python to think you were trying to specify an integer! • Don’t start your name with two underscorse (_ _), which is used for special situations. • A name is used to refer to something – a primitive value, a function, … • Giving a name to a value is called a binding. • One value can have multiple names bound to it.
Namespaces • The same name can be bound to different objects in different contexts • These contexts are called namespaces. • The names of the types and built-in functions we saw earlier belong to the global namespace. • A separate namespace is associated with each type, e.g., str. • The binding of a methodname is determined by the type of the object through which it is called.
Types and Classes type class valueobject Every value has a typeEvery object is an instance of a class
Assigning Names • Python program is a sequence of statements • Statements do not produce values and are not expressions • An assignment statement binds a name to an object • Notation: name = value • Only names a value. Does not • change the value • change any of the value’s other names • Assignment names may be chained together to bind several names to the same value: >>> a = b = c = 0 >>> a 0 >>> b 0 >>> c 0 >>>
Assigning Names • Examples: >>> one_name = 'John Doe' >>> another_name = 'Dylan Thomas' >>> one_name 'John Doe' >>> len(another_name) 12 >>> third_name Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> third_name NameError: name 'third_name' is not defined >>> third_name = one_name >>> third_name 'John Doe' >>>
Assignment Statements • There is another variation on the basic assignment statement:the augmented assignment statement • Such statements are shorthand forms for when you are carrying out an operation and the result is being assigned to its first argument • The following two statements do the same thing (on different variables!) >>> a = a + 1 >>> b += 1 >>> a 1 >>> b 1 >>> Other versions: -= *= /= //= %=
Assigning Names • You have seen before how we use built-in functions by calling them. • Now we consider definingyour own functions. • Overall form: def name(parameter_list): body where • body is one or more statements, each indented relative to def • parameter list is a (possibly empty) comma separated list of names • The body of a function may include a call to a second function • In response, Python records the call and passes control to the second function which itself may call a third function • The record of a call includes the location of the function call in the calling function so that its execution may properly continue after the call completes.
Return Statements • Some functions are supposed to return values while others may simply perform needed actions. • A return statement is used to return a value from a function. • Overall form: return value • The body of a function may include a call to a second function • In response, Python records the call and passes control to the second function which itself may call a third function • The record of a call includes the location of the function call in the calling function so that its execution may properly continue after the call completes.
Function Body • How to defer function body implementation? • A function definition must have a nonempty body • Solution: the “do nothing” statement pass • defmyfunc(): pass • If you were to call this function, it would return None • Note: None prints as the empty string
Function Parameters • To call a function that was defined with parameters, arguments must be supplied for the parameters. • For each parameter in turn, Python assigns the parameter name to the corresponding argument’s value. • Once all parameter names have been assigned, the function body is executed. • defrecognition_site(base_seq,recognition_seq): return base_seq.find(recognition_seq) • Each function has a separate namespace and its parameters go in that namespace. • Within the function body, assignments create bindings in that namespace. • Thus a name bound in the interpreter (or a calling function) and a name with the same spelling bound in a function definition have nothing to do with each other. • They are in different namespaces.
Function Parameters >>> def validate_base_sequence(base_sequence): seq = base_sequence.upper() return len(seq) == (seq.count('T') + seq.count('C') + seq.count('A') + seq.count('G')) >>> seq = 'AAAT‘ >>> validate_base_sequence('tattatat') True >>> seq 'AAAT' >>> line splitting allowed within parentheses in interpreter namespace seq names ‘AAAT’ in function namespace seq names ‘tattatat’ in interpreter namespace seq still names ‘AAAT’
Line Splitting • Another way that you can continue a statement on a new line is to end the line with \ >>> defvalidate_base_sequence(base_sequence): seq = base_sequence.upper() return len(seq) == seq.count('T') + \seq.count('C') + \seq.count('A') + \ seq.count('G') • The end of a block (like the body of the function above) is indicated by a line at the same indentation level as the block header (def). • In the above, there is a blank line that starts at the same indentation level as def.
Comments • If Python encounters the # character, it treats the rest of the line as a comment and thus does not process it as part of the script • Well chosen comments are essential for writing understandable scripts • But don’t overdo it!
Docstrings • You can provide documentation for your functions by placing a string immediately after the def line • Since you normally use more than one line, triple quotes are used. • These “docstrings” are then produced when a user enters help(fcn_name)
Asssert Statments • Typically, when you define a function you expect the parameters to be of a specific type or class. • Unlike C, C++ and many other languages, a Python parameter does not have a declared type • Any name can refer to an arbitrary value or object • It is a good idea to specify your assumptions about parameters in a docstring • But a docstring will not provide protection in cases where the assumptions do not hold. They are not statements and are not executed. • Python assertstatements may be used instead. • Such a statement “asserts” that a given expression evaluates to True. • If it evaluates to False, you get an AssertionError • The general form of an assert statement is: assertexpression
Asssert Statments • A failed assert statement: • You can add a more informative message for assert failure assertexpression, msg
Default Parameter Values • It frequently happens that most calls to a function receive the same value for one of its parameters. • Python provides a way for you to indicate a default value for a parameter which will be used unless an actual value appears in its place. • This mechanism is often used for optional parameters. • There can be any number of default parameters, but all default parameters must follow all non-default parameters. • It is often the case that an optional parameter specifies a True/False value. • Such parameters are called flags.
Default Parameter Values def validate_base_sequence(base_sequence, RNAflag=False): """Return True if the string base_sequence contains only upper- or lowercase T (or U, if RNAflag), C, A, and G characters, otherwise False""" seq = base_sequence.upper() return len(seq) == (seq.count('U' if RNAflag else 'T') + seq.count('C') + seq.count('A') + seq.count('G')) >>> validate_base_sequence('ATCG',False) True >>> validate_base_sequence('ATCG',True) False >>> validate_base_sequence('AUCG',True) True >>> validate_base_sequence('AUCG') False Second argument omitted Default value (False) used
Keyword Parameters • We have so far been using positional parameters. • That is, when we call the function, we pass the arguments in the order in which the parameters appear in the function definition • When we have default parameters, we may specify the argument by using the parameter name • These arguments are called keyword arguments • See the example on the next slide
Keyword Parameters >>> def divisions(numerator=1,denominator=1): print(numerator/denominator,numerator//denominator) >>> divisions(10,4) 2.5 2 >>> divisions(denominator=4,numerator=10) 2.5 2 >>> divisions(5) #denominator defaults to 1 5.0 5 >>> divisions(denominator=5) #numerator defaults to 1 0.2 0 >>> divisions() #both arguments default to 1 1.0 1 Remember that all non-default parameters are positional and must precede all default parameters
Modules • Python provides a large number of optional types, functions and methods. • These are defined by modulefiles kept in a librarydirectory as part of Python’s distribution. • Throughout the course, we will describe a number of these modules that are generally useful. • There are also a wealth of other modules supplied by the Python community. • A module file contains Python statements (mostly defs). • Normally, there is a docstring at the beginning of the file describing the components supplied by the module. • For now, we concentrate on the use of modules.
Importing a Module • To make a module’s contents available, you must specify it in an importstatement. • This will result in the module being loaded into the Python environment and its name becoming available in the containing namespace. importname • name does not contain a path or extension (but the file must have extension .py) • Python maintains a list of directories where modules may be found • It also keeps track of the modules that have been imported so far • When a module is imported the first time, Python searches the directories in the list until the module file is found. • It then executes the statements in the module and creates an object to represent the module and its contents. • If the module is imported again, all this is skipped (unless the module has been modified).
Importing a Module • Each module has a distinct namespace • Python includes quite a few modules during its build process • But their names are not available until they are imported. • For example, consider the os module, which provides an interface to the operating system. • All the contents of the os module are already in Python, but the name os has no meaning until the module is imported. • Importing assigns the name to the object representing the module. • Each module has a separate namespace distinct from the interpreter namespace and any other module’s namespace • Module components are accessed using the dot notation
Importing a Module • A module may also have sub-modules • For example, os.path is a submodule of os • Examples >>> import os >>> os <module 'os' from 'C:\Python32\lib\os.py'> >>> os.getcwd() 'C:\\Python32' >>> os.getlogin() 'rtindell' >>> os.path.exists('C:\\Users\\rtindell') True >>> os.path.exists('C:\Users\rtindell') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape
Variations on Import >>> sys Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> sys NameError: name 'sys' is not defined >>> version Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> version NameError: name 'version' is not defined >>> from sys import version >>> version '3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]' >>> sys Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> sys NameError: name 'sys' is not defined >>> import sys >>> sys.path ['', 'C:\\Python32\\Lib\\idlelib', 'C:\\Windows\\system32\\python32.zip', 'C:\\Python32\\DLLs', 'C:\\Python32\\lib', 'C:\\Python32', 'C:\\Python32\\lib\\site-packages'] Version of Python Module search path
The random Module • Various methods for random number generation • random.randint takes two integer arguments and returns a random integer in the range of the first to the second, inclusive. • random.randint(1,4) will return one of the integers 1, 2, 3, 4. • Useful for simulations of systems • Also useful for generating examples and “test cases” for your code.
Python Files • A file you import becomes a module just as for the built-in modules • Each python file must import any modules it uses. • However, the import action is not transitive (ah, bit of discrete math) • That is, if module A imports module B and module B imports C, module C is not visible in A. It must directly import C if it wants to use it. • A module file will often include statements to test its other components. • Such statements will be executed whether the module file is imported or executed.
Example Script # Example Python Script def switch(s,p1,p2): ''' Returns a string equal to s with all occurrences of p1 replaced by p2 and all occurrences of p2 replaced by p1 Assumes that '!!!' is not a substring of any of the strings ''' s = s.replace(p1,p1+'!!!') s = s.replace(p2,p1) s = s.replace(p1+'!!!',p2) return s t = input('String to be altered: ') q1 = input('First string for the switch: ') q1 = input('Second string for the switch: ') t = switch(t,q1,q2) print('String after switch\n',t)
Assignment • You are to create a file named repeater.py • Your file should contain a script that prompts for two strings and prints “Yes” if the first string contains at least two non-overlapping substrings equal to the second string, otherwise prints “No”. • VARIATION: do the same, but allow overlapping of the substrings.