O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required