python-part3

Learn Python Through Anime: Part 3

If you are new here, check the previous part of Learn Python Series:

User-Defined Functions In Python

You might have noticed by now that we have mentioned a lot about function and return data type, i.e., int(), print(), type(), id(). We used these names unknowingly till now. Now you will explore more about functions and return keywords.

Functions are the most important topic in Programming languages. With the help of functions, you can reduce code reusability and save time for code execution. Functions can make a program smaller by eliminating repetitive code. Later if you make a change, you only have to make it in one place. The function makes debugging the program easier.

By now you have used functions many times. The print() statement is a function that displays the message, the input() is a function as well. Anything in a programming language that has open and close parenthesis () is considered as Method/Function. Now re-read the sentence again, sentences ending with () are Method or Function. But Method and Function are different. Think of function as function() and method as object.function(). e.g. for Function: print(), len() whereas e.g., for Method: xyz.count(), str.upper().

Before getting into Syntax and Example stuff, know the reason Why we use functions? Consider an Anime Merchandise Showroom, there is a machine that welcomes every customer that enters the stores. You need to write a code to display a Welcome message every time someone comes in. Of course, you can use a for loop but this will complicate things. However, the function does the job easier.

You can create a new function with the name greet and call it every time a new customer enters the store. This makes things easy. You can save memory, the run time and can re-use the same code whenever you need it, this is called code reusability.

Define A Function In Python

Finally, it’s time to see the syntax and examples. The Functions we looked at so far were built-in functions. From now on we will define a User-defined Function. User-defined are the functions that are newly made by a user of any name. Seeing any name, don’t go assigning around and give random names, try to give a suitable name for Function.

Syntax:
def function_name(): #empty parenthesis
    statements
function_name()
def function_name(argument1,argument2): 
    statements
variable1,variable2 = value,value
function_name(variable1,variable2)

def is a Python keyword that tells us that there is a function defined. The next thing after the keyword def is the function name/Identifier. The function name is then followed by an open and close parenthesis. Most often the parenthesis is empty and sometimes it has n-arguments based on Program requirements.

You can execute this function only when you call the function back. If you don’t call the function back it will never be executed. You need to be careful when you use functions with arguments. If you need two arguments inside a function definition and call back more than two arguments then obviously it will throw some error.

When you open the interactive shell and type help(“def”) you can see the detailed information and syntax related to it. help() function is very handy to use.

A massive examples list to understand functions. With Explanation for every Examples

#example-1
def welcome():
    print("Congrats on making this far")
    print("Share Anime Vyuh Articles")
welcome()

Output:
Congrats on making this far
Share Anime Vyuh Articles

As mentioned in syntax the function starts from the def keyword followed by a name and parenthesis. The first example is just a welcome program to all the fresh readers. Once the welcome function is filled with the statements, the next thing we need to call the function, so that it can execute. You can call the function as many times as you like.

welcome()
welcome()
Output:
Congrats on making this far
Share Anime Vyuh Articles
Congrats on making this far
Share Anime Vyuh Articles
#example 2

def farewell():
     print("Sayonara!")
#No output because you didn’t call the function

There is no output until you call back the function, Even though the program is error-free, it won’t run unless you call it. Thus it gives no output.

#Example 3
def greet():
    print("Welcome to Anime Hospital")
    print("How can I help you?")

print("Patient 1 appears:")
greet()
print("Patient 2 appears:")
greet()
print("Patient 3 appears:")
greet()

Alternative without function

greet = "Welcome to Anime Hospital \n How can I help you?"
for i in range(1,4):
    print("Patient {} appears".format(i))
    print(greet)
Output:
Patient 1 appears:
Welcome to Anime Hospital
How can I help you?
Patient 2 appears:
Welcome to Anime Hospital
How can I help you?
Patient 3 appears:
Welcome to Anime Hospital
How can I help you?

Define a greet method or function with an introduction message. Since we can call the function as many a time we want. After the entry of each person call the function, so that the greet function is executed and the message is displayed. You can do this with help of for loop as well? The same output we get, then why can’t we use for itself instead of def. The main disadvantage of using for here is that it takes more execution time compared to function. Thus we use the function in such situations, in order to save memory and execution time.

#Example 4:
def song(): 
    print(“Yo-hohoho, Yo-hohoho”)
def lyrics():
    print(“Binkusu no sake wa, todoke ni yuku yo”)
    print(“Umikaze kimakaze namimakase”)

song()
song()
lyrics()
song()
Output:
Yo-hohoho, Yo-hohoho
Yo-hohoho, Yo-hohoho
Binkusu no sake wa, todoke ni yuku yo
Umikaze kimakaze namimakase
Yo-hohoho, Yo-hohoho

Using multiple functions, you can create as many functions as you need. Here we created two functions, the first one is the song function and the second is the lyrics function. The statement inside the song function is repeated many times, thus we will call song() before and after calling lyrics() function. So go ahead and try some examples with function with empty arguments, because we will get into the examples with arguments.

Function With Parameters

#example 5
def max(a,b,c):
    if a>b:
        if a>c:
            print(a) 
        else:
            print(c)
    elif b>c: 
        print(b)
    else:
        print(c)

max(1000,1001,1001)
Output:
1001
def greet(name1,name2):
    print("Welcome",name1,'nice to meet you')
    print("Welcome",name2,'nice to meet you')
greet("Naruto","Luffy")
Output:
Welcome Naruto nice to meet you
Welcome Luffy nice to meet you

