Lecture 4 - Functions
日期: 2017-03-01 分类: 跨站数据测试 245次阅读
Lecture 4 - Functions
1. Function syntax
Syntax
def <function name> (<formal parameters>):
<function body>
tips
If the output can be either an int or a float, select num, which isn’t a real Python type, but which we’ll use to indicate that either basic numeric type is legal.
eg:
def a(x): ''' x: int or float. ''' return x + 1 # Output is num
2. ENVIRONMENTS
Environments to understand bindings
Environments are formalism for tracking bindings of variables and values
Assignments pair name and value in environment
Asking for value of name just looks up in current environment •
Python shell is default (or global) environment
Definitions pair function name with details of function
COMPUTING POWERS AS AN EXAMPLE
- Example of computation without and with functional abstraction
## Example of computation without and with functional abstraction
## Without functional abstraction
##x = raw_input('Enter a number: ')
##p = int(raw_input('Enter an integer power: '))
##
##result = 1
##
##for turn in range(p):
## print('iteration: ' + str(turn) + ' current result: ' + str(result))
## result = result * x
## With functional abstraction
def iterativePower(x,p):
result = 1
for turn in range(p):
print ('iteration: ' + str(turn) + ' current result: ' + str(result))
result = result * x
return result
3.UNDERSTANDING VARIABLE BINDING
- Each function call creates a new environment, which scopes bindings of formal parameters
and values, and of local variables (those created with assignments within body) - Scoping often called static or lexical because scope within which variable has value is
defined by extent of code boundaries.
4. Using function modules
steps:
- Place in a XX.py file
Use import command to access
example:# circle.py # From Lecture 4, Modules pi = 3.14159 def area(radius): return pi*(radius**2) def circumference(radius): return 2*pi*radius
2 ways:
import circle
from circle import *
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
上一篇: 干货,收藏
下一篇: HTML标签常用标签
精华推荐