Back to Python Mastery
IntermediateTeenagers
Introduction to Functions
As your programs get bigger, you'll find yourself writing the same code over and over. Functions are here to help!
A function is a reusable block of code that performs a specific task. You define it once and can use it many times.
Here's how to define a simple function:
'def' is the keyword to define a function. 'greet' is the name of our function. To run the code inside the function, you "call" it by its name:
This will print "Hello, world!".
Functions can also take inputs, called 'parameters' or 'arguments'.
And they can also return a value:
Functions are essential for writing clean, organized, and efficient code.
A function is a reusable block of code that performs a specific task. You define it once and can use it many times.
Here's how to define a simple function:
def greet():print("Hello, world!")'def' is the keyword to define a function. 'greet' is the name of our function. To run the code inside the function, you "call" it by its name:
greet()This will print "Hello, world!".
Functions can also take inputs, called 'parameters' or 'arguments'.
def greet_user(name):print(f"Hello, {name}!")greet_user("Bob") # This will print "Hello, Bob!"And they can also return a value:
def add(a, b):return a + bsum_result = add(5, 3)print(sum_result) # This will print 8Functions are essential for writing clean, organized, and efficient code.
Simple Function
Complete the function to take two numbers and return their sum.