So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that execute when the function is called. Once we define a function, we can reuse the function over and over throughout our program.
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character canβt be a number. You canβt use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesnβt take any arguments. Later we will build functions that take arguments as their inputs.
The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces. The body can contain any number of statements.
Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics and then call that function:
Construct a block of code that correctly creates a function called βprintMenuβ that prints the menu and prices, then call the function. Watch your indentation!
The following code should define the function printPrice, that prints items and their prices, and define a second function printReceipt, that uses printPrice to print a receipt. Then, the code should call printReceipt. Watch your indentation!