Python for AIPython for AI
Functions

Defining functions

Create your own reusable functions

In Python, functions let you group code to perform a specific task, making your programs organized and easy to reuse.

Your first function

Imagine you have a few lines of code that you use many times. Instead of typing it out every time, you can put it in a function. This makes your code cleaner and easier to manage.

python
def greet():
    print("Hello, Pythonista!")

greet() # This calls the function

Function syntax

Let's break down how to declare a function in Python. It's quite simple!

Inputs
parameters
→
Function
body runs
→
Output
return value
A function is a black box: data goes in, work happens, a value comes out.
  • You start with the def keyword, which means "define function."
  • Next comes the function name, like greet in our example.
  • Parentheses () always follow the name. These can hold inputs, called parameters.
  • A colon : ends the def line.
  • The function's code block is indented. This indentation tells Python what code belongs to the function.
python
def function_name(parameter1, parameter2):
    # This is the function's body
    # It tells the function what to do
    print("Inside the function")

Naming functions

Good function names are important. They make your code understandable.

  • Use lowercase letters.
  • Separate words with underscores (_). This is called snake_case.
  • Choose names that describe what the function does, like calculate_total or send_email.

Calling functions

Defining a function doesn't execute its code. You need to "call" or "invoke" it to make it run.

python
def say_hello():
    print("Hello there!")

# Call the function by its name followed by parentheses
say_hello()

Functions with logic

Functions aren't just for single print statements. They can contain any Python code, including if statements, loops, or even calls to other functions.

python
def check_age(age):
    if age >= 18:
        print("You are an adult.")
    else:
        print("You are a minor.")

check_age(20)
check_age(16)

Variable scope: Local vs Global

Where you define a variable affects where it can be used. This concept is called scope.

Local variables

Variables created inside a function are "local." They only exist and can be accessed within that function. Once the function finishes, they disappear.

python
def my_function():
    message = "This is a local variable."
    print(message)

my_function()
# print(message) # This would cause an error because message is local

Global variables

Variables defined outside any function are "global." They can be accessed from any part of the program, including inside functions.

python
global_name = "Alice"

def greet_global():
    print(f"Hello, {global_name}!")

greet_global()
print(global_name)

Modifying global variables

If you want to change a global variable from inside a function, you need to use the global keyword. Otherwise, Python will create a new local variable with the same name.

python
count = 0 # Global variable

def increment_count():
    global count # Declare intent to modify the global variable
    count += 1

print(f"Before: {count}")
increment_count()
print(f"After: {count}")

Best practice: Use parameters and returns

Instead of relying on global variables, it's usually better to pass data into functions as parameters and get results back using return statements.

python
def add_numbers(num1, num2):
    result = num1 + num2
    return result # Send the result back

sum_value = add_numbers(5, 3)
print(f"The sum is: {sum_value}")

Common mistakes

  • Forgetting the colon : at the end of the def line.
  • Incorrect indentation for the function body.
  • Not calling the function after defining it, which means it will never run.
  • Trying to access a local variable outside its function scope.
  • Forgetting global when intending to modify a global variable.

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
Which keyword defines a function in Python?
Fill in the blanks
Not started
Define a function that prints 'hi'.
1
2 print("hi")
3greet()

What's next?

You've learned the basics of functions! Next, you can explore functions that take different types of arguments and how to make your functions even more flexible.