22
loading...
This website collects cookies to deliver better user experience
# define a basic function
def func1():
print("I am a function")
func1()
print(func1())
print(func1)
I am a function
I am a function
None
<function func1 at 0x0000025C054DBF70>
I am a function
got printed, and then the same string followed by the word None
, and then finally this string 0x0000025C054DBF70
. So in the first case, the function is being called directly, which executes the contents of the function, causing the print statement to print the string. In the second case, the function is also being called inside the print function, so the output is the same as in the first case, but then the outer print statement executes, and since our function doesn't return a value, Python evaluates the return value to be the Python constant of none, and then just prints the string representation of that. In the last case, the function itself is not being executed at all since we're not including those little parentheses that would call the function. We're just printing the value of the function definition itself, which evaluates to this string 0x0000025C054DBF70
. This just demonstrates that functions themselves are objects that can be passed around to other pieces of Python code.# function that takes arguments
def func2(arg1, arg2):
print(arg1, arg2)
# function that returns a value
def cube(x):
return x * x * x
func2(10, 20)
print(func2(10, 20))
print(cube(3))
10 20
10 20
None
27
# function with default value for an argument
def power(num, x = 1):
result = 1
for i in range(x):
result *= num #result*=num is same as result=result*num
return result
print(power(2))
print(power(2, 3))
print(power(x = 3, num = 2))
2
8
8
print(power(2))
I'm calling the function power, but I'm not giving it a value for x, so x is going to default to one.print(power(x = 3, num = 2))
I'm reversing the order in which the arguments are called. So Python lets you call functions with their named parameters along with their value, and when you do this, the Python interpreter figures out which arguments to supply the values to. You don't have to call the function with the arguments in a particular order, if you simply supply the names along with the values.#function with variable number of arguments
def multi_add(*args):
result = 0
for x in args:
result += x
return result
print(multi_add(1, 2, 3))
print(multi_add(1, 2, 3, 10))
print(multi_add(1, 2, 3, 10, 16))
6
16
32