Functions: Defining and Calling
Functions let us group reusable code under a name. This makes code more organized and avoids repetition.
In Python, we define a function using the def
keyword followed by the function name and parentheses.
1. Defining a Function
Use def
to define a function. Include parentheses (with or without parameters) and end the line with a colon.
Defining a Function
def greet(): print("Hello, welcome!")
- The function is named
greet
. - It has no parameters.
- When called, it prints a greeting.
2. Calling a Function
Once defined, you can call the function by writing its name followed by parentheses.
Calling a Function
greet()
- 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.
Function with Parameters
def greet_user(name): print("Hello,", name) greet_user("Alice")
greet_user
takes one argument calledname
.- When called with
"Alice"
, it prints:Hello, Alice
.
4. Returning Values
Functions can send back a result using the return
statement.
Returning Values
def add(a, b): return a + b result = add(5, 3) print(result)
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 |
Quiz
0 / 1
In Python, functions are defined using the 'def' keyword followed by the function name and parentheses.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result