Docsity

Standard C++ Library, Schemes and Mind Maps of C programming

Partial preview of the text

Download Standard C++ Library and more Schemes and Mind Maps C programming in PDF only on Docsity!

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 1 of 12

Go Back

Full Screen

Functions Re-visited

October 8, 2015 Brian A. Malloy

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 2 of 12

Go Back

Full Screen

1. Two Types

• The f(x) analogy is misleading because Python

functions may or may not return a value.

• display prints a value and then returns/leaves

• double computes a new value and returns

the newly computed result

def display(x): print "x is ", x

def double(x): return 2*x

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 4 of 12

Go Back

Full Screen

1.2. If we call it wrong: None

  • On line #4, we first call display,
  • and then try to print the returned value.
  • But no value is returned!
  • So Python returns special value: None

1 def display(x): 2 print "x is ", x 3 4 print display(12)

x is 12 None

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 5 of 12

Go Back

Full Screen

1.3. Missing return statement: None

  • Must supply a return value for every x
  • badAbs doesn’t have return if x is zero

1 def badAbs(x): 2 if x > 0: 3 return x 4 elif x < 0: 5 return -x 6 7 print badAbs(12) 8 print badAbs(-12) 9 print badAbs(0)

12 12 None

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 7 of 12

Go Back

Full Screen

2. Composition

• Composition is when one function calls an-

other function

• Compose means to “combine things”

• In the next example, display calls fixedAbs

• It’s as if display is composed of fixedAbs

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 8 of 12

Go Back

Full Screen

1 def fixedAbs(x): 2 if x < 0: 3 return -x 4 else: 5 return x

6 def display(x): 7 print fixedAbs(x), "is positive"

8 display(12) 9 display(-12) 10 display(0)

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 10 of 12

Go Back

Full Screen

3.1. Better Version of isEven

  • if x % 2 == 0 then x is even!
  • Recall, == is relational operator: it re-

turns a boolean value

1 def isEven(x): 2 return x % 2 == 0 3 4 print isEven(12) 5 print isEven(17) 6 print isEven(0)

True False True

Two Types Composition Boolean Functions Math Library

JJ II

J I

Slide 11 of 12

Go Back

Full Screen

4. Math Library

• Many functions available; consult:

https://docs.python.org/2/library/math.html

1 import math 2 3 def areaCircle(radius): 4 return math.pi * (radius**2) 5 6 print math.factorial(5) 7 print math.fabs(-5.3) 8 print math.pi 9 print areaCircle(5) 10 print math.sqrt( math.fabs(-3.0) )