What is a Function in Python?

Where do we use Function? and why do we use it?

INTRODUCTION:

generally, when we have to write huge lines of code we get confused

sometimes we’ve to repeat a code for the same process So instead of writing all the code again and again we can use functions that once declared can be used anywhere in the code

Reusability of code is the main advantage of using functions

Syntax

def function_name(parameters):
	"our code"
	statement(s)

here def is a keyword that shows the function header

function_name is a uniquely named identifier

parameters by which we will pass values for the function they are optional

colon : is the end of the function header

then we’ve to write our code which should be intended for 4 spaces or 1 tab

we can use a return statement if we need any values from the functions

Example:

def welcome (name):
    print("Hello, " + name + ". how are you!")
welcome('Everyone')

Output

Hello, Everyone. how are you!

Return Statement:

It is used to get the value evaluated from the code of the function

if there is no expression inside the statement then the return statement itself will not be present then it will return none object

Example for return:

def value(num):
    if num >= 0:
        return num
    else:
        return -num


print(value(9))

print(value(-8))

Output:

9
8

Example with more parameters:

def my_function(OS):
  for x in OS:
    print(x)

Fav= ["Mac", "Android", "Linux"]

my_function(Fav)

we can send any kind of data type of argument to a function like string, number, list, dictionary, etc.), and it will be treated as the same data type inside that function.

for example. if you send a list as an argument, it will still be a List when it reaches the function:

Output:

Mac
Android
Linux

Types of functions:

  1. Builtin functions
  2. User defined functions click here to know more

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!๐Ÿ‘‹
Can we help you?