bembry.org
Home / Technology / Python / Notes

Lesson 8 Notes: Recursion, Fruitful Functions, and More

  • Preview …
    • Notes from recent work
    • Recycling Variables
    • Recursion
    • Functions that Give Back
    • Logical Operators and Boolean values
    • Notes on Program Development
  • Review
  • Notes From Recent Work
    • To print without space, concatenate:
    • print x+y+z
    • End all "if…elif" sequences with an "else."
    • To reuse a set of code, make it a function.
    • Think more to work less.
    • Avoid nesting "if" statements
    • Test code rigorously; test all scenarios and try to break the program.
  • Recycling Variables
    • Once a variable is created, its value can be reassigned.
    • Example:
      card_value = card1+card2
      if hit = = yes:
          card_value=card1+card2+card3
      else:
         pass
      print card_value
  • Recursion
    • Recursion is a function calling itself
    • Recursion allows function to be repeated
    • Example:
      def count(x):
         x = x+1
         print x
         count(x)
    • If function never stops, it is called an "infinite recursion"
  • Whoa!
    • To prevent infinite recursion, create a "base case".
    • "Base case" is the condition that will cause the function to stop calling itself
    • Example:
      def count(x):
      if x <100:
          x = x+1
          print x
          count(x)
      else:
         return
  • Functions that Give Back
    • Functions can be created that return a value to the program that calls it.
    • Example:
      def add_it(x,y):
         new = x + y
         return new
      sum = add_it(5,6)
  • Logical Operators
    • Conditional tests can be rolled together using keywords and, or, not
    • and : Both conditions must be met for test to be "true".
    • or : Either condition must be met for test to be "true".
    • not : Tests true if condition is not met.
    • With all conditional tests, Boolean results apply:
      • true = = 1
      • false = = 0 (or !=1)
  • Logical Operator Examples
    • if x>0 and x<10:
    • if y>0 and x>0:
    • if pwd=="code" or pwd=="monster":
    • if y>0 or x<0:
    • if not(x<y):
    • if x>y or not(x<0):
  • Alternative and Test
    • When testing values for < or >, these tests can be written as one test.
    • Example:
      if 0<x<100:
      if 1000>= x >= 0:
  • Developing Programs
    • Start by writing in your own words what the program should do.
    • Translate this description into a series of steps in your own words.
    • For each step, translate your words into Python code.
    • Have code print variables to test that they are giving the values you expect.
      Example: print "Num1 =", num1
  • Review
    • What is infinite recursion and how can it be avoided?
    • How do you make a function return a value to the main program?
    • What are "logical operators"?
    • What Boolean result is given for true/false?
Restricted access