Chapter 3
Functions
Functions in Python allow you to break a task down into appropriate sub-
tasks. They are one of the powerful tools of abstraction that higher-level pro-
gramming 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 ...
Get A Concise Introduction to Programming in Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.