****学 习 地 址 :****
计算机科学圈| 01000011 01010011 01000011
1. Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
「函数是一个有组织的、可重用的代码块,用于执行单个的、相关的操作。函数让程序变得更短, 更整洁, 便于阅览和调试,提高可重复使用性。为应用程序提供了更好的模块化和高度的代码重用性。」
2. Build-in Functions
内置函数(Built-in Functions)是在Python解释器程序中已经定义的函数,随着解释器的运行而执行其功能。在Python的程序中,用户无需再定义此类函数,可以直接在其程序中调用。
Python提供许多内置函数(Built-in Functions),例如print()等:
Built-in Functions | ||||
---|---|---|---|---|
abs() |
delattr() |
hash() |
memoryview() |
set() |
all() |
dict() |
help() |
min() |
setattr() |
any() |
dir() |
hex() |
next() |
slice() |
ascii() |
divmod() |
id() |
object() |
sorted() |
bin() |
enumerate() |
input() |
oct() |
staticmethod() |
bool() |
eval() |
int() |
open() |
str() |
breakpoint() |
exec() |
isinstance() |
ord() |
sum() |
bytearray() |
filter() |
issubclass() |
pow() |
super() |
bytes() |
float() |
iter() |
print() |
tuple() |
callable() |
format() |
len() |
property() |
type() |
chr() |
frozenset() |
list() |
range() |
vars() |
classmethod() |
getattr() |
locals() |
repr() |
zip() |
compile() |
globals() |
map() |
reversed() |
__import__() |
complex() |
hasattr() |
max() |
round() |
3. Defining a Function
定义函数可以让程序变得更短, 更整洁, 便于阅览和调试,提高可重复使用性。
Syntax
def functionname(argument-list): ##第一行确定函数的名字和实参(输入)
"function_docstring" ##函数定义第一行之后的内容都是函数体 。函数体是一块缩进的代码。
function_suite
return [value] ##返还的值是函数的输出。
Rules to define a function in Python
-
以关键字def开头,后跟函数名称和括号;
-
参数是位置特异性的,调用时要按照定义的参数顺序输入;
-
任何输入参数或参数都应放在括号内,可以在括号内定义参数;
-
函数的第一条语句("function_docstring")是可选语句;
-
每个函数中的代码块均以冒号(:)开头并缩进。
例,绝对值函数的定义:
def abs(x): ## define a function named 'abs' of one argument named 'x'
if x >= 0: ## function body starts here
return x
else:
return -x ## function body ends here
3. Calling a Function
在Python中调用函数,只需在函数名称后加上(),然后将所有必需的参数按定义时对应位置放在方括号内即可。
例如,调用上面编写的函数:
def abs(x): # define a function named 'abs' of one argument named 'x'
if x >= 0: # function body starts here
return x
else:
return -x # function body ends here
# call the function, now that it's defined
print(abs(-10))
print(abs(abs(-10)))
4. Exercise & Answer
Coding Exercise:One Road
For part 1, there is a single road between the two cities. The road has three bridges with weight limits a, b, c.
**Write a program that prints out the maximum weight that can be transported along this road.
my Answer
maxWeight=min(a,b,c)
print(maxWeight)
Coding Exercise:Two Roads
For part 2, there are two roads between the two cities. One has three bridges with weight limits a, b, c,and one has two bridges with weight limits d, e.
**Write a program that prints out the maximum weight that can be transported between the two cities.
my Answer
maxWeight1=min(a,b,c)
maxWeight2=min(d,e)
print(max(maxWeight1,maxWeight2))
Scramble Exercise:Sort of Strangeness
drag-and-drop the lines to rearrange the code so that it prints the three numbers x, y and z sorted in increasing order, so that the smallest is printed first, then the middle one, and then the largest one.
my Answer
Coding Exercise: Growth Debugging
Fix the logic error in this program: it should calculate the population of your country for the next 3 years.
my Answer
populationIn2012 = 1000
populationIn2013 = populationIn2012 * 1.1
populationIn2014 = populationIn2013 * 1.1
populationIn2015 = populationIn2014 * 1.1
Coding Exercise: Complication a simple expression
use max in a clever way to simulate min
my Answer
min(A, B)
print(-1*max(-1*A, -1*B))
Coding Exercise: Payment Calculator
Write a program to print out the minimum payment using min and max.
my Answer
miniPayment=print(min(balance,max(10,0.021*balance)))
Scramble Exercise: Sorting Scramble
Code scramble:make the program sort the three numbers x, y and z into increasing order, so that x has the smallest value, y has the next smallest value, and z has the largest value.
my Answer
「这里x =min(x, y)如果放在tmp = max(x, y)之前,当输入y值小于x值时,通过x =min(x, y),那么x会获取y,导致初始值丢失。」
参考:
[1]https://cscircles.cemc.uwaterloo.ca/
[2]https://python-textbok.readthedocs.io/en/1.0/Errors_and_Exceptions.html#answer-to-exercise-1
[3]https://www.tutorialspoint.com/python/python_functions.htm
网友评论