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):OutPut:
print(name + " is programer");
myfunc("Ravi")
Ravi is programer
def myfunc(fname,lname):OutPut:
print(fname + " " +lname);
myfunc("Ravi","Sharma")
Ravi Sharma
def absolute_value(num):OutPut:
"""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))
2
4
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")
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)
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)
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