DEV Community

Cover image for Mastering Python Functions: Unlocking the Power of Reusable Code (Day 5 of 100 Days of Python)
All About Python
All About Python

Posted on

Mastering Python Functions: Unlocking the Power of Reusable Code (Day 5 of 100 Days of Python)

When we were kids, we were taught to add single digit numbers. After some practice and time, we were able to do it with ease. But as number of digits increased, we started using pen and paper to add one digit at a time and also note down the carry number. The reason was simple, unless we train our brains, we have a limit till which we can process information. In simple terms, adding numbers with multiple digits was a complex task for our brains.

Yet, we were able to solve the questions by breaking down the problem into smaller steps. In case of addition, it was to add one digit at a time, add the carry to the next number, and continue it for each number. What this example teaches us is that complex problems can be broken down into sub-problems to make it easy to solve.

We face a similar challenge in programming, when we write program in python (or in any other language). Experience shows that most programmers cannot keep track of more than 10 statements or so at a time. So we cannot just "attack the problem" as a whole, but instead divide it into sub problems and solve it. Functions in python allows us to do the same.

Modular approach (aka stepwise refinement method) in programming talks about breaking a problem into subproblems (in the form of functions which we will discuss later) and then further breaking down the subproblems until we reach a level where we can easily solve it. At the end, we merge all the subproblems and get our final solution. Algorithmic techniques like "divide and conquer", "dynamic programming" are all based on the approach to divide an unsolvable large problem into multiple solvable subproblems.

In this blog, we will talk about how we can use functions in python to adapt a modular approach to programming.

Functions in Python

Functions are reusable blocks of code in a programming language that have a specific task/purpose. They can take input(s), process data and return output(s) (although it is not necessary that they take input everytime or return output everytime). To strengthen our understanding of functions, first let's use the functions that comes built in python to see how they word.

Built-in Functions

As the name suggests, these functions come built-in in python and can be used anywhere in a python code. We will run python in interactive mode to run all our code all the code in this blog. Let's go through some functions one by one.

input function

First in our list is the input function. This function is responsible for taking any data as input from the user. The function takes the input and returns it as a string. Here's how you can use it.

>>> name = input("Enter a name: ")
Enter a name: All About Python

>> name
'All About Python'
Enter fullscreen mode Exit fullscreen mode

The function takes in an input string (which is displayed to the user when taking input) and returns the data that the user entered.

In this example, the user is prompted to enter its name, and the input function stores it in the name variable. Later, the data from that variable can be displayed to the users.

eval function

The eval function is used to evaluate a string, which could be any valid python statement.

>>> eval('10+12')
22
>>> eval('print("Hello World")')
Hello World
Enter fullscreen mode Exit fullscreen mode

print function

The print function is used to display a value to the console. You can directly pass a string or a number you want to be displayed, or you can pass a variable and print will display the content stored in the variable.

One thing to note here is that when we type the name of the variable in interactive mode, it displays the content within the variable, like so.

>> string = "Hello World"
>> string
Hello World

However, this won't work on shell mode. To display the value in the console, we need to use the print function.

If you want to print multiple values, separated by spaces, you can pass those values (comma separated) within the print function, like so.

>>> print("series:", 1, 2, 3, 5, 8)
series: 1 2 3 5 8
Enter fullscreen mode Exit fullscreen mode

The values passed within print function are displayed on a single line. To display values on multiple lines, we can use \n character for new line, like so.

>>> print("first line\nsecond line\nthird line")
first line
second line
third line
Enter fullscreen mode Exit fullscreen mode

\n is one of the special characters called escape sequences. Few other escape sequences are \t, \b, \f and \r. As an excercise, try using them with print statement and see how it looks.

round function

The round function is used to round off floating point numbers to a specific number of places. For ex:

>>> round(89.625, 2)
89.62
>>> round(34.12, 1)
34.1
Enter fullscreen mode Exit fullscreen mode

min and max function

The min and max functions are used to check to compare two or more numbers and return the minimum and maximum numbers among them respectively.

>>> max(59, 80, 95.6, 95.2)
95.6
>>> min(59, 80, 95.6, 95.2)
Enter fullscreen mode Exit fullscreen mode

The function requires at least two inputs to work (coz you can't just compare one number with another)

You can also compare string values with them. In case of strings, it will simply compare strings based on the ASCII value of their characters (like a < b and c < d).

>>> max('alpha', 'beta', 'gaama', 'yo')
'yo'
>>> min('alpha', 'beta', 'gaama', 'yo')
'alpha'
Enter fullscreen mode Exit fullscreen mode

You cannot compare strings with numbers using min and max function.

pow function

The pow function stands for power. It is used to find a number raised to the power of another number, like so:

>>> pow(2, 3)
8
>>> pow(3, 2)
9
Enter fullscreen mode Exit fullscreen mode

dir function

Apart from the above functions, there are some builtin function that help developer know more about other functions and data in python. There are 3 such functions we are going to discuss:

  • dir function
  • type function
  • help function

The dir function is used to list all the attributes and methods present within an object.

We haven't discussed attributes and methods yet, but you can understand them as crucial data related to that object.

Here's how the dir function output looks like:

>>> dir(2)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
Enter fullscreen mode Exit fullscreen mode

What the function represents here is a list of all the attributes and methods related to the int class object (the number we passed onto it).

We don't need to understand it yet, but this function can be really helpful in the future.

type function

The type function allows us to view the data type of the daya passed onto it. In interactive mode, this function returns a string of the format <class 'type'>, where type is replaced with the type of the data, for example:

>>> type(12)
<class 'int'>
>>> type('string')
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

help function

The help function helps display information about python modules, classes and functions. This functions is only useful in interactive mode, where it opens a help utility which shows information about the object passed onto it.

For example, passing the max function on help displays the following:

>>> help(max)
Enter fullscreen mode Exit fullscreen mode
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
(END)
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are still multiple functions we can talk about in this blog, but it would end up being too much for a single blog post. Thus, we conclude today's blog.

For those of you who want to know all the builtin functions in python, you can try running the following command in interactive mode and get surprised.

>>> dir(__builtins__)
Enter fullscreen mode Exit fullscreen mode

In the next blog post, I would talk about some more builtin functions using modules like math and random and talk about some properties of functions like composition, type conversion.

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more β†’

Top comments (0)

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay