def function_name(parameter1, parameter2, ...):
# function's body
...
return "return value"
def
+ function name + parameters name
- After def, we write the name of our function (so as to invoke it later) and the names of parameters, which our function can accept, enclosed in parentheses. Do not miss the colon at the end of the line. The names of a function and its parameters follow the same convention as variable names, that is, they should be written in lowercase with underscores between words.
# Function definition
def multiply(x, y):
return x * y
# Function calls
a = multiply(3, 5) # 15
b = multiply(a, 10) # 150
def welcome():
print("Hello, people!")
# This function does nothing (yet)
def lazy_func(param):
pass
- When you choose to call lazy_func() with an arbitrary value as its argument, nothing will happen. So pass is just a placeholder, but at least your code will be valid with it.
def send_postcard(address, message):
print("Sending a postcard to", address)
print("With the message:", message)
send_postcard("Hilton, 97", "Hello, bro!")
# Sending a postcard to Hilton, 97
# With the message: Hello, bro!
send_postcard("Piccadilly, London", "Hi, London!")
# Sending a postcard to Piccadilly, London
# With the message: Hi, London!
This function takes exactly 2 arguments, so you will not be able to execute it with more or less than 2 arguments:
send_postcard("Big Ben, London")
TypeError: send_postcard() missing 1 required positional argument: 'message'
- problem
# implement the function below 我的
def get_sum(a, b):
pass
sum_num = a + b
return (sum_num)
#improvement
def get_sum(a, b):
return a + b
def closest_higher_mod_5(x):
if x % 5 == 0:
return x
return x + (5 - x % 5)
```