Functions In Python, How To Write Function In Python


Introduction

Now, that we have covered the basic foundation required to start python, Let's begin with a very useful term in programming called as function.


If you have not read the python foundation post, then read it here
you will wonder that without knowing anything about the functions, still you used the functions in the foundation post!
Remember? we used the print() function to output a message on the screen?

The print() function you used is known as predefined function, Predefined functions are functions that are available in python or comes built-in python, i.e we don't need to write any code, we just need to call them by their name.

We can also define our own function, It's no big deal, in couple of minutes you will be able to write your own functions and use them as you want.

To define a function use have to use the keyword "def". yes, the keyword def will tell the interpreter of python that the script in this block is a user define function. Let's See an Example


```python
def Welcome():
    print("Hey User How are you doing. Welcome to creationcodes.org")

Welcome()
```

    Hey User How are you doing. Welcome to creationcodes.org
    

Simple, Our first function is ready! Observe how the next line after def welcome(): is indented with an extra space, this allows python to know that this piece of code is the part of this function.

In python we don't have the concept of curly braces. We define a block of code using the indentations.

The def keyword is used to define your function, within the def block you write the script for your function. After defining your function, we call our function by it's name. In our case the name of the function is Welcome. So we write:


```python
Welcome()
```

    Hey User How are you doing. Welcome to creationcodes.org
    

Function With parameters in python

Now what's that? function with parameters? what is a parameter! Ahh, you are familier with the parameters. Remember? how we use the print(). We write the message we want to print within the () brackets! that message is nothing but a parameter to our function.

Let's Look At the example:


```python
def Welcome(name):
    print("hello " + name)
```

Let's call the above function!


```python
Welcome("Robert")
```

    hello Robert
    

Easy right? Now one more thing you should know about the functions is return types.

Return Types In Python

Suppose you want to create a function which can add two numbers and then, you want that result to store in a variable for further use. For this, you have to make such a function that can return the result. Python provides an easy way to return the values from a function. We just have to use the retun keyword at the end of the function and have to mention what value we want to return.

Now, What is return type? Remeber? we talked about datatypes! return types is very similar to datatype. It allows us to know what type of datatype the function is returning.

if you function returns a string, then the return type is string, If your function returns a number, the return type may be float, int depends upon the type of number.

let's look at some example.




```python
def AddMe(a, b):
    return a+b

result = AddMe(5,6)

print("The Result is: ", result)
print("Return Type is", type(result))
```

    The Result is:  11
    Return Type is 
    

Observe how we use the return keyword, the return keyword return the result of 5, 6. When the control comes out of the function, we save that return value in a variable called result. that's it, after that you know what we did.

Let's look at another example, suppose you want create a function which takes input the name of your best friend and returns a greeting for your best friend.


```python
def BestFriend(name):
    return name + " is stupid, But he is the most caring person I know."
```

Now, above function will return the greeting and we will catch that greeting in a variable. Let's call our function.


```python
greeting = BestFriend("Robin")

print(greeting)
print("Return type is: ", type(greeting))
```

    Robin is stupid, But he is the most caring person I know.
    Return type is:  
    

Now, that we have covered up functions let's talk about how we can take input from user! When we learn how to take input from users we can do a lot more fun examples!!

input() function in python

In earlier examples I show you how you can print a message on your screen, But how to take input from a user?
It's very easy in python, To take an input from a user in your python script we will use input() function.
Let's see an example where we use the input function which takes the input from user and prints a greeting message.


```python
name = input("Enter Your Name: ")
print("Hello "+name)
```

    Enter Your Name: srujan
    Hello srujan
    

The input function takes a perimeter as string to display a message as what we want the user to enter. The return type of the input() function is string.

You should keep in mind that the return type of the input() is a string because it will cause errors when you deal with numbers.

Suppose you want to calculate the area of the circle. You write a script which takes the radius as input. let's look.


```python
def circleArea(radius):
    return 3.14*radius**2

radius = input("Enter the radius of the circle: ")

print("The Area is: ", circleArea(radius))
```

    Enter the radius of the circle: 5
    


    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

     in 
          4 radius = input("Enter the radius of the circle: ")
          5 
    ----> 6 print("The Area is: ", circleArea(radius))
    

     in circleArea(radius)
          1 def circleArea(radius):
    ----> 2     return 3.14*radius**2
          3 
          4 radius = input("Enter the radius of the circle: ")
          5 
    

    TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'


See, you got an error! why? because the return type of input() function is a string, and we can not do mathematics with string right!!!

The easy solution to this problem is type casting. Type casting is technique from which you can convert from one datatype to another.

python provides different methods for type casting. and they are easy to remeber because the names are similar to the names of datatypes!

int() will convert any string to int.
str() will convert int to string.


```python
def circleArea(radius):
    return 3.14*radius**2

radius = input("Enter the radius of the circle: ")

radius = int(radius)

print("The Area is: ", circleArea(radius))
```

    Enter the radius of the circle: 5
    The Area is:  78.5
    

Now, our code is error free and is in working condition!!

That's for now... we covered enough topics to understand functions. We also covered the input() to take input from users. We covered how to do type conversion.
That's a lot. just relax for now, and keep coming for further posts. We will be doing some silly and intresting examples to make programming a fun loving tasks.

will meet in next post.
Thankyou.


```python

```


Post a Comment

0 Comments