Python:Functions: Difference between revisions

From wiki
Jump to navigation Jump to search
mNo edit summary
 
(18 intermediate revisions by the same user not shown)
Line 1: Line 1:
[[category:Python]]
[[category:Python]]


You can pass a function-name as parameter
;sys._getframe(  ).f_code.co_name
:Return name of current function
 
;eval(functionnameasstring)()
:Convert a function name as string to a function call
:WARNING: Make sure you have control over the string provided, you may call anything this way.
 
 
=Passing arguments=
 
If an argument is a mutable object it is passed by reference. So when you modify the object in the function, the change there in the outside world too.
Immutable objects are passed by value. You cannot change the object, you have to return the new one.


<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
def main():
def main():
     outcome = function1('function2',par2)
     aInt = 1
    aList = ['a']
    bInt = function(aInt, aList)
    print(aInt, bInt, aList)  # This will print:  "1 6 ['a', 'something']"
    return
 
def function (a, b):
    # a is a new integer object
    # b is a reference to the aList object.
    a += 5
    b.append('something')
    return a
 
main()
</syntaxhighlight>
 
 
Arguments are positional but can be passed by keyword too.
 
<syntaxhighlight lang='python'>
def main():
    outcome = function(par1,par2)
     function(par2 = <value>, par1 = <value>)
     function(par2 = <value>, par1 = <value>)
    return
def function (inpar1, inpar2 = <defaultvalue>):
    codeblock
    return result
