24
loading...
This website collects cookies to deliver better user experience
# define a function that says Hi.
def greet():
print("Hello")
#calling the function
greet()
#prints> Hello
# structure of a function
def function_name(paramters):
"""docstring"""
statement(s)
def
keyword, marks the beginning of a function """docstring"""
, to explain what the function does.return
(optional) statement that returns a value to the function.#function parameters
def greet(name, msg):
print(f"Hello {name}, {msg}")
#call the function with the arguments
greet('Mark', 'Good Evening')
#prints> Hello Mark Good Evening
greet()
has two parameters name, msg
parameters
are passed as arguments
.def greetings(name, msg="How are you?"):
print(f"Hello, {name} {msg}")
#positional arguments.
greetings('Asha')
#> Hello, Asha How are you?
msg
is provided in function call, it will overwrite the default argument.#keyword arguments in order
greetings(name="fast furious", msg="is out!")
#keyword arguments out of order
greetings(msg="is out!", name="Vin")
def greet(*names):
for name in names:
print(f"Hello {name}.")
greet('juma', 'larry', 'lilian')
#> Hello juma.
#> Hello larry.
#> Hello lilian.
def recurse():
#statements
recurse() #recursive call
recurse()
#finding the factorial of a number
def factor(x):
"""
this function finds the factorial of a given number
factorial number is the product of a
number starting from 1 to that number itself
"""
if x == 1:
return 1
else:
return (x * factor(x-1))
num = 3
print(f"factorial is: {factor(num)}")
#syntax:
lambda arguments: expression
#sum of numbers
sum = lambda x: x+2
print(sum(2))
#> 2+2= 4
#multiple args
product = lambda x, y: x*y
print(product(2, 6))
#> 2*6 = 12