Introduction To Python Part 5

Jreyes
2 min readNov 23, 2021

--

Functions

A function in python is a block of code that will execute whenever it is called. We can pass parameters in the functions as well. To understand the concept of functions, let's take an example.

Suppose you want to calculate the factorial of a number. You can do this by simply executing the logic to calculate a factorial. But what if you have to do it ten times a day, writing the same logic, again and again, is going to be a long task.

Instead, what you can do is, write the logic in a function. Call that function every time you need to calculate the factorial. This will reduce the complexity of your code and save your time as well.

How to Create a Function?

# we use the def keyword to declare a functiondef function_name():#expressionprint('abc')

How to Call a Function?

def my_func():print('function created')#this is a function callmy_func()

Function Parameters

We can pass values in a function using the parameters. We can use also give default values for a parameter in a function as well.

def my_func(name = 'eduardo'):print(name) #the output will be: eduardo#default parametermy_func()#userdefined parametermy_func('python')

Lambda Function

A lambda function can take as many numbers parameters, but there is a catch. It can only have one expression.

# lambda argument: expressionslambda a,b : a**bprint(x(2,8))#the result will be exponentiation of 2 and 8.

Now that we have understood function calls, parameters, and why we use them, let's take a look at classes and objects in python.

Classes & Objects

What are Classes?

Classes are like a blueprint for creating objects. We can store various methods/functions in a class.

class classname:def functionname():print(expression)

What are Objects?

We create objects to call the methods in a class, or to access the properties of a class.

class myclass:def func():print('my function')#<span style="color: #ff6600;">creating</span> an objectob1 = myclass()ob.func()

__init__ function

It is an inbuilt function that is called when a class is being initiated. All classes have __init__ function. We use the __init__ function to assign values to objects or other operations which are required when an object is being created.

class myclass:def __init__(self, name):self.name = nameob1 = myclass('eduardo')ob1.name#the output will be- eduardo

Let's pause here and continue next week with OOPs Concepts.

Jump to the next chapter

--

--

Jreyes
Jreyes

Written by Jreyes

I'm a software engineer making his way into the tech industry.

No responses yet