Defining a Function
A function is a named block of code you can run again and again. You define it once, then call it whenever you need it.
Define one with def, a name, parentheses, and a colon. The indented lines below are the function body:
def say_hello():
print("Hello!")Defining it does not run it. To actually run the body, you call the function by writing its name followed by parentheses:
say_hello() # prints: Hello!
say_hello() # prints it againMost useful functions hand a value back with return. The moment return runs, the function stops and gives that value to whoever called it:
def lucky_number():
return 7
result = lucky_number()
print(result) # prints: 7A function with no return hands back None automatically. return is how a function reports its answer.
Define a function called greeting that takes no parameters and returns the string "Hello!". Then call it, store the result in a variable named message, and print(message).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.