A function is a piece of code that you can save and reuse it in other progrmas.
You can even use functions written by others (available in the Interent)
A function takes some input and produces an output
Returns the length of input
A = "Hello world"
len(A)
movie_rating = [10,9.5,4,3.5,10,9,5,5]
len(movie_rating)
Returns total of inputs
movie_rating = [10,9.5,4,3.5,10,9,5,5]
sum(movie_rating)
Sorts the input
movie_rating = [10,9.5,4,3.5,10,9,5,5]
sorted(movie_rating)
movie_rating = [10,9.5,4,3.5,10,9,5,5]
# it justs sorts the list but not creats a new list
movie_rating.sort()
movie_rating
To define a function we use def + name of our function + formal parameter X in parentheses
Define a function -> def
Name of our function -> sub
Formal parameters in parentheses followed by a colon(:) -> (n):
- Functions can have multiple parameters (n,m):
Inside function we have our code block with indent -> be carefull with the indent
Return -> returns the output
""" Documentation """ -> Explain what this block of codes does -> """subtract 100 from n"""
Call the function and give it a value to see the output -> sub(200)
def sub(n):
"""subtract 100 from n"""
m = n - 100
return m
sub(200)
def sub(n): # Function has one parameter or inputs
"""subtract 100 from n"""
m = n - 100 #notice the code with indent inside function
return m #notice the code with indent inside function
# our input is 600, we call sub function and give it our input -> it returns output 500
sub(600)
# our input is 1000, we call sub function give it our input -> it returns output -60
sub(40)
def mult(a,b):
c = a*b
return c
# we have two parameters or inputs (two int)
mult(10,9)
# We have two parameters or inputs (one int, one float)
mult(5,2.5)
# We have two parameters or inputs (one int, one string)
# print hello, three times
mult(3, 'hello,')
Use help() function to display the documentation
help(sub)
def staff_name(names):
for name in names:
print(name)
company_staff= ['sara', 'john' , 'smith' ]
staff_name(company_staff)
def staff_list(staff):
for i,j in enumerate(staff):
print('Staff', i , 'is', j)
company_staff= ['sara', 'john' , 'smith' ]
staff_list(company_staff)