Lesson 1 of 5 · Functions · 3 min read · Updated
Defining functions
Giving a piece of work a name, handing it values, and getting a result back.
A function is a named block of code you can run whenever you need it. Write the logic once, call it from anywhere, and fix it in one place.
def greet(name):
"""Return a greeting for name."""
return f"Vanakkam, {name}!"
message = greet("Kavya")
print(message)
print(greet("Arun"))
Vanakkam, Kavya!
Vanakkam, Arun!
defstarts the definition;nameis a parameter — a placeholder for the value passed in.- The indented block is the body. It does not run until the function is called.
returnhands a value back to the caller and ends the function.- The triple-quoted line is a docstring:
help(greet)shows it.
print is not return
def show(total):
print("Total is", total)
result = show(250)
print(result)
Total is 250
None
Warning
A function without return gives back None. Printing inside a function shows a value to the user; only return gives it to the rest of your program. Prefer return, and let the caller decide whether to print.
Several results, early returns
def min_max(values):
return min(values), max(values)
low, high = min_max([72, 45, 91])
print(low, high)
def grade(marks):
if marks >= 90:
return "A"
if marks >= 75:
return "B"
return "C"
print(grade(95), grade(80), grade(40))
45 91
A B C
Returning two values really returns one tuple, which the caller unpacks. And because return ends the function at once, grade needs no elif or else.
What does a function return if it has no return statement?
Try this now
- Write
is_even(n)that returns True or False, and use it in a loop over 1 to 10. - Write
average(values)that returns the average of a list, and 0 for an empty list. - Write
celsius_to_fahrenheit(c)and print a conversion table from 0 to 100 in steps of 10.
Create a free account to save your progress, or sign in.