Article directory
Experiment 02 function call
Purpose
- Learn how to create functions
- Know how to call functions
- Master the role of functions that return no value
- Understanding functions applied to functions
Laboratory equipment
- Jupter Notebook
Experimental content
1. (30 points)
Complete the body of the following function according to the function's docstring.
Hint: Python has a built-in function for this round
.
The round() method returns the rounded value of the floating point number x.
round()
Method syntax:
round( x [, n] )
parameter
- x: Numeric expression.
- n: Numerical expression, indicating the number of digits from the decimal point.
def round_to_two_places(num):
"""返回给定的四舍五入到小数点后两位的数字。
>>> round_to_two_places(3.14159)
3.14
"""
# 用你自己的代码替换这个部分。
# ("pass" 是一个关键字,它什么都没做,我们使用它作为占位符,
# 因为在开始一个代码块之后,Python至少需要一行代码)
return round(num, 2)
function test
round_to_two_places(4.2562)
4.26
2. (30 points)
round
The help specification ndigits
(second parameter) may be negative.
what do you think it will happen Try some examples in the cells below?
# Put your test code here
round(123456789,-3)
123457000
Can you think of a useful example?
Can write an example you can think of
round(9634057,-5)
9600000
3. (40 points)
In an earlier programming problem, candy-sharing friends Alice, Bob, and Carol tried to divide the candy evenly. Any remaining candy is smashed for the sake of their friendship. For example, if they have a total of 91 candies, they will each take 30 and smash 1.
Below is a simple function that will calculate the number of candies to smash for any number of total candies.
Modify it so that it optionally accepts a second parameter that represents the number of friends the candy is divided equally. If no second argument is provided, it should assume 3 friends as before.
Update docstring to reflect this new behavior.
def to_smash(total_candies):
"""返回在3个朋友之间平均分配给定数量的糖果后必须粉碎的剩余糖果数量。
>>> to_smash(91)
1
"""
return total_candies % 3
function test
Suppose there are four friends, the number of candies is 23, 36, 53, 46 respectively, call the function to calculate the number of candies to be smashed
#Put your test code here
def to_smash(total_candies, n_friends=3):
"""返回在n个朋友之间平均分配给定数量的糖果后必须粉碎的剩余糖果数量。
默认为3个朋友
>>> to_smash(91, 4)
3
"""
return total_candies % n_friends
#假设有四个朋友,糖果数分别为23,36,53,46,调用函数,计算要砸碎的糖果数
sum=23 + 36 + 53 + 46
print("sum=", sum)
to_smash(sum,4)
sum= 158
2