Introduction
Functions help us group instructions together to do a specific job. This makes our code easier to read and reuse.
Jump into concepts and practice - no test required
Functions help us group instructions together to do a specific job. This makes our code easier to read and reuse.
def function_name(parameters): # code to run return result # optional
Use def to start a function.
Parameters are optional and go inside parentheses.
def greet(): print("Hello!")
def add(a, b): return a + b
def say_name(name): print(f"Your name is {name}.")
This program defines a function to multiply two numbers and then uses it to multiply 4 and 5. It prints the result.
def multiply(x, y): result = x * y return result answer = multiply(4, 5) print(f"4 times 5 is {answer}")
Indentation is important in Python to show which code belongs inside the function.
If you don't use return, the function will return None by default.
Functions group code to do one job.
Use def to create a function with a name and optional parameters.
Use return to send back a result from the function.
def.def. Others are not valid Python keywords.greet that takes no parameters?def, function name, parentheses for parameters, and a colon.def greet():. Others have wrong keywords, brackets, or missing parentheses.def add(x, y):
return x + y
print(add(3, 4))add takes two numbers and returns their sum.add(3, 4) returns 3 + 4 = 7, which is printed.def multiply(a, b)
return a * bdef multiply(a, b), causing a syntax error.is_even that returns True if a number is even, otherwise False. Which is the correct function?n % 2 == 0).