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

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.

## 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?

• ### 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 ")

if nota > 1  or nota < 0:
elif nota >= 0.9 :
elif nota >= 0.8 :
elif nota >= 0.7 :
elif nota >=0.6 :
else :

try:
nota = float(nota)
except:
print "solo numeros!"

• ### 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.

### 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

One?

### 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

A microphone

### 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:

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

• ### Rob said:

http://pastebin.com/L6eEqdc9

• ### 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

• ### 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.

• ### 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.

• ### Ken Doman said:

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

• ### Evita said:

The exercises(4.4 - 4.7) :

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.

• ### 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

• ### 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

• ### 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

Ex. 4.7

• ### 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

• ### 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: ')

try:
input = float(
input)
if(
input > 1 or input < 0):
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:
except:

• ### 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
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:
quit()

# Make sure score is less than one
if 1 < score or 0 > score :
quit()

```

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.

• ### 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):
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: '))
except:
```

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);
```