Python Programming

Function in Python

In Programming, Python by Baqir Ali

In order to have a good and meaningful code, you have to think about organizing it into functions. A function is a block of code that is used to perform a specific task. There are two types of functions. One is a built-in function and the second is user-defined functions.

A built-in function is a function that comes with python itself, and the user-defined function is a function defined by a programmer according to his need.

Why do we use a function?

There are two main reasons that we use a function. Code reusing and easy debugging.

A simple example of a function that prints Hello People. Remember function should be defined before calling it

Example 1:

#start of function definition
def greetings():
    print("Hello People")
#end of function definition
#function call
greetings()

Output: Hello People

Example 2: A function that prints multiple lines.

def greetings():
    print("Hello Programmers")
    print("Welcome to Code Modes")

greetings()

Output:

Hello Programmers
Welcome to Code Modes

Example 3: A function that prints a line of stars when called

def greetings():
    for i in range(1,10):
        print("x ",end='')

greetings()
print()
greetings()
print()

Output:

x x x x x x x x x
x x x x x x x x x

Remember the above functions neither receive nor return any value.

Parameterized function in Python

A function that receives value from the user and uses it inside the block of the code.

Example 3: A function that receives a value and checks if it is even or odd.

def check(x):
    if x%2==0:
        print("Even")
    else:
        print("Odd")

val=input("Enter a number: ")
val=int(val)
check(val)

val=input("Enter a number: ")
val=int(val)
check(val)

Output:

Enter a number: 6
Even
Enter a number: 5
Odd

Returning Value from a Function in Python

A function that takes a value, operates on it, and returns its answer. The following is an example of a function that receives a value finds its factorial and returns it.

def factorial(x):
    ans=1
    for i in range(1,x+1):
        ans=ans*i
    return ans

val=input("Enter a number: ")
val=int(val)
answer=factorial(val)
#whenever a function returns a value receive it in a variable like 'answer'
print(answer)

Output:

Enter a number: 6
720

Support us by sharing this post