0.1 Functions

Introduction to Functions

Just like a value can be associated with a name, a piece of logic can be given a name by defining a function. In Python, functions are defined using the def statement.

Example Code:

Output Window

Python uses indentation to identify the block of code that is part of the function. Usually 4 spaces are used as indentation.

It may look like forcing indentation is a big constraint in the beginning, but you'll not even notice it as you get used to it. In fact, every good programmer indents his code any way.

Python has a great feature called docstrings. Docstring is a string literal that occurs as the first statement in a function, used to describe the function. In Python, it is a common practice to put some examples in the docstring demonstrating how that function behaves. The following example adds a docstring with examples to the square function.

Example Code:

Output Window

In most examples and exercises, PythonMonk tries to run the examples specified in the docstring as testcases to verify the correctness of the function.

Time for an exercise. Try to implement a function cube that takes a number as argument and returns its cube.

Output Window

Once a function is defined, it can be used in other expressions or in defining new functions. The following example demonstrates the case of using already defined square function to define a new function.

Example Code:

Output Window

Now, it is your turn. Implement a function sum_of_squares that takes 2 numbers as arguments and returns sum of its squares. You should call the square function to compute square.

Output Window

Built-in functions

Python comes with some useful functions predefined.

For example, the min function computes minimum of given two numbers.

Example Code:

Output Window

And the max function computes maximum of given numbers. Try to compute the maximum of 3 and 5 by calling the max function.

The built-in function int converts a string to an integer.

Example Code:

Output Window

And the function str converts a number to a string.

Example Code:

Output Window

Write a function count_digits to find the number of digits in the given number.

Hint

You'll have to use built-in functions str and len.

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2014 by Anand Chitipothu