In Python, functions are defined as follows:
def addTwoNumbers(a, b):
return a + b
x = 3
y = 4
result = addTwoNumbers(x, y)
print(‘The sum of {} and {} is {}’.format(x, y, result))
Python also supports setting default values for the input parameters. Example:
def addTwoNumbers(a = 3, b = 2):
return a + b
result = addTwoNumbers()
print(‘The result of addTwoNumbers() is: {}’.format(result))
result = addTwoNumbers(4)
print(‘The result of addTwoNumbers(4) is: {}’.format(result))
Shorthand lambda functions are defined as follows:
result = lambda a, b : a + b
print(‘The result of lambda a, b is: {}’.format(result(3, 4)))
Functions with variable length parameters are defined as follows:
def addNumbers(*argv):
result = 0
for arg in argv:
result += arg
return result
result = addNumbers(1, 2, 3)
print(‘The result of addNumbers(1, 2, 3) is: {}’.format(result))
Leave a Reply
You must be logged in to post a comment.