Sign in

Intro to Computer Science / Unit 7: Functions

7.1 Defining and Calling Functions

3 practice questionsNot yet reviewed

Notes

A function is a named block of code that does one job. You define it with def and call it by name.

def greet():
print("Hello!")
print("Welcome.")

greet()
greet()
  • This prints both lines twice, because the function is called twice.
  • Defining a function does not run it. Nothing happens until you call it.
  • Functions make code reusable, shorter and easier to test.
  • Function names follow the same rules as variable names; the body is indented.

Practice

What does a def statement do?
How many lines are printed by the code above?
What is the main benefit of putting repeated code into a function?

Ready for more? Take the Unit 7 test.