Functions
Functions
Functions allow us to not repeat ourselves and reuse things that our machines can do over again
- Functions allow code reuse.
-
Defined with def, called/invoked with function name.
-
syntax = def(keyword) name the function(),
Parameters
Parameters are the name of the variables that we use. Define - Default parameters → pre-set values.
def say_hello(name = 'John doe', emoji = '^_^'): #Default Parameters
print(f"Helloo {name} {emoji}")
Arguments
Arguments are used as the actual values we provide to a function. Call, Invoke - Positional arguments → order matters. - Keyword arguments → specify by name.
say_hello()
say_hello('marwa', '<3') #Positional arguments
say_hello(emoji = '<3', name = "Aisha") #Keyword arguments
print(say_hello) #gives location of the memory
Return
Functions should return a value.
def sum1(num1, num2):
return num1 + num2 #returns whatever this expression gives us
# Should do one thing really well and return something
print(sum1(1, 2))
def sum2(num1, num2): # Nested Functions
def anotherFunc(n1, n2):
return n1 + n2
return anotherFunc(num1, num2)
total = sum2(1, 2)
print(total)
Methods vs Functions
-
Functions: independent (print(), max()).
-
Methods: tied to objects ('hello'.capitalize()).
built-in functions
print(), input(), list(), max(), min()
created functions
def some_function ():
pass
some_function()
built-in methods
'helloooo'.capitalize()
args *kwargs
args can accept any number of positional arguments(tuple) *kwargs allow us to grab any number of keyword arguments and get a dictionary
Rule: params, *args, default parameters, kwargs (order of Parameters)**
def func1(*args):
print(args)
return sum(args)
print(func1(1,2,3,4,5)) #*args inside of this function is a tuple of arguments
def func2(**kwargs):
total = 0
for items in kwargs.values():
total += items
return total
print(func2(num1=5, num2=10))
def func3(*args, **kwargs): #using args and kwargs to have n no. of arguments
total = 0 #creating variable for summing up
for items in kwargs.values(): #looping, dictionary(kwargs) method(values)
total += items #adding dict values in the variable
return sum(args) + total
print(func3(1,2,3,4,5, num1=5, num=10))
Doc Strings(''')
- Special comments inside functions for documentation.
- They are really useful to add comments and definitions to your functions
def test(a):
'''
Info: Docstring for test and prints param a
'''
print(a)
test('woah') #to call a function
help(test) #help to find out what a function does
print(test.__doc__) #calling doc strings through methods
Practice Clean code
def is_even(num):
return num % 2 == 0
print(is_even(74))