So far we have seen the example with empty arguments. Now we will deal with arguments. Let’s take two names as the parameters and welcome them. greet(“Naruto”,” Luffy ”), Naruto and Luffy are declared as name1 and name2 respectively. In another example, declare three parameters of integer numbers, Say a, b, and c. Print the maximum number among these three. A simple code that first checks the greater number between two numbers, say if a is greater than b, we will check if a is greater than c. If a is greater it will print and else it will print c. If a is not greater than b then we check if b is greater than c, if True b is the maximum number, if both if statements are False, it will execute the else block.

#example 6
def anime_details(name,mc,waifu):
    print("Anime Name:",name)
    print("Main Character:",mc)
    print("Female Lead:",waifu)

n = input("Enter Anime Name:")
m = input("Enter Main Character:")
w = input("Female Lead:")
anime_details(n,m,w)
Output:
Enter Anime Name:Steins Gate
Enter Main Character:Okabe Rintaro
Female Lead:Makise Kurisu

Anime Name: Steins Gate
Main Character: Okabe Rintaro
Female Lead: Makise Kurisu

Example 6 is the same as that of example 5. The only difference is that we are accepting user input, instead of directly assigning variable values.

#Example 7: 
def student(name,age,branch):
    print("Student name:",name)
    print("Student's Age:",age)
    print("Branch:",branch)

n = input("Enter student name:")
a = input("Enter age:")
b = input("Branch:")
student(a,n,b)
Output:
Enter student name:Tarun
Enter age:20
Branch:ECE 

Student name: 20 #lets solve this issue next
Student's Age: Tarun
Branch: ECE

Now, this output is very weird. The Student’s name is executed as 20 and the age has printed a name. This is not a Syntax Error rather it is a logical error. The program will run fine, but the output we get is unexpected. You need to know the order, how to place the variables inside a function call. Let see next how we can overcome this Logical Error.

#Example 8:
#in order to overcome example 7
def student(name,age,branch):
    print("Student name:",name)
    print("Student's Age:",age)
    print("Branch:",branch)

n = input("Enter student name:")
a = input("Enter age:")
b = input("Branch:")
student(age=a,name=n,branch=b)
Output:
Enter student name:Tarun
Enter age:20
Branch:ECE

Student name: Tarun
Student's Age: 20
Branch: ECE

In example 7, we did get a weird output, where we exchanged the values of name and age. In example 8, we have directly assigned the variable to a specific parameter. See that even if we exchanged the order we get the proper output. It’s because we have assigned the values to the variables inside the function call itself.

#Example 9:
def area(radius,side): 
    pie = 3.14 
    area_circle = 2*pie*radius
    area_square = side*side
    print("Area of Circle",area_circle)
    print("Area of Square",area_square)

rad = int(input("Enter radius of Circle:"))
s = int(input("Enter Side of Square:"))
area(side=s,radius=rad)
Output:Enter radius of Circle:4Enter Side of Square:5Area of Circle 25.12Area of Square 25
#Example 10: Introduction To Return

def is_divisible_by_2(num): 
    if num%2==0: 
        return True 
    return False
#when you return the function call assign it to a variable

number = int(input("Enter a number:")) 
result = is_divisible_by_2(number)
print(result)
Output:
Enter a number:4
True
Enter a number:5
False

What Is Return?

So far we have discussed that this output returns this data type. These answers return in Boolean data type, and answers return in Integer/String data type. What on earth is this return? The return keyword is to exit a function and return a value.

def watch_anime():
    if free_time():
        return True
    else: 
        return False

How many functions do you think this program has? There are two functions in this program: watch_anime() and free_time(). Can you predict what this function does?

First, there is one function that is already written i.e., free_time(). On certain conditions the free_time() function returns True or False value. It is pretty easy to recognize the free time returns True or False, because we know that it takes only Boolean conditions. So now again in the watch_anime() function, we are returning True or False. Next, it is very important to know how to execute the call function with a return value.

def free_time():
    ask = input("Do you work today?(Y/n):").lower()
    if ask.startswith('y'):
        return False
    return True

def watch_anime():
    if free_time():
        return True
    return False

print("Watch Anime:",watch_anime())
Output:
Do you work today?(Y/n):n
Watch Anime: True

Do you work today?(Y/n):y
Watch Anime: False

Notice the free_time function closely it is returning False when user input is yes. It should make sense because the user says yes because he has work today, So when he has work he can’t watch anything and thus it returns False. In the same way, if the user doesn’t have work, he will return True.

Few things you need to focus on while working with return in beginning. You need to assign a return to a variable or print the function directly to be executed. Check out the difference, that is highlighted.

def value(n):
    print(n)

value(10)
#output is: 10

def value(n):
    return(n)
value(10)
#no output

def value(n):
    return(n)
val = value(10)
print(val) 
#or without new variable 
print(value(10))

Output:
10
10

More Example On Return

Return with if-else statements

def is_it_raining():
    ask = input("Is it raining, outside?(Y/n):").lower()
    if ask.startswith('y'):
        return True
    return False
if is_it_raining():
    print("Take your umbrella")
else:
    print("No need to take your umbrella today")
Output:
Is it raining, outside?(Y/n):y
Take your umbrella
Is it raining, outside?(Y/n):n
No need to take your umbrella today

Return with For loop

def check_for_loop():
    for i in range(10):
        return i

print(check_for_loop())
Output:
0

Now this is weird, we are looping through 10 numbers but only one number is executed. The reason is once you use return, you can’t use that function again. Return acts as a break statement for the def block. Just like break can’t we used outside loop, return can’t be used outside the def block.

We might have looked at a massive example list, but we missed out on one minor topic to be discussed.

Default Parameter Values

def add(a=10,b=20):
    return a+b

print(add())
Output:
30

Even though we have taken two parameters in the function, we have called an empty function. You can do this only when you have assigned default values while defining the function. But you can also give two-parameter while calling it, here is what you get as output,

print(add(4,5))
Output:
9

If you like our content, support us by Buying a Coffee.