Intro to Functions
Functions are blocks of reusable code that help us organize our programs, avoid repetition, and make our code cleaner and easier to understand.
What Is a Function?
Think of a function as a machine: You give it some input (called arguments), and it gives you back an output (called the return value). A function can also do something internally without returning anything.
In Python, you define a function using the def
keyword, followed by the function name and parentheses ()
.
def say_hello():
print("Hello, world!")
This code defines a function called say_hello
. But defining a function does not run it. You have to call it:
say_hello() # Output: Hello, world!
Why Use Functions?
- Reduce repetition in your code
- Break down complex problems into smaller pieces
- Make your code easier to test and debug
- Improve readability and collaboration
Anatomy of a Function
Here’s a function that accepts input:
def greet(name):
print(f"Hello, {name}!")
Then, call it(use it) like this:
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
Parameters vs Arguments
- Parameter is the variable used in the function definition:
name
in the example above. - Argument is the actual value passed when calling the function:
"Alice"
or"Bob"
.
Summary
- Functions are reusable blocks of code.
- You define them using
def
. - Use them to avoid repetition and improve clarity.
- You can pass values into them using parameters.
Exercise: Try It Yourself!
- Create a function called
welcome()
that prints"Welcome to LanceCourse!"
. - Create a function called
square_number()
that accepts a number and prints its square. - Create a function
describe_pet()
that takes a pet name and type, then prints a sentence like"My dog is called Rex."