7.2. Defining Functions - How¶
The same syntax we use to name procedures can be used to define new functions. The only difference
is that a function will return a value. To return a value from a function use the Python
keyword return
followed by the value to return. The value can be a literal value like 3.14
or "Hello there"
, but will generally be a variable that we calculated within the function.
This is a definition for a function that accepts the lengths of the two legs (shorter sides) of a
right triangle as its parameters and calculates the length of the hypotenuse (long side). The final
value that it computes - sideC
is what gets returned.
Of course, running it right now does nothing. Just like a procedure definition, a function definition
does not cause anything to happen on its own. It is only the instructions for what to do when
someone calls hypotenuse_length
. So let’s add a call to the function. This working program
asks for the lengths of two sides from the user and then uses those two values a
and b
to
call hypotenuse_length
.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
Check Your Understanding