Functions: Defining and Calling
Functions let you group reusable code under a single name. This makes your programs cleaner, easier to read, and free of repetition.
In Python, you define a function using the def keyword, followed by the function name and parentheses.
1. Defining a Function
Use def to define a function. Add 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 accept input values, known as parameters, to perform actions that depend on those inputs.
Function with Parameters
def greet_user(name): print("Hello,", name) greet_user("Alice")
greet_usertakes one argument calledname.- When called with
"Alice", it prints:Hello, Alice.
4. Returning Values
Functions can produce and send back results using the return statement.
Returning Values
def add(a, b): return a + b result = add(5, 3) print(result)
addtakes two arguments and returns their sum.- The result is stored in
resultand printed.
Summary
| Concept | Description |
|---|---|
def | Keyword to define a function |
| Function call | Executes the code inside the function |
| Parameters | Inputs to customize behavior |
return | Sends back a value to the caller |
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