Featured Post

How To Use Python Input Function

Image
 How To Use Python Input Function Introduction  This Python Beginner tutorial will guide you on the usage of input() function in python. We use input function in all our Python Projects, so, it's necessary to understand,  what is input function, how it is used and why it is used in python projects.  What is input() function  Python input() function is a function that accepts input values from a user when prompted to provide an input. It is an inbuilt function that reads the input values from the user and after evaluating it, by default, the input() function will return the input as a string. The input function doesn't have parameters inside its parenthesis, but, it takes a prompt in the form of a string inside it's parenthesis. For example: Consider a variable that you created , name, and you want to get input of different name values from the user, so you use the input function with a prompt inside it's parenthesis as shown below: CODE name = input(...

Essentials About Python def Keyword

 Essentials About Python def Keyword










INTRODUCTION

For all those code newbies who find it hard to digest the usage and where withals of  the term def that appears a lot of time while coding in Python, here is a great news! I am going to explain not only what is the def that is used so frequently in all of the Python projects, but also, it's usage, why it is used and how it is used in detailed steps.


WHAT IS def

The def keyword is used for describing or defining a Python function in which we need to implement certain specified tasks. We require various tasks to be done inside a function, such as calculating the sume of numbers, carrying out subtraction of numbers, finding the average of numbers, finding Grades based on score , etc. I will be outlining below, the various tasks that could be performed inside the def function and I will be also guiding you on each of them step-by-step citing examples along the way.


WRITE THE STRUCTURE OF  A def Function

def function_name(parameter1, parameter2):

The def function is written as mentioned above. First we write def that is short for define, then it is followed by the function with a specific name and the name is assigned to the function based on the tasks that it is going to perform,. The function name is then followed by a parenthesis and inside the parenthesis, there are two parameters, namely, parameter 1 and parameter 2, and right after the parenthesis, we write a colon and this colon will set the indent of the code block that ensues the colon , inside this function. 


HOW & WHERE IT IS USED IN FUNCTIONS

There are different tasks that could be performed inside the def function and today, I will expatiate the various specific tasks and outcome to be achieved using the def function. 


Calculating the Average 

We can calculate the average of three numbers or more numbers using the def function and here I will show you can write the code for this function and also get the outcome with this code


Explanation

In the above example code, let us first figure out what is happening with the def function. First we define or describe the function with the name of find_average, we give this function a name of find_average, as it is used to calculate the average of three numbers. Inside the find_average function we have assigned three parameters namely, x, y and z inside the parenthesis of the function find_average. Then we write the colon and after writing the colon, when we click the Enter key , we are immediately taken to the next indent code block inside the function. We create a variable called 'average', remember, we could give it any name, such as 'average' or 'avg' or 'avrg', the idea is to allocate such a name that will indicate a specific or unique identity of the variable, based on the specific task that is associated with the variable. In this case, we need to calculate the average of x,y and z and store the value of the average inside this variable called 'average'. So, I presume that it is clear by now until now, what we are trying to achieve with this function called find_average with def preceding it.

Next, we use the 'return' keyword to return the average after calculation. As we can see here, the return keyword is used here to return a value after calculation

Next we create a variable called answer and we store the value after calculating the average of the numbers 7, 16 and 25. Calling a function is a very important task in order to execute the calculation of the average with the specific numbers that you feed inside the parenthesis of the function.  At first we used the parameters inside the parenthesis of the function and then while calling the function, we write the function with the specific arguments inside it. So, 7 is the value for x, 16 for y and 25 for z. Hence , arguments represent the actual values of the parameters that we provide to the function to perform the calculation and when we call the function by writing the name of the function, with the values of the arguments inside the function parenthesis, that is, by writing find_average(7, 16, 25), we are actually calling the function. While calling the function, we also assign it to the variable called answer so that the calculated result values could be stored in this variable called answer.

Finally we print out the answer by using the print() function. We write print(answer)


Code 

def average(x,y,z) :     
       average = (x + y+ z)/3
       return average
answer = find_average(7,16,25)
print(answer)



Calculate The Sum of Two Numbers


Here we will learn how the def function will help us to perform addition of two numbers and also to display the calculated result .


Explanation

In this problem we follow exactly the same steps that we did for the above problem, and in this problem we need to find the sum of two numbers. We do this by defining a function called add_num, we are the one giving this name to our function and then inside the parenthesis, we are going to put in two parameters namely, x and y. Then, we write the formula or rather the method to add the numbers by creating a variable, we name it as 'sum' and assigning it the task of x+y and we store the values derived from adding x and y to it. Then we write the return keyword in order to tell the function to return the sum value after calculation. Next, we call the function add_sum by providing it specific arguments, in this case, the numbers, 7 and 25 and assign it to a variable that we create by the name of solution. Finally, we print out the outcome by using the in-built print() function. The final code snippet looks like the following 


Code


def add_num(x, y):
     sum = x + y
     return sum
solution = add_num(7, 25)

print(solution)



Calculate students' Grades-use def in conditional loops 

In this example, we will be calculating the Grades of students based on their scores earned and we will be able to display the result from performing the calculation inside this function

Explanation

In this problem we need to calculate students' Grades based on their marks scored using the def keyword in Python. First we define the functio, with the help of the def keyword  that is going to carry out the task of find out the Grades based on score in which we are now going to use the conditional loop. We name this function as find_grade as this makes sense based on the tasks that it is going to perform for us. Inside the parathensis of this function we include 'score' as the parameter since the Grades are based on the score of individual students. Instead of score , we can also call the variable as marks , that is upto us what names we want to specify for our variables that we want to use as a parameter here in the function. Please note, 'score' is the variable that we created here, with the intention of  storing students' scores and use that for the conditional loop inside the function that we defined as demonstrated below.

We need to specify the conditions for determining the Grades. The first condition is such that if the score is greater or equal to 95, then the function should return a score of  'A'  as this is going to be the highest Grade based on the highest score range. If the score is greater or equal to 85, then the Grade that is to be returned is 'B', if the score is greater or equal to 75, then the Grade to be returned is 'C' or else if the score is greater or equal to 65, then the Grade to be returned is 'D' and if the score is any less than this range, then the Grade to be returned is'F'.  As we know very well, 'F' stands for Fail !

As you can see in the code below, the 'return' keyword is used to return the Grades, the function uses the 'return' keyword to ask the function to do something! Here the function is using the 'return' keyword to do the task of  allocating the specific Grades based on specific Scores.

We call the function by  writing the function name with the specified argument inside the parenthesis. In other words, we replace the parameter inside the parenthesis with the argument value. As mentioned earlier in this post, argument is the specific value that we need inside the parenthesis of the function in order to call the function to perform the specified task. By writing  the argument value, 75, inside the parenthesis, the function is able to perform the task of finding the Grade for the specified value of 75, that we call it as an argument and not parameter. Later, I will be writing a detailed tutorial on the exact difference between argument and parameter in another post which is going to be coming in the subsequent week ahead!

After calling the function, we assign it to a variable with the name of  'grade'. Please note that here we had to create the variable, grade, in order to assign and store the values of the function that is called with the specified arguments. Finally, we use the print() function to display the result or outcome of the grade that we want to calculate for the students based on their score.

The final code is as shown below. 

Code


def find_grade(score) :
    if score >= 95 :
         return "A"
   elif score >= 85 
        return "B"
   elif score >= 75 :
        return "C"
   elif score >= "65" :
       return "D"
   else :
       return "F"
grade = find_grade(75)
print(grade)


Use def with welcome message function

In this example, we are going to see how the function that we create with the def keyword will help us to display greeting messages to the specific user using his or her specific name!

Explanation

In this task we learn how to use def keyword to defind a function to output welcome greetings to the users and this greetings will be also greeting the user with specific name of the user to give a friendly welcome message. 

First we use the def keyword and create a function, give it a name of welcome_message, then, inside the parenthesis of the function we give it a parameter of name since name is the variable we create to be used for storing the name of the user so that the function can do welcome greeting by also specifying the name of the user or rather, address the user with the specific name while greeting the user. The function is called by writing the function with the argument inside its parenthesis, that is, we call the function by its name, example, welcome_message("Meera Menon") and here we are using the argument value as "Meera Menon", where the user's name is "Meera Menon" and the function will perform the task of welcoming the user with the user's name.

    

Code

def  welcome_message(name) :
    print("Hello, welcome to the coding world of", name)
welcome_message("Meera Menon")



Use def to calculate the area

In this example, we will see how to calculate the area of an object by performing different tasks in our function that we created with the def keyword.

Explanation

In this case example, we are going to find or rather calculate the Area of an object by defining a function that we give the name of find_area, a name that is given with the identity of finding the area of specified dimensions, and for this we create a function, give it a name of find_area and use the def keyword to describe or define it , with two parameters inside the parenthesis, namely, l that stands for length and w that stands for width, in this case, both the values of the length and width have already been provided in the parenthesis. 

We create a variable called area and store the calculated values of the result of multiplication of l and w. Then we instruct the function find_area to return the calculated area values. Next step involves calling the function find_area. For calling any function, we just write the function name at the end of the code and here we can call the function by writing function find_area, here , we do both the tasks simultaneously, that is calling the function as well as display the calculated result from the function performance. So, we just write the argument values of length and width that is, l and w respectively inside the function parenthesis and also include that inside the python inbuild print function. 

The print function will help us to display the result after calling the function or like here , we are able to display the result of the calculation simultaneously while calling the function.  We are also able to do the steps separately, that is, first call the function , by writing function find_area() and then in the next line, just use the print function to display the result. I have mentioned both the situations , the one in commented writing  is the situation where I first call the function, then print it out in the next line. This print function will enable us to display the result of multiplying the values of 7 and 70 to calculate the area of the provided dimentions.

Code

def find_area(l=4, w=10) :
      area = l * w
      return area
#find_area(7,70)
#print(find_area(7,70)

print(find_area(7,70))



CONCLUSION 

We are now able to use the def keyword in creating a function to perform our specified tasks and the then also display the calculated results for specific arguments that we want it to perform upon. Hence we see how valuable is the usage of the def keyword. Now, we are no longer confused at hearing the term def while reading Python documentations or reading Python codes. 

If you want to read more such python guides, remember to follow my posts here and subscribe for content related to Python for Beginners. 



 Read More Python Posts

Fighting Challenges Of Programming

 

What Programming Language Should You Learn First As A Beginner 




















Comments

Popular Posts

Build A Random Quote Machine in React

Build A Calculator in React

A Simple Guide to Promises in JavaScript ES6

Welcome to my first Blog Post

How To Fight Programmer's Imposter Syndrome

Top Free Online Websites to Learn Coding

Guide to Learn Coding Efficiently and Effectively