Here is an example:
my_number = max(3, 4, 2) # calling the function with 3 arguments and assigning the result to a variable
print(my_number) # also print is a function
4
def
keyword, followed by the function namereturn
statement, followed by the return value(s)# Define a function that takes two arguments and returns the bigger one
def bigger_of_two(a, b):
if a > b:
return a
else:
return b
# Call the function with two arguments and print the result
print(bigger_of_two(4, 3))
4
x = 8
def some_function():
print("Value from outer scope:", x) # x is accessible from the inner scope
y = 3
print("Value from same scope:", y) # y is not accessible from the outer scope
some_function()
print("Value from inner scope:", y)
Value from outer scope: 8 Value from same scope: 3
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[4], line 8 5 print("Value from same scope:", y) # y is not accessible from the outer scope 7 some_function() ----> 8 print("Value from inner scope:", y) NameError: name 'y' is not defined
def get_min_max(list):
minimum = min(list)
maximum = max(list)
return minimum, maximum # returning multiple values
list_min, list_max = get_min_max([1, 2, 3, 4, 5]) # multiple assignment (first value goes to a, second to b)
print(list_min)
def default_argument(a, b, c=3): # default value for c
return a + b + c
print(default_argument(1, 2)) # c will be 3
def arbitrary_argument(*args): # variable number of arguments
sum = 0
for a in args:
sum += a
return sum
print(arbitrary_argument(1, 2, 4, 6))
import module_name
statement.
operatorimport math # importing a module
math.sqrt(16) # using a function from the module
module.submodule
(according to the folder structure)module.submodule.function()
as
keyword: import folder.module as mod
import pandas.plotting as pdp # importing a submodule
pdp.lag_plot() # using a function from the submodule
pip install <module name>
pip install pandas
if you have several Python versions you may have to use the specifice pip command
pip3 install <module name>
x = 1
def namespaces():
def subspaces():
z = 3
print(pow(3,2)) # access namespaces from the built-in scope
print(x) # access x from the global scope
print(y) # access y from the enclosing scope
print(z) # access z from the local scope
y = 2
subspaces()
print(y) # access y from the local scope
print(z) # z is not accessible from the outer scope (NameError)
namespaces()
9 1 2 3
def namespaces():
def subspaces():
x = 2 # x is now a local variable
print(x)
x = 1 # x is a local variable of namespaces
subspaces()
print(x)
namespaces()
2 1