This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Functions



Functions allow us to reuse bits of code. For example, say that we are calculating tax on transactions. We can wrap up our code in a functional unit and give it a name:

def calculate_tax(price, tax):
    sales_tax = price * tax
    total = price + sales_ tax
    return total

From then on we can just call that name and pass it some information (called arguments):

calculate_tax(53.79, 0.075)

This will save us time as well as make our code easier to review. Lets take a look at some more in-depth learning resources.

Learning Resources

Python for Informatics


Dive Into Python3:


Practice

Post chapter excercises and questions below.

Q:  What is an example of a machine or process that takes external input and returns a modified output?

Q: How many tasks do you think that an individual function should generally perform?


 

Task Discussion


  • Fer said:

    diveintopython3.org is DOWN

    Exercise 4.4

    Answer is B, exactly it's the start of a function DEFINITION

    C could be taken as right since you define a function to be used later on. so D would be right then

     

    Exercise 4.5

    The right would be

    ABC

    Zap

    ABC

    So the closest answer is D

     

    Exercise 4.6

    # -*- coding: iso-8859-15 -*-
    horas = int(raw_input("Enter hours:"))
    precio = float(raw_input("Precio / hora"))

    def paga(horas,  precio):
        if horas > 40:
            extra = horas - 40
            payment = (40 * precio) + ((extra * precio) * 1.5)
        else:
            payment = horas * precio
        
        return payment

    print paga(horas,  precio)

    Exercise 4.7

    # -*- coding: iso-8859-15 -*-

    nota = raw_input("Introduce nota ")

    def grado(nota):
        if nota > 1  or nota < 0:
            grade = 'None'
        elif nota >= 0.9 :
            grade = 'A'
        elif nota >= 0.8 :
            grade = 'B'
        elif nota >= 0.7 :
            grade = 'C'
        elif nota >=0.6 :
            grade = 'D'
        else :
            grade = 'F'
        return grade
        
    try:
        nota = float(nota)
        print "El grado es "+grado(nota)
    except:
        print "solo numeros!"

    on Nov. 7, 2013, 5:44 a.m.
  • Wouter Tebbens said:

    Exercise 4.4. b is a correct  answer, though if we understand that a function is something that is to be "stored for later", then we can say d is correct as well.

    Exercise 4.5: d is correct: though the output will be three lines:

    ABC
    Zap
    ABC

    Exercise 4.6. see program here: http://pastebin.com/BHyqB4qg

    Exercise 4.7: see here: http://pastebin.com/0t0h7DsR

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    an amplifier takes a signal and according to the level of amplification requested it amplifies that signal.

    Q: How many tasks do you think that an individual function should generally perform?
     

    At least one task: with only one task it can make sense already to build a function, so we can easily reuse it.

    on March 26, 2013, 8:32 a.m.

    Anonym said:

    I am away for a short period. I will endeavour to respond to your email when I return. If you don't hear from me in a couple of weeks or so, please send me a reminder.
    on March 26, 2013, 9:13 a.m. in reply to Wouter Tebbens
  • drediamond said:

    One?

    on Dec. 16, 2012, 11:49 p.m.

    cstsupport said:

    Greetings from Ireland during this festive season. Thank you for contacting me. I am currently out of the country with very limited access to my email, from Wednesday December 12th until Friday December 21st. If you have any urgent queries, please contact Ms. Aoife Hayes at aoife.hayes@cst-international.com Until then I look forward to responding to your queries upon my return. Warmest Regards, Rosetta Talley
    on Dec. 16, 2012, 11:52 p.m. in reply to drediamond
  • drediamond said:

    A microphone

    on Dec. 16, 2012, 11:34 p.m.

    cstsupport said:

    Greetings from Ireland during this festive season. Thank you for contacting me. I am currently out of the country with very limited access to my email, from Wednesday December 12th until Friday December 21st. If you have any urgent queries, please contact Ms. Aoife Hayes at aoife.hayes@cst-international.com Until then I look forward to responding to your queries upon my return. Warmest Regards, Rosetta Talley
    on Dec. 16, 2012, 11:36 p.m. in reply to drediamond
  • saravanan said:

    Chapter 4

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    computers.

    Q: How many tasks do you think that an individual function should generally perform?

    Only one task for better reuse and better output

    on Sept. 10, 2012, 12:21 p.m.
  • Rob said:

    My chapter 4 answers:

     

    http://pastebin.com/L6eEqdc9

     

    on Sept. 8, 2012, 8:05 p.m.
  • ionut.vlasin said:

    Exercise 4.4 b

    Exercise 4.5 d

    Exercise 4.6 http://pastebin.com/aywCNjCc

    Exercise 4.7 http://pastebin.com/TQ9TviG8

    on July 11, 2012, 4:08 a.m.
  • jeroenrijckaert said:

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    A1: Coffeemachine. Burned coffee beans, water and power as input. Hot coffee as output.

    Q: How many tasks do you think that an individual function should generally perform?

    A: 1 task only, but it might be applied as part of different solutions to lots of problems.

    on June 27, 2012, 3:05 p.m.
  • pannix said:

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    calculator

    Q: How many tasks do you think that an individual function should generally perform?

    preferably one

    PS: The Dive into Python3 links are broken.

    on May 11, 2012, 12:09 p.m.
  • Ken Doman said:

    My Ch. 4 Answers:

    Chapter 4 answers

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    An ice machine takes in water and electricity, and returns ice



    Q: How many tasks do you think that an individual function should generally perform?

    As few as possible to get the job done

    on Jan. 17, 2012, 1:29 p.m.
  • Evita said:

    The exercises(4.4 - 4.7) :

    http://pastebin.com/QNxwWZFw

     

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    A: A calculator, a computer.

    Q: How many tasks do you think that an individual function should generally perform?

    A: Less is best, even one if possibly.

    on Oct. 11, 2011, 7:48 p.m.
  • NamKeph said:

        Exercise 4.4:   b
        Exercise 4.5:   d
        Exercise 4.6 - 4.7
            http://pastebin.com/0t1p5bwW
        Q:  What is an example of a machine or process that takes external input and returns a modified output?
            any vending machine
        Q: How many tasks do you think that an individual function should generally perform?
            ideally, only one
     

    on Oct. 7, 2011, 4:47 a.m.
  • Mars83 said:

    • Exercise 4.4:
      • b)
    • Exercise 4.5:
      • d)
    • Exercise 4.6:
    • Exercise 4.7:
    • Diveintopython3:
      • Link broken? # Edit: Server seems to be down
    • Q:  What is an example of a machine or process that takes external input and returns a modified output?
      • ATM (bank machine)
    • Q: How many tasks do you think that an individual function should generally perform?
      • as few as possible, in the best case only one task
    on Oct. 4, 2011, 7:22 p.m.
  • Sage Ross said:

    on Oct. 3, 2011, 11:26 p.m.
  • dean said:

    My answers:

    http://goo.gl/2EE55

    on Oct. 2, 2011, 5:48 p.m.
  • emilfos said:

    Ex. 4.4

    The purpose of 'def' is to indicatethe start of  a function.

    It prints out:

    'ABC'
    'Zap'
    'ABC'

    Ex. 4.6

    http://pastebin.com/MxTnKWsJ

     

    Ex. 4.7

    http://pastebin.com/dGyZ0B2U

    on Sept. 27, 2011, 12:19 p.m.
  • Zolomon said:

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    A: A game!

    Q: How many tasks do you think that an individual function should generally perform?

    A: One, and it should perform it well!

     

    Exercise solutions: https://gist.github.com/1063934

    on July 4, 2011, 4:58 p.m.
  • Dan R said:

    Q1 - A vending machine

    Q2 - One

    Ex 4.4:

    hours = raw_input('Enter hours: ')
    rate = raw_input('Enter rate: ')

    try:
        hours = float(hours)
        rate = float(rate)
    except:
        print('Unable to process data')

    def pay(hours, rate):
        if (hours > 40):
            pay = (40 * rate) + ((hours - 40) * rate * 1.5)
        else:
            pay = (rate * hours)
        return pay

    print(pay(hours, rate))

    Ex 4.5

    score = raw_input('Enter the score: ')

    def grade(input):
        try:
            input = float(
    input)
            if(
    input > 1 or input < 0):
                return 'Bad score'
            elif (
    input > 0.9):
                return 'A'
            elif (
    input > 0.8):
                return 'B'
            elif (
    input > 0.7):
                return 'C'
            elif (
    input > 0.6):
                return 'D'
            elif (
    input <= 0.6):
                return 'F'

            else:
                return 'Bad score'
        except:
            return 'Bad score'

    print(grade(score))
          

    on June 26, 2011, 1 a.m.
  • Sudaraka Wijesinghe said:

    My py4int exercise 4 code

    Exercise 4.4

    # Payment calculation
    def calculate_pay(hours, rate):
        if hours > 40 :
            pay = rate * 40 + rate * 1.5 * (hours - 40)
        else:
            pay = hours * rate
    
        return pay
    
    
    # Get hours from the user
    hours = raw_input('Enter number of ours: ')
    
    # Get rate from the user
    rate = raw_input('Enter rate per hour: ')
    
    # Calculate pay
    try:
        f_hours = float(hours)
        f_rate = float(rate)
    except:
        print 'You entered non numeric values'
        quit()
    
    # Calculate pay/bonus
    pay = calculate_pay(f_hours, f_rate)
    
    # Output calculated pay
    print 'Gross pay:',pay
    
    
    

    Exercise 4.5

    # Grading function
    def computegrade(score):
        if 0.9 < score :
            return 'A'
        elif 0.8 < score :
            return 'B'
        elif 0.7 < score :
            return 'C'
        elif 0.6 < score :
            return 'D'
        else:
            return 'F'
    
    # Get score from user
    inp = raw_input('Enter score: ')
    try:
        score = float(inp)
    except:
        print 'Bad score'
        quit()
    
    # Make sure score is less than one
    if 1 < score or 0 > score :
        print 'Bad score'
        quit()
    
    grade = computegrade(score)
    
    print grade
    
    
    

    Q:  What is an example of a machine or process that takes external input and returns a modified output?

    Calculator


    Q: How many tasks do you think that an individual function should generally perform?

    There would be some situations where you need to group several tasks into a single group/unit. However best practice is to keep the tasks performed by a function to a smaller count if not one.

    on June 25, 2011, 1:14 p.m.
  • Vladimir Támara Patiño said:

    4.1 Prints a different sequence of 10 random numbers, each between 0 and 1

    4.2 NameError: name 'repeat_lyrics' is not defined

    4.3 NameError: global name 'print_lyrics' is not defined

    4.4

    def compute_pay(hours, rate):
        pay = hours*rate
        if (hours>40.0):
            pay = pay + (hours-40)*rate*0.5
        print "Pay", pay
        return pay
    
    try:
        hours = float(raw_input('Enter Hours: '))
        rate = float(raw_input('Enter Rate: '))
        print "Pay: ", compute_pay(hours, rate)
    except:
        print "Error, please enter numeric input"
    

    4.5

    def compute_grade(s):
        if (s > 1.0 or s<0.0):
            return 'Bad score'
        elif (s > 0.9):
            return 'A'
        elif (s > 0.8):
            return 'B'
        elif (s > 0.7):
            return 'C'
        elif (s > 0.6):
            return 'D'
        else:
            return 'F'
    
    try:
        s = float(raw_input('Enter score: '))
        print compute_grade(s);
    except:
        print 'Bad score'
    

    Q:  What is an example of a machine or process that takes external input and returns a modified output? Blender

    Q: How many tasks do you think that an individual function should generally perform? One

    Clarifications

    No errors found in chapter 4 of Py4Inf. From it, just want to highlight it calls arguments the values passed to a function during function call and parameters the variable names used in the definition of the function.

    Regarding section 1.2 of DIP, I would not talk about "declaration of functions" but "definition of functions."

    Other information:

    In Python there is no declaration of functions, but it is possible to use a forward defined function B in a function A as long as the calling of function A occurrs after the definition of function B. i.e the following prints 15:

    # Based on discussion at http://code.activestate.com/lists/python-list/336892/
    
    def A(x):
        return B(x)
    
    def B(x):
        print x
    
    A(15) 
    

    def is like an assignment, the last assigned value that is evaluated is the one used. The following example prints 2

    def op(x):
        print x
    
    def op(x):
        print x+1
    
    op(1);
    

    on June 1, 2011, 6:21 a.m.