3 Functions: Don’t repeat yourself!

 

In this chapter

  • Simon explains how to avoid repeating yourself (and why)
  • Erik writes his first Python function
  • Erik starts using Python’s interactive tool
  • Erik improves his function to make his receipt look professional

“Where did we stop yesterday?” Simon asked Erik the next day.

“You were going to tell me why bugs are called bugs,” Erik said.

“Right!” Simon said. “Believe it or not, many years ago, computers were made of electro-mechanical things called relays that had contacts similar to light switches. One day, the engineers discovered an error in their program. Their code was correct, but they found a bug stuck between the contacts in one of the relays. That’s why programmers call errors bugs. The bugs are usually hidden in your code, and you must remove them to make your program work. What else?”

“You said that I shouldn’t repeat myself. And you said we were going to write our own function today.”

“Right! First, tell me what you know about functions so far.”

“We used a couple of functions already,” Erik answered. “We used print() and input(). You said that somebody wrote them so we can use them. We can also use arguments with functions. We just have to put the arguments between the parentheses, and the function will do something with them, like print them.”

New things you have learned today

Code for this chapter