In this article, let us learn about the “def” keyword in Python with the help of some examples.
The very fact that you have googled and found this article shows that you are a keen learner who thinks differently!
Keep it up and I am sure you will become a master craftsman in the world of Python in no time at all!
For those of you in a hurry, here is a short version of the answer.
Python’s “def” Keyword Cheatsheet
What is the meaning of the “def” keyword? The keyword “def” is short for the word “define” and it is used to signify the beginning of a function definition in Python.
Here is a short example of the usage of the “def” keyword in Python.
def print_hello(): print("Hello Inventors!")
If this short answer still leaves you with an “incomplete” feeling, then don’t worry as this answer is aimed at people who just want to refresh their memories!
This article is specifically crafted keeping beginners in mind, so if you are feeling confused, forget that you ever read the paragraphs above, find a quiet place, focus for the next 10 to 15 minutes and read the rest of the article, then come back and read the answer above, I guarantee that will make more sense!
Let us start our journey by learning some fundamental concepts that are needed to understand the “def” keyword!
Fundamentals Needed Before You Can Understand The “def” Keyword
I have used the term “keyword” a lot above, but what does “keyword” mean?
Keywords are the “Building Blocks” of Python
The basic building block of any human language is words, the same is true for computer languages too!
Words are used to make sentences and sentences are used to get your idea across to the person you are communicating with.
Take a look at the words below.
Only the word “YES” can be found in an English dictionary, other words even though they make sense to us are not what is considered as “formal”.
This is because, while a native or a fluent English speaker might understand words like “aargh” not everyone will!
Our computers vocabulary is limited to just 2 words: 0 and 1.
Since we can’t write all our instructions to the computers in binary, we invented computer languages (like our “Python”)
Using computer languages
- we can write our instructions in a way that is more comfortable for us,
- then let a compiler translate that to 0’s and 1’s and
- then eventually let the computer execute our instructions!
The vocabulary of such computer languages even though much larger than just 0 and 1, they are still nowhere near to that of humans.
The words in the vocabulary of computer languages are called tokens
These “tokens” are parsed (“parsed” is software slang for “understood”) one by one by Python as our code is executed.
These “tokens” can be classified into the following categories
- operators and
Similar to the way that we make sentences using words, in computer languages, the “tokens” above are used to make “statements“.
>>> a = 10
In the line above:
- “a” is an identifier,
- “=” is an operator, and
- “10” is a integer literal
There are no keywords or delimiters in the line above but we will get to that in a second.
“Keywords” are tokens that are reserved for “special” uses and we cannot use them as variable names.
For example, we cannot use keywords like “if” like this
>>> if = 10 File "<input>", line 1 if = 10 ^ SyntaxError: invalid syntax
The only way to use the word/token “if” and “else” in our Python program is to use them when we need to run some code conditionally as shown in the example below.
a = 10 if a == 10: print ("a is equal to 10") else: print("a is not equal to 10")
Here the keywords “if”, “elif” and “else” are used to tell the python program that we want to do some condition checking and proceed to execute only select lines based on what the condition evaluates to.
A Challenge for you!
Before looking at the output, I want to challenge you to compute in your heads and predict what the code will print!
These thinking exercises will condition your brain to think like a programmer!
Are you ready? Okay, time for the explanation!
In the example above, since the value of “a” is equal to “10”, “if” gets executed and we get the following output
a is equal to 10
Here is a short intro to the “Python Interpreter” in case you are not familiar with it. If you are already familiar with the interpreter, how to launch and use it, you can safely skip this side-note!
Side-Note: A Short Intro to the “Python interpreter“
The Python interpreter, simply put, is the command line prompt “>>>” you will get when you enter the “python3” command in your Linux or Mac terminal (“3” stands for Python version 3).
This way of using python is also called using the “Interactive mode of the Python Interpreter”
$ python3 Python 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
If you are in windows, you can open up the interpreter app by opening the command prompt and by entering the following command
>python Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
Here you can play around with any python program, one line at a time as shown below!
You can even use this environment like a calculator by typing the expression to be evaluated as shown below!
I remember the first time I played around with the interpreter, it was loads of fun! To this day, it is still my go-to calculator app!
Go ahead, play a little with the interpreter! You can always bookmark this page and come back to it later!
Alright if you are done playing around with the interpreter let us go back to the main focus of this article, which is about learning the comparison operators.
Just to get the concept of “tokens” more clear let us take another example.
a = 10 b = [10, 0] if a < 10: print("a is less than 10") elif a == 10: print("a is equal to 10") else: print("a is greater than 10")
The above program comprises of the following tokens.
|Identifiers||a, b (Variable identifiers)|
print (built-in function identifier)
|Literals||Integer literals: 10, 0 |
“a is less than 10”
“a is equal to 10”
“a is greater than 10”
|Operators||=, < , ==|
|Keywords||if, elif, else|
|Delimiters||“”, “()”, “,”, “:”|
Now that we have understood how computer languages work and how tokens are the vocabulary of computer languages, let us turn our attention to “keywords”
You can think of “keywords” as “words reserved for a specific uses”!
But then how do we know if a given token is a keyword or if we are allowed to use them as identifiers (variable names, function names, and class names) in Python?
Let us learn that next!
How to know if a given word is a keyword?
You can do this 2 ways
- research on the internet (the hard way!)
- use the keywords module in Python (the easy way!)
Let us see how we can use the keywords module to check if a given word is a keyword (Trust me this is very easy!)
You can do so on the python interpreter as shown below.
>>> import keyword >>> keyword.iskeyword("apple") False >>> keyword.iskeyword("if") True >>> keyword.iskeyword("else") True
As you can see “apple” is not a keyword but “if” and “else” are!
The keywords module also lets us see the full list of keywords using the following command
>>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
As you can see there are 35 keywords here that are reserved for special purposes.
The next short section is a “fun” experiment. A word of warning the next section is meant for intermediate programmers and not beginners!
Side-note#2: A Fun Experiment
As we already know, print is an inbuilt function used to print some stuff on the screen. If you looked closely at the above list of 35 keywords, print is not one of them.
That is because print is an identifier and not a keyword.
So does this mean we can use that as a variable name in our code? What will happen if we do so?
Let us experiment and play with that!
>>> print("Hello Inventors!") Hello Inventors! >>> print = 10 >>> print 10 >>> print("Hello Inventors") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable
In the example above
- 1st we print “Hello Inventors” onto the screen using the “print” function
- Then we use print as a variable name and assign the value to 10
- Then we again try to print “Hello Inventors” again.
And the Python interpreter throws us an error saying you can’t do that!
So what happened there?
Have a look at the image below.
When we first called print function, the identifier print was pointing to the function that prints stuff
But as soon as the line “print = 10” got executed, the Python interpreter reassigns it to the integer value 10. Hence the error message “TypeError: ‘int’ object is not callable“
Here ‘int’ stands for integer, hope you got the point!
This usage of using built-in functions as variables is considered extremely bad practice, so never do this!!
Now that we have understood the building blocks of the python programs and what the role of “keywords” are, let us go ahead and learn more about the def keyword!
What Does the Keyword “def” Do?
Before can learn about the “def” keyword, we need to tackle one more fundamental concept, the concept of “functions”.
What are functions?
Say you want to teach a friend of yours “How to make a cup of coffee.”
The steps you would give him would look something like this
- boil the milk
- add some coffee powder
- add sugar to taste
- stir for consistency
Now replace the friend you are giving the instruction to with a computer. Since a computer is dumb, you need to explain each step in more detail.
For example to “boil the milk” you need to
- Pour the milk into the container
- Turn on the stove
- wait till milk boils
- turn off the stove
Similarly, other steps also have some details attached to them (which are fairly obvious in this case).
But if you write code like that, and if your colleague wishes to read the code, he won’t understand what you are trying to make the computer do.
So grouping them together into discrete actions like shown below is a useful technique.
Steps to make a coffee
- Boil the milk
- Pour the milk into the container
- Turn on the stove
- wait till milk boils
- turn off the stove
- add coffee powder
- take the coffee jar
- add one spoon of coffee powder to the milk
- add sugar
- take sugar jar
- add one spoon of sugar to the milk
- Stir the coffee
- take a spoon and stir the container
- once coffee looks consistent enough pour that in a cup and enjoy the coffee
Writing like this helps us achieve 2 things
- our colleague will be able to read our code easier, he can just ignore the details and focus on the big picture.
- the computer can focus on the details as it does not care about the big picture.
In computer science, each of the above 4 groups is called a “function“.
Let us approach this concept of functions from another perspective just to make it clearer.
Consider the Python program below which takes in the 2 sides of the rectangle as input and prints out the area of the rectangle as an output.
# get the length and breadth length = input ("Enter length of the rectangle: ") breadth = input ("Enter breadth of the rectangle: ") # convert the value to decimals length = float(length) breadth = float(breadth) # calculate the area and give result to the user area = length * breadth print ("Area of the rectangle = " , area)
Very simple right? It is very easy to read and understand this program all thanks to the comments!
Now, consider the code below instead.
Isn’t the above program easier to read and understand? Even without the comments?
Yup, the above code is short, sweet, and straight to the point!
We will get into how we can implement something like this in a little while, right now I want you to focus on “the idea behind functions“
Most of the time, we don’t care about the details of “how” some functionality is implemented, all we care about is “what” action is being done. So we try to code in a way that we group the statements implementing a specific functionality/action and hide them inside what we call in computer science as “functions“
Functions are a group of statements doing a specific action or implementing a specific functionality!
If you are still not getting the light bulb moment in your head about the concept of functions, fear not I have dedicated an entire article to learning this concept which you can read in the link below.
So read the article above and come back to this one and continue from here!
The def keyword and its relationship to functions
So how does the def keyword fit into all of this?
Let us take a look at Example#9 again.
The time has finally come for us to see how Example#9.2 in the previous section can be implemented using functions!
Take a look at the code below.
Don’t feel intimidated to read code, at first it can be tough! But as you get more practice, you will be reading code like you read plain English!
length = 0.0 breadth = 0.0 def get_inputs(): length_string = input ("Enter length of the rectangle: ") breadth_string = input ("Enter breadth of the rectangle: ") length = float(length_string) breadth = float(breadth_string) def calc_area(): area = length * breadth print ("Area of the rectangle = " , area) get_inputs() calc_area()
In the example above let us focus on the below 2 particular lines (lines 4 and 10)
def get_inputs(): def calc_area():
As you can see, there are 2 def keywords in the code above.
Here “get_input” and “calc_area” are the names of the functions a.k.a Identifiers
The indented lines following the names do the specific actions of getting the inputs and calculation the areas respectively and hence
- lines 4 to 8 is the function get_inputs and
- lines 10 to 12 is the function calc_area
Thus the def keyword is used to tell Python that what comes next is a function!
Let us have a quick look at the steps to follow to create a function in Python to make things more clear.
Steps to create a function in Python
The syntax is quite simple. All you need to do is follow the steps below.
- start the line with def
- give your function a name (without spaces)
- add a couple of brackets “()” after the name followed by a colon “:”
- add the statements we want to group together as an indented block of code!
- When we need to execute the statemetns in the indented block of code under the def statement all we need to do is use the name of the function followed by a pair of brackets as shown in lines 14 and 15 in the Example above!
By “indented block of code” I mean starting the line with some spaces (4 spaces are recommended) as shown below
def function_name(): line1 line2 . . .
The def keyword is used to tell Python that the following block of indented code is a function.
Thus we can use functions to organize the code nicely into several sections using the def keyword!
I hope you now have a good understanding of the “def” keyword in Python!
Where To Go From Here?
If you made it this far, then bravo to you! Great job!
I hope I did a good job quenching your thirst for knowledge about the “def” keyword!
I wanted to just write a simple intro to functions followed by saying def is the “magic word” to be used with functions, but I wanted you to learn some behind-the-scenes stuff that makes it all look like magic!
Regarding the code in Example#10, it is but a simple introduction to functions and there is a lot more you need to learn if you wish to wield the full power of functions properly in your Python programs!
I have written another article on functions which teaches all the tricks you need to know as a Python programmer to wield the full power of functions. You can find that in the link below.
With that, I will end this article.
Hope you had a good time reading this article and you have learned something useful!
Feel free to share this article with your friends and colleagues!
Also, check out the articles in the “Related articles” sections below!