INTRODUCTION |
You already know how to define a function with or without parameters and how to call it. From mathematics you probably know that there, functions are understood as something slightly different. In mathematics, a function y = f(x) has an independent variable x. For each value of x, the function returns a value of the dependent variable y. One example is the quadratic function:
You can also define functions in Python that calculate a value and then "return" it as a variable. |
THE KEYWORD RETURN |
from gpanel import * makeGPanel(-25, 25, -25, 25) def squarenumber(a): b = a * a return b for x in range(-5, 6): y = squarenumber(x) if x == -5: move(x, y) else: draw(x, y) |
MEMO |
With return, a function can return a value to the caller and stop further processing. Just as in mathematics, a function cannot return multiple values [more...
return is usually the last statement in the functions block. But this is not necessary. However, as you have seen, in contrast to mathematics, there are also functions in computer science that do not return a value but can still have an effect. Functions are even able to do both, cause something and return something [more... When you call such a function, the returned value must not be "picked up", you can therefore use a function with a return value as a command]. This graphical representation of the quadratic function is not very nice yet. In addition to the missing coordinate system, the graph's angular progression is also quite unpleasant. This is due to the fact that you only calculate the function at a few integer points that you connect with straight lines. This exposes an essential weakness of computer science compared to mathematics: Although the function delivers a y value for every value of the x-axis (for every real number), in computer science we can only calculate it at a finite number of points. We say that the continuous x-axis is dissolved into discrete points. |
DECIMAL NUMBERS (FLOATS) |
from gpanel import * makeGPanel(-6, 6, -3, 33) setColor("gray") drawGrid(-5, 5, 0, 30) def squarenumber(a): b = a * a return b setColor("blue") lineWidth(2) x = -5 while x < 5: y = squarenumber(x) if x == -5: move(x, y) else: draw(x, y) x = x + 0.01 |
MEMO |
In Python, decimal numbers are called float. Unlike in mathematics, decimal numbers in computer science always have a certain (finite) number of digits. In Python there are about 14 digits (in other programming languages such numbers are called double). One example in computer programming is that you can never exactly specify the number π (which is of course an infinite decimal fraction), because you would only get a precision of around 14 digits with a float. If you need a coordinate grid, you can do the following:
|
EXERCISES |
|