top of page

Data Scientist Program


Free Online Data Science Training for Complete Beginners.

No prior coding knowledge required!

Functions in python

In python , functions can be considered a small factory that have a specific task that takes an input, processes it and produces an output.It is essentially like a block of statements performing a specific task.

A function in python is defined using the def keyword followed by the name of a function and one or moreoptional parameters wich represents the variable that exists only within the functionand can not called outside the function The function can have a return value which is optional

It presents the output generated by the function and is returned to the main program For calling a function, we need to inser inputs ( or arguments) in order to perform a certain task and produce an output Functions are very helpful when it comes code more organized and fashionable and it can be called repeatedly instead or rewriting the code.

A simple example of fuctions is the print() function which gives the screen printout of the input.

Function can be considered as a self-contained block of code that encapsulates a specific task or related group of tasks. In previous tutorials in this series, some of the built-in functions are provided by Python. id()

The usual syntax for defining a Python function is as follows:

def <function_name>([<parameters>]):

When the function is called, you specify a corresponding list of arguments:

>>> f(6, 'bananas', 1.74)
6 bananas cost $1.74
print("this is easy")
this is easy

Taking an example , Let us say that you want to write a code that celebrate person birthday by showing his name and his age :

def birthday(name, age) :
      print ("happybirthday", name)print(name, "is",age, "years old")
      print("I wish you great day!")print(birthday("sara" ,25))            

The out put for this code would be :

happybirthday sara
sara is 25 years old
I wish you great day!

We can create function that creates 2 functions sin_angle and cos_angle . These functions calculate in and cosin of an angle given in degrees :

import math
def sin_angle(x):
    Y=math.radians(x)return math.sin(x)

#let us take an example for x=60 :print(sin_angle(30))

def cos_angle(x):
    Y=math.radians(x)return math.cos(x)
#let us take an example for x=60 :print(cos_angle(60))

The output would be :


As applications grow larger, it becomes increasingly important to modularize code by breaking it up into smaller functions of manageable size


Recent Posts

See All
bottom of page