def my_function():
  print("Hello from a function")
 
my_function()

output

Hello from a function

return = handing the answer back to the program so it can keep using it

def get_greeting():
  return "Hello from a function"
 
print(get_greeting())
Local VariablesGlobal Variables
Declared inside a functionDeclared outside a function
Cannot be accessed outside of functionCan be accessed in any function/

Recursive

  • Recursion is when a function calls itself.

  • contain base case (case that contain no further call to the recursive program) and recursive case

  • it must change its state and move toward the base case

  • Used when the task can be reduced to a simpler ver of itself

RecursiveIterative
Advantagecleanerless memory
easier to break into smaller parts
  1. Base case
    The condition that stops the recursion

!

  1. Recursive case
    The part where the function calls itself again
def countdown(n):
    if n == 0:
        print("Done")
        return
    
    print(n)
    countdown(n - 1)
 
countdown(5)

5
4
3
2
1

def countdown(n):
    if n == 0:
        print("Done")
        return ///base case
		else:
	    print(n)
	    countdown(n - 1) ///recursive case
 
n = int(input("input ur number: "))
countdown(n) //run the function again

return means:

“Stop the function RIGHT HERE and go back to where it was called.”

def factorial(n):
  # Base case
  if n == 0 or n == 1:
    return 1
  # Recursive case
  else:
    return n * factorial(n - 1)
 
print(factorial(5))
FUNCTION factorial(n : INTEGER) RETURNS INTEGER
 
    IF n = 0 OR n = 1
    THEN
        RETURN 1
    ELSE
        RETURN n * factorial(n - 1)
    ENDIF
 
ENDFUNCTION