Course 5.2Lesson 1 of 6
A function is a group of lines with a name. The word def starts it, then comes the name, brackets and a colon, and the indented lines are its body. Defining a function only stores it, and calling it with its name and brackets runs the lines. A function can be called as often as you like, so you write the lines once. Functions avoid repeating, make a fix easy to do in one place, and make a program clear to read. A function that is defined but never called does nothing.
Try the code and the simulations beside the lesson.
After this lesson you can
def,You have used functions made by others: print(), len(), range(). You only had to know their names. You did not need to know how len() counts. A function is a group of lines with a name. You write the lines once. Then you use the name whenever you need them.
Think of a recipe in a cookery book. The book has the steps of "tea" once. When you want tea, you do not write the steps again. You say "make tea". A function is the recipe, and calling it is saying "make tea".
The name of a function follows the rules for the names of variables: small letters, words joined with _, and a name that says what the function does. greet is a good name. g1 is not.
This is the first thing to understand, and the most common mistake.
The function say_goodbye is defined, but the program does not show Goodbye!. Why? Because the function was never called. Only the last line of the program runs, and it is a print. To see Goodbye!, add the line say_goodbye() at the end. A function that is not called is like a recipe that nobody cooks.
Notice the brackets. say_goodbye alone, without brackets, is the name of the function, and does not call it. With brackets, say_goodbye() calls it.
Python reads from the top. A function must be defined before the line that calls it runs. If you call greet() on line 1 and define it on line 5, Python stops with NameError: name 'greet' is not defined. The usual style is: all the def blocks at the top, and the main program below them.
def only stores the recipe under a name. The brackets in greet() are what make it run.
Three reasons, and each will be useful in your own programs.
print_report() is easier to understand than thirty lines.There is a fourth reason, which you will feel later: you can test a function alone, and trust it afterwards.
greet does nothing, greet() runs.def line.IndentationError).def. A NameError.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
def name(): followed by indented lines defines a function. Defining does not run it.name() calls it and runs the lines.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
greet and greet()?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.