Programming in Python

BEES 2023

Agenda

  • Functions
    • Function definitions and function calls
    • Docstrings
    • Return values
    • None and the default return value
    • The stack: getting to grips with functions and control flow
    • A few common mistakes about functions
  • Functions perform some task - mini program

    • May take arguments/parameters

    • My return a value that can be used late

  • Functions are a convenient way of organizing and structuring the code.

 

 

 

Functions

Function Definition

Calling a function

Function Example

docstring Example

return value Example

Yet another Example

Use of return for control flow

return in all flows

return as a substitute for break

None

  • None is a "null" value.

  • If you don't return something, the function returns None

x = print("hello")

print(x)

def helloWorld():
  print("Hello, world!")
  return None
  
x = helloWorld()

print(x)

Function stack

Few mistakes

# Return and print are not the same:

def sum(x, y):
  return print(x + y)


z = sum(5, 10)

print("The return value is:", z)
# Global variables are not function arguments

kilos = 11

def kilos_to_pounds(kilos):
  return kilos * 2.205


kilos_to_pounds(10)

Lecture 5 challenge

Questions?

BEES 2023 - Lecture 5

By Narges Norouzi

BEES 2023 - Lecture 5

  • 200