Python Introduction | Functions | What Is a Function?
Scripts often repeat the same process many times. Writing the same code again each time is tedious. A function lets you call a predefined process whenever and wherever you need it.
Consider Example 1. It stores names in variables and prints messages in the form "Hello, OO. How are you?". It repeats similar print statements to display similar text.
Example 1
a = "Taro"
b = "Hanako"
c = "Ichiro"
print("Hello, " + a + ". How are you?")
print("Hello, " + b + ". How are you?")
print("Hello, " + c + ". How are you?")
A function is useful in this situation. Example 2 rewrites the code using a function. First, define a function that prints a message in a fixed format. You can then call it at any time with code such as showMsg("Taro").
Example 2
def showMsg(str):
print("Hello, " + str + ". How are you?")
showMsg("Taro")
showMsg("Hanako")
showMsg("Ichiro")
This example only displays a short message. With more complicated processes, the ability to write code once and call it whenever needed becomes especially convenient.
Is print Also a Function?
You have already used a function: print, which displays values. Python provides many built-in features, and most of them are available as functions.