Sign InCoursewareNuggetsTutorials AboutClassesCodePad

Defining a Function

The night sky is beautiful above Kunlun Mountain -- there are thousands of shining stars scattered across the sky. Tali tries to draw the stars and galaxies. But there are so many of them. Can she draw one star and reuse the same code for drawing other stars? Yes! She can define a function that contains the code to draw a star.

import turtle t = turtle.Turtle() turtle.Screen().setup(600, 120) def draw_star(): # define a function called draw_star for side in range(5): t.forward(50) t.right(144) for num_stars in range(5): t.setx(50 * num_stars) draw_star() # call function draw_star() to run the code inside the function

A function is a piece of code that has been given a name. We can then use that code over and over again by calling the function's name in a program. We have used Python's built-in functions, such as print( ) or input( ). We have also used functions defined in the turtle module, such as forward( ) or right( ). Now we will learn how to create and use our own functions.

In Python, we define a function using the keyword def (short for define), followed by the name of the function, parentheses ( ), and a colon (:). The function body is the block of code immediately following this line. Make sure to indent the statements properly, just like the way we indent block of statements in a for loop.

def ❮function_name❯(): 
© CS Wonders·About·Classes·Cheatsheet