Function
A function is a type of subprogram that carries out a task and returns a value.
You can use the result of a function elsewhere in your program, such as storing it in a variable or using it in a decision.
def add_nums():
num1 = int(input("Enter first number"))
num2 = int(input("Enter second number"))
total = num1 + num2
return total
#Main
total = add_nums()
print("The total is", total)
def add_nums(num1, num2):
total = num1 + num2
return total
#Main
total = add_nums(6,4)
print("The total is", total)
Key features of functions
-
Has a name so it can be called when needed
-
Can take inputs (called parameters)
-
Returns a value to the main program
-
Used when you need a result from a task
Why use functions?
-
Organises your code into smaller, easy-to-understand sections
-
Returns data to use elsewhere
-
Avoids repetition – write once, use many times
-
Makes your code easier to test and fix
-
Helps with teamwork, as different people can work on different procedures concurrently