Defining a Function

Assume you and some friends go out to dinner and decide to split the bill evenly. How much should each person pay? Here is a function that calculates each person's share:

>>> def SplitBill(Bill,NumberOfPeople):

... # The hash character (#) starts a comment. Python

... # ignores everything from # to the end of the line.

... return (TotalWithTip / NumberOfPeople)

>>> SplitBill(23.35,3) 8.9508333333333336

The statement def FunctionName (parameter,...): starts a function definition. I indented the following four lines to indicate that they are a control block — a sequence of statements grouped by a common level of indentation. Together, they make up the body of the function definition.

Python statements with the same level of indentation are grouped together. In this example, Python knows the function definition ends when it sees a non-indented line. Grouping statements by indentation-level is common practice in most programming languages; in Python it is actually part of the syntax. Normally, one indentation level equals four spaces, and eight spaces equals one tab.

Was this article helpful?

0 0

Post a comment