def func_name(list of parameters):
'''
docstring
'''
block of statements
return output_variables
- def: write the reserved name 'def' (from 'define') to start a function
- name and parameters: write the name of the function followed by a list of parameters (optional) in parantheses (obligatory); remember to put ':' at the end of the header
- docstring: not necessary but very helpful. Write here a short explanatory comment about function operation, inputs and outputs. You can easily retrieve it later to include it in your documentation
- function body: write the block of statements to be executed whan the function is called - indented!
- return: write the reserved work 'return' to denote the end of the function (optional: if 'return' is omitted the interpreter silently adds the 'return None' line)
- output values: if you want the function to return one or more values write them separated by comma right after the 'return' keyword
- Write its name and a list of arguments. Arguments are the values we assign to parameters (or 'values we pass to the function'):
func_name(arguments)
- or, Write an assignment with function at the right part:
asum = func_name(arguments)
def hello(): # no need to always include parameters
print('Hello function!') # remember indentation!
# 'return None' is silently added by the interpreter
hello() # calling the function by its name
def ask_name():
'''
Gets and returns the user name from keyboard
'''
name = input('Please enter your name: ')
return name
help(ask_name)
print(ask_name())
def addcon(x,y):
'''
Input: two numeric arguments -> returns their sum
Input: two string arguments -> returns their concatenation
'''
return x+y
a = '7'
b = 'R'
c = addcon(a,b)
print(c)
import random, math
def stat(numlist):
'''
Input: list of numerics
Output: Mean and Standard deviation
'''
mn = sum(numlist)/len(numlist)
sm = 0
for k in numlist:
sm += pow((k-mn), 2)
sd = math.sqrt(sm/(len(numlist)-1))
return mn, sd
help(stat)
mylist = [random.randint(1,100) for i in range(100)]
mean, std = stat(mylist)
print('Mean: {:5.2f}, Standard deviation: {:5.2f}'.format(mean, std))
def trans(oldstr, mode):
'''
Changes the letter case of the input string - Returns a new string
Input: string and mode (flag: 1-> returns UPPER case, all other -> returns lower case)
'''
if mode:
def change(char):
'''
Alters the letetr case (upper or lower)
'''
return char.upper()
else:
def change(char):
'''
Alters the letetr case (upper or lower)
'''
return char.lower()
new_str=''
for ch in oldstr:
new_str += change(ch)
return new_str
while True:
txt = input('Text to transform: ')
md = input('Enter: (1) From lower to Upper, or any other key (from Upper to lower)')
print(trans(txt, md))
if input('Enter for another run / "q" to quit') == 'q':
break
Three major processes take place:
1. When the interpreter meets a 'def' command it constructs a new 'function' object in memory and adds a new binding in the namespace: the one between the name of the function and the 'function' object.
2. When the function is called, arguments pass to the local namespace of the function by shared object reference
3. After the execution of the function is over, a new object has been constructed (the one that the function returns) and is available in the namespace.
See the following example and visualization
def addcon(x,y):
'''
Input: two numeric arguments -> returns their sum
Input: two string arguments -> returns their concatenation
'''
return x+y
a = 5
b = 10
c = addcon(a,b)
print(c)
- The 'function' object addcon(x,y) is constructed and referenced by the name 'addcon' (red arrow)
- When called: arguments pass to the function by 'object reference' (that means: argument objects 5 and 10 are referenced both by parameters a, b in main program and x, y in the function)
- After function execution an integer object with value 15 has been constructed and returned. It is referenced in the namespace by the name 'c' (red arrow)
import random
def sumpow(funclist, ex):
'''
Returns the sum of all funclist members raised to power ex
'''
sm = 0
for item in funclist:
sm += item**ex
return sm
alist = [random.randint(1,100) for x in range(10)]
sum_squares = sumpow(alist, 2)
print(sum_squares, type(sum_squares))
# An integer object is constructed and returned by sumpow()
# and a binding is added in the namespace between sum_squares and this integer object
import math
def circle(r):
'''
Given the radius r it returns the circumference (c) and area (a) of a circle
'''
c = 2*math.pi*r
a = math.pi*r**2
return c, a
radius = 1
circumf, area = circle(radius)
print(circle(radius), type(circle(radius)))
# A tuple object (with 2 items) is constructed by circle() function and returned
# When a function returns more than one object, they are all packed in a tuple object container
. Free learning material
. See full copyright and disclaimer notice