def followed by the function name and input parameters in parenthesesreturn to specify the output value(s) of the functiondef add_numbers(x, y):
result = x + y
return result
To call a function, use its name followed by input values in parentheses The function returns the output value(s), which can be stored in a variable or used directly
sum = add_numbers(2, 3)
print(sum)
5
def greet(name, greeting = "Hello"):
print(greeting + ", " + name)
greet("Alice")
Hello, Alice
greet("Bob", "Hi")
Hi, Bob
def add_numbers(*args):
result = 0
for num in args:
result += num
return result
add_numbers
<function __main__.add_numbers(*args)>
add_numbers(1, 2, 3)
6
add_numbers(1, 2, 3, 4, 5)
15
def add_numbers(*args):
"""
Computes the sum of n numbers
Parameters:
args: A tuple of numbers
Returns:
int: The sum
"""
result = 0
for num in args:
result += num
return result
help(add_numbers)
Help on function add_numbers in module __main__:
add_numbers(*args)
Computes the sum of n numbers
Parameters:
args: A tuple of numbers
Returns:
int: The sum
double = lambda x: x * 2
print(double(3))
6
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
120
global_var = 10
def my_func():
local_var = 20
print(global_var)
print(local_var)
my_func()
10 20
print(global_var)
10
print(local_var)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[15], line 1 ----> 1 print(local_var) NameError: name 'local_var' is not defined
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: division by zero")
else:
return result
print(divide(10, 5))
2.0
print(divide(10, 0))
Error: division by zero None