Movatterモバイル変換


[0]ホーム

URL:


Python for Beginners2015.11.01

Functions with parameters

Introduction

As we shrink down our code and add functions to remove duplication, wearefactorizing it. This is a good thing to do. But the functions wehave defined so far are not very flexible. The variables are definedinside the function, so if we want to use a different angle or adistance then we need to write a new function. Our hexagon function canonly draw one size of hexagon!

That is why we need to be able to give parameters, also calledarguments, to the function. This way thevariables in thefunction can have different values each time we call the function:

Remember how we defined the functionline_without_moving() in the previoussection:

defline_without_moving():turtle.forward(50)turtle.backward(50)

We can improve it by giving it a parameter:

defline_without_moving(length):turtle.forward(length)turtle.backward(length)

The parameter acts as avariable only known inside the function’s definition.We use the newly defined function by calling it with the value we want theparameter to have like this:

line_without_moving(50)line_without_moving(40)

We have been using functions with parameters since the beginning of thetutorial withturtle.forward(),turtle.left(), etc...

And we can put as many arguments (or parameters) as we want, separating themwith commas and giving them different names:

deftilted_line_without_moving(length,angle):turtle.left(angle)turtle.forward(length)turtle.backward(length)

A parameterized function for a variable size hexagon

Exercise

Write a function that allows you to draw hexagons of any size you want, eachtime you call the function.

Solution

defhexagon(size):for_inrange(6):turtle.forward(size)turtle.left(60)

A function of several parameters

Exercise

Write a function that will draw a shape ofany number of sides (let’s assumegreater than two) of any side length. Get it to draw some different shapes.

Here’s an example of drawing shapes with this function:

_images/shapes.png

Tip

The sum of the external angles of any shape is always 360 degrees!

Solution

defdraw_shape(sides,length):for_inrange(sides):turtle.forward(length)turtle.right(360/sides)

Bonus

It might sound crazy, but it’s perfectly possible to pass afunction as a parameterto another function! Python regards functions as perfectly normal ‘things’, the same asvariables, numbers and strings.

For instance, you could create a shape drawing function which turned one way or anotherdepending on which turtle function you passed to it -turtle.left orturtle.right.

See if you can implement this!

Note

Passing a function (e.gturtle.left) is different thancalling it, whichwould instead be writtenturtle.left(45).


[8]ページ先頭

©2009-2025 Movatter.jp