Computer Science · Ch 7 — Functions
Creating User Defined Function
7.3.1
Creating User Defined Function
A function definition always begins with the keyword def (short for define). The general syntax for creating a user defined function is:
def function_name([parameter1, parameter2, ...]):
statement(s)
[return value(s)]
Read the syntax with these rules in mind:
- The items enclosed in
[ ]are parameters, and the brackets mean they are optional — a function may or may not have parameters. Likewise, a function may or may not return a value (thereturnline is optional too). - The function header always ends with a colon (
:). - The function name must be unique, and the same rules that apply to naming identifiers in Python apply to naming functions.
- The body of the function is marked by indentation: any statement written outside the function's indentation is not part of the function.
A first user defined function
The task: write a user defined function that accepts two numbers from the user, calculates their sum and displays it. The requirements break down as — (1) accept 2 numbers from the user, (2) calculate their sum, (3) display the sum.
# Function to add two numbers and display their sum
# function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of", fnum, "and", snum, "is", sum)
# function call
addnum()
Notice that addnum() takes no parameters (the parentheses in the header are empty) and returns nothing — it reads its own inputs and prints its own result.