Function Arguments

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. When the function is called, we pass along a first name as argument.
def myfunc(name):
print(name + " is programer");

myfunc("Ravi")
OutPut:
Ravi is programer
def myfunc(fname,lname):
print(fname + " " +lname);
myfunc("Ravi","Sharma")
OutPut:
Ravi Sharma
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
OutPut:
2
4

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")

OutPut:

The youngest child is Linus

In this example, the order in which we specify the arguments is important. Otherwise, we get incorrect results.

def display(name, age, sex):
    print("Name: ", name)
    print("Age: ", age)
    print("Sex: ", sex)

display("Lary", 43, "M")
display("Lary","M",43)


def display(name, age, sex):
    print("Name: ", name)
    print("Age: ", age)
    print("Sex: ", sex)

display(name="Joan", age=24, sex="F")

display(age=43, name="Lary", sex="M")

Python passing parameters by reference
n = [1, 2, 3, 4, 5]
print("Original list:", n)

def f(x):
    x.pop()
    x.pop()
    x.insert(0, 0)
    print("Inside f():", x)
f(n)
print("After function call:", n)


No comments:

Post a Comment