Docsity

Functions - Computer Science - Lecture Notes, Study notes of Computer Science

Partial preview of the text

Download Functions - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Functions

Homework

  • HW 2 out (due Wed.)
  • Need to create a .zip file (to submit)

Dealing with complexity

Many problems in programming arrise when building large systems

  • programs that are thousands of pages long
  • programs so long no single person can keep them in their head at once
  • these systems are possible because of techniques for controlling complexity
    • what much of programming and computer science is about
  • black box abstraction is a key approach (used throughout engineering)

Basic Functions

A function creates a named black box out of sequence of statements

In python we use the def keyword to define a function def print_message_twice(): msg = "Hello World!" print(msg) print(msg)

  • Function names follow the same rules as variable names
  • The empty parentheses indicate the function does not take any arguments
  • The first line is called the function header
  • The rest is called the function body
  • The colon is required to separate the header and the body
  • Each statement in the body must be indented (the same amount)
  • The convention is to indent four spaces

Once defined, functions can be called by name

print_message_twice() Hello World! Hello World!

In a script, the function must be delcared before it is used

  • NameError: name ’print message twice’ is not defined

We can also obtain the type of a function

type(print_circle_area) <class ’function’>

Function Arguments and Parameters

Many functions take arguments

  • That is, values can be passed into the function when it is called
  • The number of arguments depends on the function definition
  • Arguments as literals, variables, or the results of expressions (more later)

Inside the function, arguments are assigned to parameters

  • The parameters are given in the function header
  • Only “visible” within the function body

A simple example of a function definition

def print_message_twice(msg): print(msg) print(msg)

To call the function, we pass in an argument

print_message_twice("Hello World!") Hello World! Hello World!

More on Functions

Functions must be delcared before called

print_message_twice("spam")

def print_message_twice(msg): print(msg) print(msg)

  • Results in an error: NameError: name ’print message twice’ is not defined

Unless the call is in the body of a function

  • For example, this is OK:

def print_messages_twice(msg): print_message_twice(msg) print_message_twice(msg)

def print_message_twice(msg): print(msg) print(msg)

print_messages_twice("spam")