Python to C++, A Data Scientist’s Journey to Learning a New Language — Functions

Daniel Benson
Geek Culture
Published in
7 min readJun 28, 2021

Introduction

Welcome back, brave readers, to the next installment in the Python to C++ Series. In the last installment we learned about conditions, conditional statements, and used all our newfound knowledge to build up a simple calculator from scratch in both Python and C++. In this installation we will be taking a leap into a more advance topic as we learn the ins and outs of functions and function creation in our programming languages of interest. The raw code we will be using throughout this article can be found:

Python

C++

A Function’s Function

Those of you approaching this series with previous experience in Python (or even C++) may already be familiar with the function, making you privy to its importance in any major programming project. Often times as programmers we will find ourselves needing to repeat the same processes over and over again; rewriting the same code repeatedly throughout the program quickly becomes a monotonous time and space waster. A function allows us to build a block of code that can be called to run at any point and as many times as needed within our program.

Let’s take a look at an example by creating a simple output function that prints out “Hello readers” whenever it is called.

Python:

# Basic function that prints out hello world
def hello_world():
print("Hello readers")
# Call to the hello_world function
hello_world()

returns:

$ python3 functions.py>> Hello readers

C++:

void printHelloWorld()
{
std::cout << "Hello readers!\n";
}
// Call to the printHelloWorld function
printHelloWorld();

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> Hello readers!

The Anatomy of a Function

The requirements of a function are simple regardless of which language we wish to use. In Python the following layout must be followed:

                   |  1: All Python functions must begin by defining 
| the block of code with def
1 2 3 | 2. All Python functions must have a function
def hello_world(): | name; the function name should be all lower
4 | case with words separated by an underscore
return something | 3. Parentheses should always follow the
| function name with a colon after
| 4. All Python functions should end with a
| return statement or a print statement
| depending on the function’s use-case.

In C++ the following layout must be followed:

            1          2      3
void printHelloWorld()
4
{
5
std::cout << "Hello readers!\n";
}
----------------------------------------------------------------
1: Like Python a function in C++ must be defined; however, C++ requires the programmer to specify what data type the function will be returned: void if we just want the function to print something
out, int if we want a returned integer, string for string, double/float, etc.
2: All C++ functions must have a function name; the function name should be in the form of snake-case where the first letter of the first word is lowercase and all proceeding words are capitalized with no space between.3. Like Python the function name should be followed by parentheses the use of which will be discussed later in the article.4. Where Python requires a colon to separate the function creation from the function’s code block, C++ requires the function’s code block to be wrapped between curly braces {} — remember the main function we are required to create in every C++ program we create.5. Every C++ function must end with a print statement or by returning a data type that matches the function’s definition

When adding lines of code within a function’s code block, regardless of the programming language used, one should always indent each line of code. This helps keep code readable and is actually required in the Python programming language — failure to do so will throw an error message.

Simple Functions

We will start our jump into functions by looking at a couple of simple examples. These examples will include a function that gathers a user’s name and a function that will print out a user’s name.

Our function for gathering a user’s name will include a basic print statement asking for the user to enter their name, a variable to save the user’s input, and a return statement allowing the variable with the user’s input to be used outside of the function.

Python:

# Function that gather's a user's name
def gather_user_name():
print("What is your name?")
name = input()
return name
# Save the results of calling gather_user_name into a variable
name = gather_user_name()
# Print out the user's name
print(f"Your name is {name}!")

returns:

$ python3 functions.py>> What is your name?
>> Daniel
>> Your name is Daniel!

C++:

std::string gatherUserName()
{
std::string name;
std::cout << "What is your name?\n";
std::cin >> name;
return name;
}

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> What is your name?
>> Daniel
>> Your name is Daniel!

Our function for printing a user’s name will include a call to our previous function, a variable that saves the returned user input for use in this new function, and a print statement outputting the user’s inputted name.

Python:

# We can call a function within another function
def print_user_name():
name = gather_user_name()
print(f"Your name is {name}!")
print_user_name()

returns:

