Functions: Defining and Calling
Functions let us group reusable code under a name. This makes our code more organized and avoids repetition.
In Python, we define a function using the def
keyword followed by the function name and parentheses.
Let’s go through the basics of creating and using functions.
1. Defining a Function
Use def
to define a function. Include parentheses (with or without parameters) and end the line with a colon.
def greet():
print("Hello, welcome!")
Explanation:
- This function is named
greet
. - It has no parameters.
- When called, it prints a greeting.
2. Calling a Function
Once defined, we can call the function by writing its name followed by parentheses.
greet()
Explanation:
- This line runs the
greet()
function and prints the message.
3. Function with Parameters
Functions can take input values (parameters) to perform different actions based on the input.
def greet_user(name):
print("Hello,", name)
greet_user("Alice")
Explanation:
greet_user
takes one argument calledname
.- When called with
"Alice"
, it prints:Hello, Alice
.
4. Returning Values
Functions can send back (return) a result using the return
statement.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Explanation:
add
takes two arguments and returns their sum.- The result is stored in
result
and printed.
Summary
Concept | Description |
---|---|
def | Keyword to define a function |
Function call | Runs the code inside the function |
Parameters | Inputs to customize behavior |
return | Sends back a value from the function |
What’s Next?
Next, you’ll learn how to pass arguments and handle return values in more detail — key to writing powerful Python functions.