Welcome back, this is a second Python tutorial that is meant to cover building blocks of Python, click here for the first Python Building Block tutorial. These building blocks are meant to give you the tools to start building your own Python projects. In this Python tutorial we’ll be going over functions and classes.
How To Use Functions in Python
Functions are one of, if not the, most important building block you’ll be using in Python. From an object oriented programming point of view, we treat functions in Python like variables in algebra, phonemes in language, or nodes in graphs. In a broad sense, there are three parts of a function that you have to know in order to use them. 1) the function name, 2) the function parameters, and 3) the function return. Functions do not always need parameters or a return value, but always need a name.
Your function names should make sense, don’t name your function “x” or “a” or “blah”. If your function adds two numbers you should call it “add” or “adds_two_numbers”. There are two types of parameters you can pass, mandatory parameters and optional parameters. Mandatory parameters must be supplied when you call a function, Optional parameters may or may not be specified at the time you call a function, but must be passed when declaring the function.
# this is the basic make up of a function # you can pass optional parameters by giving them a preset value # it is customary to separate words with _ in Python def example_name(mandatory_parameter, optional_parameter=True): # do something here make sure you use your parameters if optional_parameter: abc = mandatory_parameter else: abc = "xyz" # return some value return abc # example of a function call example_name("abc")
Alright, so now that we’ve seen how to basically declare and call a function, let’s go over something a little more complex – recursive functions. Recursive functions are functions that call themselves. Recursive functions need a base case to return an actual value to avoid infinite recursion, which will stall your program at the best and crash your computer at the worst. I’ll show you the classic use case of a recursive function for the Fibonacci sequence.
# returns then n'th fibonacci number def fibonacci(n): if n == 0 or n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) # should return 1 fibonacci(1) # should return 2 fibonacci(2) # should return 55 fibonacci(9)
When should something be a function? Good question. Like I’ve been saying this whole time, functions are like building blocks. A function can be treated as a black box that takes and input and gives you an output. If there’s any order of operations that you want done on a set of variables then you want to use a function. If there’s any process you need to run more than once, then you want to use a function. Note that these rules for functions are not exclusive to Python. Python functions follow pretty much the same set of rules as functions in other mainstream languages.
How to use Classes in Python
Classes are how you create your own custom objects in Python. When doing object oriented Python programming, which is probably the most common use case in industry, you’ll want to create your own custom objects at a pretty regular interval. While I was working at Amazon, I created object classes all the time. A common pattern for creating classes is the Factory Pattern, which I’ll go over in a later session.
Classes in Python contain a special method called “__init__”. Double underscores at the front and back of a method name in Python indicate special, reserved name functions. The init function tells Python what the initial state of the class should be. Use this function to set values to different instance variables. In the following Python code example, we’ll create a “Student” class with an initial name. It is important to remember that all class functions should include self as a parameter, AND it should be the first parameter passed to the function. Class variables, static variables that belong to each member of a class regardless of the state, should be set outside of the init function.
# you do not have to specify that the class is an object, but I do class Student(object): class_variable = "example" def __init__(self, name): self.name = name # create a new student with the name Alice new_student = Student("Alice")
Let’s add a function to our Student class. We’ll add some functions around a “grade” class variable. We will add a grade variable set to None in the init class because grades vary from student to student. We’ll also add a “set_grade” function.
# you do not have to specify that the class is an object, but I do class Student(object): class_variable = "example" def __init__(self, name): self.name = name self.grade = None def set_grade(self, grade): self.grade = grade # create a new student with the name Alice new_student = Student("Alice") # set her grade to an "A" new_student.set_grade("A")
That’s it for the basics of using functions and classes. If you have any questions, drop them in the comments below, and check here for more Python tutorials. To learn more feel free to reach out to me @yujian_tang on Twitter, follow the blog, or join our Discord.
To learn more, feel free to reach out to me @yujian_tang on Twitter, connect with me on LinkedIn, and join our Discord. Remember to follow the blog to stay updated with cool Python projects and ways to level up your Software and Python skills! If you liked this article, please Tweet it, share it on LinkedIn, or tell your friends!
I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.DonateDonate monthlyDonate yearly