Functions
Package reusable code into functions with def in Python — parameters, return values, and why functions keep your programs clean and DRY.
What you will learn
- Define functions with def
- Use parameters and return
- Reuse your code
def defines a function
A function is a named, reusable block of code. You define it once (write the steps) and then call it whenever you need it, as many times as you like. The word def starts a definition, the name comes next, and the brackets hold any parameters — values you hand in each time.
def greet(name):
return "Hello, " + name + "!"
print(greet("Asha"))
print(greet("Ravi"))Here is how this runs:
def greet(name):defines a function calledgreetthat expects one input, calledname. The indented line is its body and does not run yet — it is just saved for later.- Inside,
returnhands a value back to whoever called the function — here it builds and returns the text"Hello, " + name + "!"(+joins strings together). greet("Asha")calls the function withnameset to"Asha". It returns"Hello, Asha!", whichprintthen shows.- The second call reuses the same function with
"Ravi"— that is the whole point of a function: write it once, call it again and again.
Note: Output: Hello, Asha! Hello, Ravi!
A function can take more than one parameter, and return can hand back the result of a calculation:
def add(a, b):
return a + b
print(add(5, 3)) # 8This function expects two inputs, a and b. When you call add(5, 3), a becomes 5 and b becomes 3, the function adds them and returns 8, and print displays that result. Without return the function would do the sum but hand nothing back, so there would be nothing to print.
Note: Output: 8
Tip: Functions keep your code DRY (Do not Repeat Yourself). Write the logic once, call it many times.
Q. Which keyword defines a function in Python?
✍️ Practice
- Write a function that returns the square of a number.
- Write a function that returns the bigger of two numbers.
🏠 Homework
- Write a function that takes a price and quantity and returns the total.