Chapter 3

Functions

Functions in Python allow you to break a task down into appropriate subtasks. They are one of the powerful tools of abstraction that higher-level programming languages provide. Ideally, every function has a single, well-defined purpose.

Consider this example, which uses the sqrt() function from the math module to implement hypot(), also in the math module.

Listing 3.1: Hypotenuse

 1 # hypot.py
 2
 3 from math import sqrt
 4
 5 def myhypot(x, y):
 6 return sqrt(x ** 2 + y ** 2)
 7
 8 def main():
 9 a = float(input("a: "))
10 b = float(input("b: "))
11 print("Hypotenuse:", myhypot(a, b))
12
13 main()

Each chapter, as we begin with a new example, type the program in to your programming environment (such as IDLE), save it with ...

Get A Concise Introduction to Programming in Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.