Parametros - johncroth/pythonEd2024 GitHub Wiki

Last lesson we saw a function like this:

def dibujar_triangulo():
    for i in range(0,3):
        forward(80)
        right(120)

It drew an equilateral triangle with sides of length 80. If we want a different size triangle, we'd have to write another function. But no, there is a better way. Save and execute the following program in param_a.py:

from turtle import *

def dibujar_triangulo( longitud ):
    for i in range(0,3):
        forward(longitud)
        right(120)

dibujar_triangulo(40)
dibujar_triangulo(60)
dibujar_triangulo(80)
dibujar_triangulo(50)

The "parameter" longitud works like a variable within the body of the function. We have to give it a specific value when we call the function, like dibujar_triangulo(40), and the function will use the value 40 in place of longitud.

Multiple parameters

We can use as many parameters as we like in the definition of the function. Save and execute the following in param_b.py, which defines a function that draws a regular polygon with the given number of sides and length, and then uses it to draw 3 different shapes.

from turtle import *

def dibujar_polygon( longitud, lados):
    for i in range( lados ):
        forward( longitud )
        right( 360 / lados )

dibujar_polygon( 100, 4 )
dibujar_polygon( 40, 12 )
dibujar_polygon( 150, 5 )

Nested functions

Once you have defined a function, you can call it from within other functions.

from turtle import *

def dibujar_polygon( longitud, lados):
    for i in range( lados ):
        forward( longitud )
        right( 360 / lados )

def dibujar_cuadrado( longitud ):
    dibujar_polygon( longitud, 4 )

def dibujar_triangulo( longitud ):
    dibujar_polygon( longitud, 3 )

dibujar_cuadrado( 40 )
dibujar_triangulo( 80 )
dibujar_polygon( 150, 5 )

Ejercicios

With a function with two parameters def saltarXy(x,y) lift the pen, jump to a given point on the screen, and replace it. Use it to draw triangles at 4 points.

  1. Draw random regular polygons of random side length between 30 and 60 and random number of sides between 3 and 10

  2. In xxx.py, write a function def total(lista): that takes a list of numbers and prints out their sum. Test it by printing out the sums of the following lists:

a = [ 6, 5, 4, 3, 2, 1] # total es 21
b = [ 100, 101, 102] # total es 303
c = [ 1, 1, 1, 1, 1, 1, 1, 1 ] # total es 8
  1. Median of a list of numbers

  2. sqrt and hypotenuse.

  3. improve the "dibujar_casa" function by letting the user supply the height and width of the box.