Functions and How to Use Them
1) Friendly introduction
Imagine you have a magic button that does a job for you whenever you press it. In Python, that magic button is called a function. You give it a name, tell it what to do once, and then you can use it as many times as you like. Functions save time, reduce mistakes, and make your code neat and easy to read.
2) What is a function?
- A function is a reusable block of code that does one specific task.
- You can "call" a function to make it run.
- Some functions take information in (parameters), and some send a result back (return value).
3) Why use functions?
- Reuse: Write once, use many times.
- Clarity: Break big problems into small, easy steps.
- Teamwork: Other people (and future you!) can understand and reuse your code.
4) How to create a function (the recipe)
- Start with def
- Give your function a name (letters, numbers, underscores; can't start with a number)
- Add parentheses () with parameters inside (or leave empty if none)
- End the line with a colon :
- Indent the next lines (the function body)
- Optionally use return to send a value back
Example 1: A simple function with no parameters
def say_hello():
print("Hello, PyVerse!")
# Call (use) the function
say_hello()
say_hello()What you'll see:
Hello, PyVerse!
Hello, PyVerse!Example 2: A function with a parameter
def greet(name):
print("Hi", name, "!")
greet("Ava")
greet("Leo")Output:
Hi Ava !
Hi Leo !Example 3: Returning a value
def add(a, b):
return a + b
total = add(7, 5) # total becomes 12
print(total)Why return? Because it gives you a result you can store and use later. print just shows it on the screen.
Example 4: A useful mini-tool (temperature converter)
def to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
temp_c = to_celsius(68)
print(round(temp_c, 1)) # 20.0Example 5: Default parameter (optional input)
def welcome(name="friend"):
print(f"Welcome, {name}!")
welcome()
welcome("Sam")Output:
Welcome, friend!
Welcome, Sam!5) Variables inside functions (scope)
Variables created inside a function live only inside that function.
def make_message():
msg = "Functions are cool!"
return msg
print(make_message()) # Works
# print(msg) # Error: msg is not defined outside the function6) Common mistakes (and quick fixes)
- Forgot parentheses when calling: write greet("Alex"), not greet.
- Missing colon after the function header: def hello(): not def hello()
- No indentation in the function body: indent the code under def
- Using print when you need a value back: use return if you want to store or reuse the result
7) Mini exercise: Build a time converter
Task:
- Write a function total_seconds(hours, minutes) that returns how many seconds are in the given hours and minutes.
- Example: total_seconds(1, 30) should return 5400.
Steps:
- Multiply hours by 3600.
- Multiply minutes by 60.
- Add them and return the result.
- Test your function with a few inputs.
Try it yourself before peeking!
Possible answer:
def total_seconds(hours, minutes):
return hours * 3600 + minutes * 60
print(total_seconds(1, 30)) # 5400
print(total_seconds(0, 45)) # 2700
print(total_seconds(2, 0)) # 72008) Quick summary
- Functions are reusable mini-programs you can name and call.
- Define with def, a name, parentheses, a colon, and an indented body.
- Parameters let you pass information in; return sends a value back.
- Use functions to keep your code clean, clear, and powerful.
You're now ready to make your own handy helpers in Python. Try turning any repeated steps in your code into functions—and press your new "magic buttons" whenever you need them!