Prev: Functions defined | Next: Variable Scope
def myfunc(a, b):
a = 31
b[0] = 'K'
return a, b
x = 10
y = [1,2,3]
newx, newy = myfunc(x, y)
print(newx, newy)
print(x, y)
Right panel: when assigning new values in the function, a new obect (int 31) has been constructed and bound to name 'a' BUT in the list object the first item changed its value 'in place' (now new copy constructed). So, the names 'b' in the function and the name 'y' in the main program continue the shared object reference.
You can further explore the visualization here
This leads us to an importan rule of Python function operation:
- for immutable types (like integer, strings. etc.) new objects are constructed locally in the function
- for mutable types (lists, dicts, etc.) item assignments happen 'in place' and so any changes in the function are reflected in the main program as well.
def myfunc(a, b):
a = 31
b = b[:]
b[0] = 'K'
return a, b
x = 10
y = [1,2,3]
newx, newy = myfunc(x, y)
print(newx, newy)
print(x, y)
- ...be omitted; in this case the parameter's default value is used, or
- ...explicitly be assigned a different value (from the default)
def power(x,y=2):
return x**y
a = power(10) # y takes the default value 2
b = power(10,3) # y is explicitly assigned the value 3
a, b
def power1(x,y=2): # non-default parameter x preceds y
return x**y
def power2(y=2,x): # non-default parameter x is after y
return x**y
- keyword argument: any argument preceded by a name (like an assignment)
power(5, y=3) # 3 is a keyword argument
- positional argument: not a keyword argument; must always be positioned before keyword arguments
power(5, y=3) # 5 is a positional argument
def kinetic(txt, *, m, v):
'''
Returns the kinetic energy of a body
with mass m moving with speed v
'''
en = (m * v**2)/2
print(txt, en)
return en
#...................
kinetic('Kinetic...', m=10, v=20)
#...................
func_name(*args, **kwargs):
..........................
- Note that the important symbol is the asterisk(s) '*' and '**' but NOT the 'args' or 'kwargs' names. These are simply conventions to remind us of 'arguments' and 'keyword arguments' respectively. In fact, we could use other names as well (like *vars, or **keywords, etc..)
- varied-positional arguments are packed inside the function in a tuple object
- varied-keyword arguments are packed inside the function in a dictionary object
- The undefined number of arguments is declared as *args.
- Within the cities_pop() function arguments are handled as a tuple; see, for example, the for loop that computes the total population. In the example we call cities_pop() twice and we pass a different number of arguments each time.
def cities_pop(*args):
'''
Accepts a varied number of data
integers representing cities population
'''
total=0
print('Cities: ', len(args), type(args))
for element in args:
total += element
return total
case1 = cities_pop(65000, 72000)
print('Total population:',case1,'\n')
case2 = cities_pop(230000, 72000, 1000000, 37000)
print('Total population:',case2,'\n')
- The undefined number of arguments is declared as **kwargs.
- Within the cities_pop() function arguments are handled as a dict (dictionary); see, for example, the for loop that computes the total population but it also prints out the keyword city name.
- In the example we call cities_pop() twice and we pass a different number of arguments each time. In this case, however, we must write the arguments in the form of 'key=value' pairs as demonstrated in the example.
def cities_pop(**kwargs):
'''
Accepts a varied number of data
integers representing cities population,
along with key-words: city names
'''
total=0
print('Cities: ', len(kwargs), type(kwargs))
for pair in kwargs.items():
print('City: ',pair[0], 'Population: ', pair[1])
total += pair[1]
return total
case1 = cities_pop(Thessaloniki=810000,
Athens=3200000)
print('Total population', case1,'\n')
case2 = cities_pop(Thessaloniki=810000,
Athens=3200000,
Ioannina=86000,
Patras = 196000)
print('Total population:',case2,'\n')
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 = [1,2,3,4,5] #[random.randint(1,100) for i in range(100)]
mean, std = stat(mylist)
print('Mean: {:5.2f}, Standard deviation: {:5.2f}'.format(*stat(mylist)))
. Free learning material
. See full copyright and disclaimer notice