Functions in Python: Output
Functions in Python: Output
A function is a set of statements that take inputs, do some specific computation and
produces output. The idea is to put some commonly or repeatedly done task
together and make a function, so that instead of writing the same code again and
again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own
functions. These functions are called user-defined functions.
# A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd
Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a reference. When
we pass a variable to a function, a new reference to the object is created. Parameter
passing in Python is same as reference passing in Java.
Keyword arguments:
The idea is to allow caller to specify argument name with values so that caller does
not need to remember order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname ='Geeks', lastname ='Practice')
student(lastname ='Practice', firstname ='Geeks')
Output:
('Geeks', 'Practice')
('Geeks', 'Practice')
Variable length arguments:
We can have both normal and keyword variable number of arguments. Please
see this for details.
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output:
Hello
Welcome
to
GeeksforGeeks
# Python program to illustrate
# *kargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks')
Output:
last == Geeks
mid == for
first == Geeks
Anonymous functions: In Python, anonymous function means that a function is
without a name. As we already know that def keyword is used to define the normal
functions and the lambda keyword is used to create anonymous functions. Please
see this for details.
# Python code to illustrate cube of a number
# using labmda function
cube = lambda x: x*x*x
print(cube(7))
Output:
343