Your example demonstrates how to declare and use a function with a parameter, but not why they should do so.
Actually, there are no reason (for them) why they should bother with a new concept (function) instead of writing
name = input("Enter your name: ")
print("Hello " + name)
which can be done with the programming elements they already know. And is both shorter and simpler,
So, how to sell functions with parameters to beginners?
- they avoid code duplication (the example should contain several calls)
- they are called with different values (so parameters is the simplet way to transmit information)
- they implement a decomposition of tasks into subtasks (the sooner they practice the procedural approach, the better)
Here is an example:
def draw_line(width, end, middle):
line = end + middle*(width-2) + end;
print(line)
def draw_rect(height, width):
draw_line(width, "+", "-")
for line in range(height-2):
draw_line(width, "|", " ")
draw_line(width, "+", "-")
def draw_square(side):
draw_rect(side, side)
def main(args):
draw_square(3)
draw_square(5)
draw_square(7)
Actually, I use Processing with a group of students. Most of them total beginners. The first motivation for functions is decomposition.
After they draw a simple figure with a few predefined function calls, as fill()
to select a fill color, rect()
and ellipse()
, they are taught to split the work into user-defined functions
void draw() {
draw_sky();
draw_beach();
draw_sunset();
}
and parameters are then used for similar parts occurring at different places
void draw_seabird(int x, int y) {
....
}