Magic Boxes, Functions
So far, we have been giving commands line by line. But what if you have a group of commands you use often? Typing them every time would be annoying.
That is when you use a function.
A function is like a magic box that bundles a set of commands.
Creating a function (def)
To create a function, we use def, short for “define.”
Type this in PyCharm.
def say_hello():
print("Hello!")
print("Welcome to the Python course.")
# Use the function (call it)
say_hello()
In plain English:
Define a magic box named say_hello:
print "Hello!"
print "Welcome to the Python course."
(Definition ends)
Now open the say_hello box (use it)!
Once you create the box, just writing say_hello() runs everything inside it.
Functions with ingredients (parameters)
Like a vending machine that gives you a drink when you insert a coin, you can also pass ingredients into a function.
def greet(name):
print("Nice to meet you,", name, "!")
greet("Alex")
greet("Python")
Translation:
Define a magic box called greet (the ingredient is called name):
print "Nice to meet you," plus name plus "!"
(Definition ends)
Use the greet box (ingredient is "Alex")
Use the greet box (ingredient is "Python")
Result:
Nice to meet you, Alex !
Nice to meet you, Python !
Functions that return a result (return)
A magic box can finish its work and hand you back a result.
That is what return is for.
def add(a, b):
return a + b
result = add(10, 20)
print("Result:", result)
Translation:
Define a magic box called add (ingredients are a and b):
return the sum of a and b
(Definition ends)
Put 10 and 20 into the add box, and remember the result as result
Print result
Why use functions?
- They save effort: You do not need to write the same code again and again.
- They keep code tidy: Long code can be tucked into a box with a name.
- They are easy to change: Edit the box once, and everything that uses it updates.
Now you are a creator of your own magic boxes!