main()
</syntaxhighlight>
;def function (*args,**kwargs):
:Take any number of positional arguments and put them in the [[Python:DataTypes#Tuple|tuple]] args
:Take any number of keyword arguments and put them in the [[Python:DataTypes#Dictionary_or_dict|dict]] kwargs
;You can pass a function-name as parameter
<syntaxhighlight lang='python'>
def main():
    outcome = function1(function2,inpar2 = <value>)
     return
     return


Line 13: Line 65:
     return result
     return result


def function2 (inpar1, inpar2 = <defaultvalue>):
def function2 (inpar):
     codeblock
     codeblock
     return result
     return result
Line 20: Line 72:
</syntaxhighlight>
</syntaxhighlight>


=Anonymous functions(lambda)=
lambda defines an anonymous function.
Can be used in may places.
Here the dictionary has lambda functions as value. adict['a'](<value>) calls the function and returns True of False.
<syntaxhighlight lang=python>
adict = {
        'a': lambda a: 0 < a < 10,
        'b': lambda a: 11 < a < 20,
        'c': lambda a: 21 < a < 30,
        'd': lambda a: 31 < a < 40
    }


=Build in function=
adict['a'](5)  # True
adict['a'](15) # False
</syntaxhighlight>
 
=Build in functions=


List of all build in functions [https://docs.python.org/3/library/functions.html]
List of all build in functions [https://docs.python.org/3/library/functions.html]
Line 33: Line 102:
;min(obj1)
;min(obj1)
Return the smallest item in obj1
Return the smallest item in obj1
;round(x,y)
:Round x to y decimals, y defaults to 0
;BEWARE; In python 3x rounding does not work 'As taught in school'[https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior] but rounds half to even[https://en.wikipedia.org/wiki/Rounding#Round_half_to_even].
Use this to implement 'As taught in school' by overwriting the round() function.
<syntaxhighlight lang=python>
def round(valuein, digits=None):
    import decimal
    value = str(valuein)
    if digits is None:
        try:
            digits = len(value.split('.')[1])
        except IndexError:
            digits = 0
    formatstring = '1.' + '1' * digits
    try:
        result = decimal.Decimal(value).quantize(decimal.Decimal(formatstring), rounding=decimal.ROUND_HALF_UP)
    except decimal.InvalidOperation:
        result = valuein
    return result
</syntaxhighlight>


;input([prompt])
;input([prompt])
Line 44: Line 135:
:Return a string representation of an object. str for the informal representation (just make it printable), repr for the formal representation (more formating??)
:Return a string representation of an object. str for the informal representation (just make it printable), repr for the formal representation (more formating??)


=Self defined functions=
=Boolean functions=
Functions that just return True or False
;isinsantce(var, type)
:If a variable has the wanted type (list,set,int,str,dict)
;isfile(filename)
:If a file exists


Arguments are positional but can be passed by keyword too.
;any(<object>)
:If any of the elements is True (any iterateble will do)
;any(x in alist for x in aset)
:If any of the elements of list are in set
;all(<object>)
:True if all elements of <object> are true (have a value)


<syntaxhighlight lang='python'>
=Resursive functions=
def main():
In resursive functions you should update the objects to return, not create new ones. Use augmented assignment (+=).
    outcome = function(par1,par2)
    function(par2 = <value>, par1 = <value>)
    return
 
def function (inpar1, inpar2 = <defaultvalue>):
    codeblock
    return result


main()
=Other often used functions=
;Sleep function
<syntaxhighlight lang=python>
import time
time.sleep(<sec>)
</syntaxhighlight>
</syntaxhighlight>
;def function (*args,**kwargs):
:Take any number of positional arguments and put them in the [[Python:DataTypes#Tuple|tuple]] args
:Take any number of keyword arguments and put them in the [[Python:DataTypes#Dictionary_or_dict|dict]] kwargs

Latest revision as of 09:50, 28 April 2026


sys._getframe( ).f_code.co_name
Return name of current function
eval(functionnameasstring)()
Convert a function name as string to a function call
WARNING: Make sure you have control over the string provided, you may call anything this way.


Passing arguments

If an argument is a mutable object it is passed by reference. So when you modify the object in the function, the change there in the outside world too. Immutable objects are passed by value. You cannot change the object, you have to return the new one.

def main():
    aInt = 1
    aList = ['a']
    bInt = function(aInt, aList)
    print(aInt, bInt, aList)  # This will print:  "1 6 ['a', 'something']"
    return

def function (a, b):
    # a is a new integer object
    # b is a reference to the aList object.
    a += 5
    b.append('something')
    return a

main()


Arguments are positional but can be passed by keyword too.

def main():
    outcome = function(par1,par2)
    function(par2 = <value>, par1 = <value>)
    return

def function (inpar1, inpar2 = <defaultvalue>):
    codeblock
    return result

main()


def function (*args,**kwargs)
Take any number of positional arguments and put them in the tuple args
Take any number of keyword arguments and put them in the dict kwargs


You can pass a function-name as parameter
def main():
    outcome = function1(function2,inpar2 = <value>)
    return

def function1 (functiontocall, inpar2 = <defaultvalue>):
    result = functiontocall(inpar2)
    return result

def function2 (inpar):
    codeblock
    return result

main()

Anonymous functions(lambda)

lambda defines an anonymous function.

Can be used in may places.

Here the dictionary has lambda functions as value. adict['a'](<value>) calls the function and returns True of False.

adict = {
        'a': lambda a: 0 < a < 10,
        'b': lambda a: 11 < a < 20,
        'c': lambda a: 21 < a < 30,
        'd': lambda a: 31 < a < 40
    }

adict['a'](5)  # True
adict['a'](15) # False

Build in functions

List of all build in functions [1]

len(obj1)
Return the number of elements in obj1 (string, list, tuple, set)
max(obj1)
Return the largest item in obj1
min(obj1)

Return the smallest item in obj1

round(x,y)
Round x to y decimals, y defaults to 0
BEWARE; In python 3x rounding does not work 'As taught in school'[2] but rounds half to even[3].

Use this to implement 'As taught in school' by overwriting the round() function.

def round(valuein, digits=None):
    import decimal
    value = str(valuein)
    if digits is None:
        try:
            digits = len(value.split('.')[1])
        except IndexError:
            digits = 0
    formatstring = '1.' + '1' * digits
    try:
        result = decimal.Decimal(value).quantize(decimal.Decimal(formatstring), rounding=decimal.ROUND_HALF_UP)
    except decimal.InvalidOperation:
        result = valuein
    return result
input([prompt])
Read and return input from standard input. Display 'prompt' first when provided.
int(string[,base=x)])
Convert str to an integer. Base = 2 converts bit-string presentation ('010101').
str(object)
repr(object)
Return a string representation of an object. str for the informal representation (just make it printable), repr for the formal representation (more formating??)

Boolean functions

Functions that just return True or False

isinsantce(var, type)
If a variable has the wanted type (list,set,int,str,dict)
isfile(filename)
If a file exists
any(<object>)
If any of the elements is True (any iterateble will do)
any(x in alist for x in aset)
If any of the elements of list are in set
all(<object>)
True if all elements of <object> are true (have a value)

Resursive functions

In resursive functions you should update the objects to return, not create new ones. Use augmented assignment (+=).

Other often used functions

Sleep function
import time
time.sleep(<sec>)