Title: 9
Course: Start programming with Python in 10 steps

Organise your code with functions and classes

By this point, you already know how to make your computer do many things for you. Still, you might find yourself writing the same instructions over and over again, and/or ending up with large Python files where it’s hard to remember the purpose of everything. That’s where functions and classes come in handy. We’ve already been using built-in functions such as print() and input() since Step 4. Now is the time to start creating your very own, make them cooperate and arrange them into classes. In short, now your code becomes structured and reusable.

👉    8 things to know at this step

1. You define a function by assigning a name to a block of code (similar to assigning a value to a variable). Once defined, your function can be called by anyone, just like you call built-in functions.
2. When you create a function, you can require one or more arguments, but you don’t have to. Your function, your rules!
3. Inside of your function, you can call a built-in function and write other pieces of code just like before.
4. It happens that you want to pass the result (the output) of your function to another function without printing it or saving it to a file. This is when you start using the return statement.
5. The libraries that you import are other people’s programs containing many useful functions and methods. You can import your own programs in the same way.
6. Since you can import your own programs like libraries, it is good to design smaller programs that perform one main task. Such programs are called modules.
7. Classes are higher-level and more abstract units than functions.
8. An important property of classes is that they can and need to be instantiated, while lower-level units such as functions are already instances (cannot be instantiated).

🧑‍🎓    Learn actively

▶️   Functions that you write yourself are just like the built-in functions that you already know, except that you get to choose everything: their name, their arguments/parameters (if any) and their output (action or information, or both). Follow this short video tutorial to create your first function:

📹   Defining a function by Martin Volk

▶️   Now, get started with making more complex functions by following the instructions in this notebook: functions.ipynb. Start by completing the Function definition section, which will highlight the basics of 1️⃣, 2️⃣, 3️⃣ and 4️⃣ for you.
❓ What are the arguments of each of the example functions? What is the output, and is it something you can print? Look at how the return statement is used.
Tip: By adding “=” and a value after an argument in the definition of your function, you can give this argument a default value. This makes the argument optional: your function will work even if you don’t give it a value in the call, as the default value will be used instead.

▶️   Try modifying the triangle_area() and the primes_list() functions so that one of the arguments becomes optional.

▶️   Complete the Local variables section of the notebook, then the Function calls and Recursion sections to see the true extent of the code that you can write inside a function. At some points, you will be asked to refer to the following animated demonstrations: function_calls.pptx and recursion.pptx.

▶️   Finally, complete the Doc strings section for one last useful trick with functions.

▶️   Read about 5️⃣ and 6️⃣ on W3Schools. This will teach you a few more useful tricks, like re-naming a module or importing only part of a module.
Tip: Any .py file that you have created until now can be considered a module! This is especially true of scripts containing functions and classes.

▶️   Then, read about classes and what they represent in this notebook: classes.ipynb. At one point, you will be asked to refer to the following animated demonstration: classes_and_objects.pptx.
❗  An object that belongs to a class is called an instance of that class. See how these are created in the notebook and how it relates to 8️⃣.
❗  As you see, classes are made up of functions, except that the functions within a class are called methods. There are some subtle differences between regular functions and methods, but the most important one is that you use different syntax to call them.
❗  There is no need for you to actually create your own classes at this point. However, it is important that you understand what classes are and how they can be used, should someone else give you their classes to work with.

▶️   Look at the Examples of classes section of the notebook. In both examples, try explaining what each method does. Then, try creating an instance of the class and calling the methods (you can do that in the same cell).

📝   You can also refer to the Python Tutorial on classes (especially section 9.3. A First Look at Classes).

❓   A famous author of a book about programming, Martin Fowler, once said: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." How do you think functions and classes can help with that? Think about the names that you chose for your functions. If you were to ask a programming colleague for help with a specific problem, how would they know where to look?

❓ Put the pieces together

1.  Be there or be square

Write a function called 'square' that, given a number as a parameter called 'num', will return the square of that number.

  - The head of the function should be 'def square(num):'.
  - Print 'square(3)', which should output 9.

2.  An immersive recursive experience

Write a function called 'number_seq' that prints all the numbers from 1 to 19 using only recursion for looping.

  - The function should accept a parameter called 'next_num'.
  - If 'next_num' is less than 20, print 'next_num' and call number_seq(next_num + 1).
  - Call 'number_seq(1)'.

3.  Going round in circles

Create a class for a circle with following specifications:

- It should have a "radius" instance variable.
- It should have a method for finding the area (𝜋𝑟2).
- It should have a method for finding the perimeter (2𝜋𝑟).
- Use math.pi for 𝜋.
- Test the class using the given code.

circley = Circle(4.0)
print('area (should be about 50.265):', circley.area())
print('perimeter (should be about 25.133):', circley.perimeter())




4.  Do it like it counts

Create a class called 'Counter' that implements a counting function.

- Its constructor should take no parameters except for 'self'.
- It should have a 'count' instance variable that is initialized to zero (do not use a parameter for it).
- It should have a method called 'next_number' for getting the next number which adds one to 'count' and then returns it.
- Test the class using the given code.

county = Counter()
print('next (should be 1):', county.next_number())
print('next (should be 2):', county.next_number())
print('next (should be 3):', county.next_number())