$ python3 functions.py>> What is your name?
>> Daniel
>> Your name is Daniel!

C++:

void printUserNameByCalling()
{
std::string name = gatherUserName();
std::cout << "Your name is " << name << std::endl;
}
printUserNameByCalling();

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> What is your name?
>> Daniel
>> Your name is Daniel!

Functions with Parameters

A function can also include required parameters. These are info that must be passed in when the function is called before the function will run as it is supposed to. Placement order IS important, as the values passed into the function call will be used in the order in which they appear. We will look at four examples here; a function with one parameter that prints out a user’s name; a function with two parameters that returns the sum of two numbers; a function with two parameters that returns the difference of two numbers; and a function with three parameters (one of which is given a default value) that prints out a name, age, and location.

Our first function is simple, requiring only a single parameter (name) to be passed in order to run, and a single print statement that prints out the passed-in parameter in a sentence.

Python:

# We can also pass in a parameter to a function for use within the function
def print_user_name(name):
print(f"Your name is {name}!")
name = gather_user_name()
print_user_name(name)

returns:

$ python3 functions.py>> What is your name?
>> Daniel
>> Your name is Daniel!

C++:

void printUserNameUsingParam(std::string name)
{
std::cout << "Your name is " << name << std::endl;
}
printUserNameUsingParam("Daniel");

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> Your name is Daniel

Our second and third functions each require two parameters (num1 and num2) to be passed to run. Each of these functions includes just a single line, a return statement that returns the sum of the two parameters in function two and a return statement that returns the difference of the two parameters in function three.

Python Function 2:

# We can use multiple parameters within a function
def find_sum(num1, num2):
return num1 + num2
print(find_sum(5, 7))

returns:

$ python3 functions.py>> 12

C++ Function 2:

int findSum(int num1, int num2)
{
return num1 + num2;
}
std::cout << findSum(5, 7) << std::endl;

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> 12

Python Function 3:

def find_difference(num1, num2):
return num1 - num2
print(find_difference(7, 5))

returns:

$ python3 functions.py>> 2

C++ Function 3:

int findDifference(int num1, int num2)
{
return num1 - num2;
}
std::cout << findDifference(7, 5) << std::endl;

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> 2

For functions requiring parameters there may be times where one value may be repeated more frequently in proceeding function calls or we want a value indicating that there was no given value to pass into a particular parameter; this is where default values come into play. When defining a parameter for a function we can instantiate that parameter with a default value that will automatically be set if a new value is not passed into the function’s call. When using a parameter with a given default value that parameter MUST be placed after all parameters that do not include a default value. The following example includes three parameters, one of which is given a default value. The body of the function includes three print statements, one printing a name, one printing an age, and the last printing a location.

Python:

def print_info(name, age, location="Unknown"):
print(f"Hello, your name is {name}...")
print(f"You are {age} years old...")
print(f"and you are from {location}...")
print_info("Daniel", 32)
print_info("Daniel", 32, "Utah")

returns:

$ python3 functions.py>> Hello, your name is Daniel...
>> You are 32 years old...
>> and you are from Unknown...
>> Hello, your name is Daniel
>> You are 32 years old...
>> and you are from Utah

C++:

void printInfo(std::string name, int age, std::string location="unknown")
{
std::cout << "Hello, your name is " << name << std::endl;
std::cout << "You are " << age << " years old...\n";
std::cout << "and you are from " << location << std::endl;
}
printInfo("Daniel", 32);
printInfo("Daniel", 32, "Utah");

returns:

$ g++ -o functions functions.cpp
$ ./functions
>> Hello, your name is Daniel
>> You are 32 years old...
>> and you are from unknown
>> Hello, your name is Daniel
>> You are 32 years old...
>> and you are from Utah

Thank you for joining me in another installment of Python to C++, dear readers. I hope to see you next time when we take a dive into the world of classes. As always keep on reppin’ on and happy coding.

--

--

Daniel Benson
Geek Culture

I am a Data Scientist and writer prone to excitement and passion. I look forward to a future I am able to focus those characteristics into work I love.