A block of code can be put under a function name which can be used again and again.
<a href="https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
Defining Functions
· To define a simple function the keyword 'def' is used before the function name which is followed by the Parenthesis
· The parentheses hold the argument of the function.
· no {} to be used to enclose the function rather indents (spaces) should be given appropriately to define the body of the function.
def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b # keep two blank lines after and before a function definition
# (Good programming habit)
A function can have multiple arguments of different datatypes, but the arguments should be addressed in the function body.
fib(10) # Function being called with the argument
Another example on arguments and calling them.
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
This function can be called in several ways:
· giving only the mandatory argument: ask_ok('Do you really want to quit?')
· giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
· or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
The
statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.
The return key words return the data associated with the variable at the end of the return keyword.
It is not necessary that return keyword will only return a variable data it can also return logic like ‘True’ or ‘False’.
def fib2(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
return a
def fib2(n): # return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a + b return result
Comentarios